// InspectX Advanced Diagnostic & Control Sidecar // ================================================ // Connects to running InspectX via WCF IPC named pipes to expose ALL internal // diagnostic data: X-Ray source (cathode current, vacuum, kV/uA actual vs demand, // focus real vs demand, filament, turbo pump status, beam tube, converter faults), // Manipulator (per-axis position/target/velocity/homed/locked/limits/motor current), // and Door/Interlock status. // // Compile with build.bat or manually: // C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe /target:winexe /platform:x86 ^ // /r:System.dll /r:System.Drawing.dll /r:System.Windows.Forms.dll ^ // /r:System.ServiceModel.dll /r:System.Runtime.Serialization.dll ^ // /r:IpcContract.dll /r:IpcContractClientInterface.dll ^ // /out:InspectXDiagnostic.exe InspectXDiagnostic.cs using System; using System.Drawing; using System.Windows.Forms; using System.ServiceModel; using System.Text; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using IpcContract; namespace InspectXDiagnostic { // ==================== Main Form ==================== public class DiagnosticForm : Form { // Connection state - uses official IpcContractClientInterface wrappers private IpcContractClientInterface.CommunicationsChannel_XRay xrayChannel; private IpcContractClientInterface.CommunicationsChannel_Manipulator manipChannel; private IpcContractClientInterface.CommunicationsChannel_Application appChannel; // Image-processing channel - intensifier, detector params, image commands. // Optional: connect failure here is tolerated so the existing XRay / // Manipulator workflow keeps working on installs that don't expose IP. private IpcContractClientInterface.CommunicationsChannel_ImageProcessing imageChannel; private bool imageConnected = false; private bool connected = false; // UI elements private System.Windows.Forms.Timer refreshTimer; private TabControl tabControl; private StatusStrip statusStrip; private ToolStripStatusLabel statusLabel; private ToolStripStatusLabel connectionLabel; // X-Ray tab controls private Label lblKvActual, lblKvDemand, lblUaActual, lblUaDemand; private Label lblPowerActual, lblPowerDemand, lblXrayState; private Label lblCathodeCurrent, lblFocusReal, lblVacuum; private Label lblFilamentOperative, lblFilamentMax, lblFilamentMin, lblFilamentDemand; private Label lblBeamTube, lblTurboSpeed, lblTurboFault, lblVacuumSetPoint; private Label lblOverConverterAmps, lblOverConverterVolts, lblOverkV, lblOvermA; private Label lblInterlockXray, lblControllerType, lblControllerVersion, lblControllerReady; private Label lblHoursOn, lblFocusMode, lblModulation; private Label lblHeadType, lblHeadMaxKv, lblHeadMaxUa, lblHeadMaxW; private Label lblXShift, lblYShift, lblFocus; private Label lblExposureMode, lblExposurePeriod, lblExposureRemaining; private Label lblFsdVolts, lblFsdAmps; private ProgressBar pbKv, pbUa; // Manipulator tab controls private DataGridView dgvAxes; private Label lblManipInterlock, lblJoysticks, lblManipReady, lblManipType; private Label lblMagnification, lblSampleHeight, lblMaxSampleHeight; private Label lblDoorState, lblDoorFitted, lblDoorOutcome, lblDoorInterlocks; private Label lblDoorServiceMode, lblDoorTimeout, lblDoorServiceTimeout, lblDoorIsOpen, lblDoorIsClosed, lblAtLoadPosition; private Label lblOrbitSpeed; // X-Ray control tab private NumericUpDown nudKvSet, nudUaSet, nudPowerSet; private Button btnXrayOn, btnXrayOff; private NumericUpDown nudFilament, nudFocus, nudXShift, nudYShift; private ShiftPad shiftPad; private Label lblShiftPadReadout; private string lastShiftPadError = ""; // Manipulator control tab private ComboBox cmbAxis; private NumericUpDown nudAxisTarget, nudAxisSpeed; private Button btnAxisGo, btnAxisHome, btnStopAll, btnLoadPosition; private CheckBox chkJoysticks; private NumericUpDown nudOrbitSpeed; private RichTextBox txtNativeNotes; // Intensifier / ImageProcessing tab controls private Label lblIntStatus, lblIntChannelOpen, lblIntGetStatus; private Label lblIntFieldCount, lblIntFieldCurrent, lblIntFieldStatusCount, lblIntFieldStatusCurrent; private Label lblIntControllerReady, lblIntControllerComms, lblIntControllerType, lblIntControllerVersion; private Label lblIntControllerMode, lblIntControllerVisible; private Label lblIntDetectorName, lblIntDetectorSize, lblIntDetectorResolution; private Label lblIntImageLiveAvailable, lblIntImageLiveActive, lblIntGeometryDsd; private ComboBox cmbIntField; private CheckBox chkIntMirrorReadback; private Button btnIntSetField, btnIntRefresh, btnIntProbeFields, btnIntLogInterfaces; private Button btnIntControllerInitialise, btnIntControllerClose; private NumericUpDown nudIntExposure, nudIntGain, nudIntDigGain; private NumericUpDown nudIntBrightness, nudIntBinning, nudIntAccum; private Label lblIntExpRead, lblIntGainRead, lblIntDigGainRead; private Label lblIntBrightRead, lblIntBinningRead, lblIntAccumRead; private Button btnIntApplyDet; private Button btnIntLive, btnIntCapture, btnIntAverage, btnIntSaveTiff; private NumericUpDown nudIntAvgFrames; private RichTextBox txtIntDiag; private uint cachedFieldCount = UInt32.MaxValue; // Direct intensifier-field path. This bypasses ImageProcessing IPC and // uses InspectXUtilities.MiscIO -> native MiscIO.dll directly by reflection. // It is intentionally write-only because MiscIO exposes IntensifierField // as a setter only. private object directMiscIO = null; private Label lblDirectMiscIOStatus; private ComboBox cmbDirectField; private Button btnDirectInit, btnDirectWrite, btnDirectRelease; private ComboBox cmbDirectToggleInterval; private Button btnDirectToggleStart, btnDirectToggleStop; private Label lblDirectToggleStatus; private System.Windows.Forms.Timer directFieldToggleTimer; private bool directFieldToggleState = false; private int directFieldToggleWrites = 0; // Direct MiscIO readout/control tab. Uses the same InspectXUtilities.MiscIO object // as the direct intensifier controls above. Imaging.dll uses this same path for // intensifier field and iris demand when UseMiscIO is enabled. private Label lblMiscIOStatus, lblMiscDigitalRead, lblMiscAnalogRead, lblMiscIrisStatus; private NumericUpDown nudMiscDigitalIndex, nudMiscDigitalValue; private NumericUpDown nudMiscAnalogIndex, nudMiscAnalogValue; private NumericUpDown nudMiscIrisPercent, nudMiscIrisScaling; private Button btnMiscOpen, btnMiscRelease, btnMiscDigitalRead, btnMiscDigitalWrite; private Button btnMiscAnalogRead, btnMiscAnalogWrite, btnMiscIrisWrite, btnMiscSnapshot; private RichTextBox txtMiscIODiag; // Native motion / lower DLL tab. Uses direct LoadLibrary/GetProcAddress // and signatures recovered from Manipulator.dll P/Invoke metadata. private NativeMotionController nativeMotion = null; private Label lblNativeMotionStatus; private TextBox txtNativeMotionDllDir; private ComboBox cmbNativeMotionDll, cmbNativeMotionAxis; private NumericUpDown nudNativeInitArg, nudNativeAxisBase; private NumericUpDown nudNativeMoveTarget, nudNativeMoveSpeed, nudNativeVelocity; private NumericUpDown nudNativeNode, nudNativeNodeOutput; private DataGridView dgvNativeMotionAxes; private RichTextBox txtNativeMotionLog; // Log tab private RichTextBox txtLog; private int refreshCount = 0; public DiagnosticForm() { InitializeComponent(); this.Load += DiagnosticForm_Load; } private void InitializeComponent() { this.Text = "InspectX Advanced Diagnostics & Control"; this.Size = new Size(1100, 800); this.MinimumSize = new Size(900, 600); this.StartPosition = FormStartPosition.CenterScreen; this.Font = new Font("Segoe UI", 9f); this.Icon = SystemIcons.Information; // Status strip statusStrip = new StatusStrip(); statusLabel = new ToolStripStatusLabel("Initializing..."); statusLabel.Spring = true; statusLabel.TextAlign = ContentAlignment.MiddleLeft; connectionLabel = new ToolStripStatusLabel("Disconnected"); connectionLabel.ForeColor = Color.Red; statusStrip.Items.AddRange(new ToolStripItem[] { statusLabel, connectionLabel }); this.Controls.Add(statusStrip); // Menu strip MenuStrip menuStrip = new MenuStrip(); ToolStripMenuItem fileMenu = new ToolStripMenuItem("&File"); ToolStripMenuItem connectItem = new ToolStripMenuItem("&Connect", null, (s, e) => Connect()); connectItem.ShortcutKeys = Keys.F5; ToolStripMenuItem disconnectItem = new ToolStripMenuItem("&Disconnect", null, (s, e) => Disconnect()); ToolStripMenuItem exportItem = new ToolStripMenuItem("&Export Log...", null, (s, e) => ExportLog()); exportItem.ShortcutKeys = Keys.Control | Keys.S; ToolStripMenuItem exitItem = new ToolStripMenuItem("E&xit", null, (s, e) => Close()); fileMenu.DropDownItems.AddRange(new ToolStripItem[] { connectItem, disconnectItem, new ToolStripSeparator(), exportItem, new ToolStripSeparator(), exitItem }); ToolStripMenuItem viewMenu = new ToolStripMenuItem("&View"); ToolStripMenuItem refreshItem = new ToolStripMenuItem("&Refresh Now", null, (s, e) => RefreshAll()); ToolStripMenuItem autoRefreshItem = new ToolStripMenuItem("&Auto Refresh (500ms)"); autoRefreshItem.CheckOnClick = true; autoRefreshItem.Checked = true; autoRefreshItem.Click += (s, e) => { refreshTimer.Enabled = autoRefreshItem.Checked; }; viewMenu.DropDownItems.AddRange(new ToolStripItem[] { refreshItem, autoRefreshItem }); menuStrip.Items.AddRange(new ToolStripMenuItem[] { fileMenu, viewMenu }); this.MainMenuStrip = menuStrip; this.Controls.Add(menuStrip); // Tab control tabControl = new TabControl(); tabControl.Dock = DockStyle.Fill; tabControl.TabPages.Add(CreateXrayStatusTab()); tabControl.TabPages.Add(CreateManipulatorStatusTab()); tabControl.TabPages.Add(CreateXrayControlTab()); tabControl.TabPages.Add(CreateManipulatorControlTab()); tabControl.TabPages.Add(CreateIntensifierTab()); tabControl.TabPages.Add(CreateMiscIOTab()); tabControl.TabPages.Add(CreateNativeMotionTab()); tabControl.TabPages.Add(CreateLowLevelTab()); tabControl.TabPages.Add(CreateLogTab()); this.Controls.Add(tabControl); tabControl.BringToFront(); // Timer refreshTimer = new System.Windows.Forms.Timer(); refreshTimer.Interval = 500; refreshTimer.Tick += (s, e) => RefreshAll(); } // ==================== X-Ray Status Tab ==================== private TabPage CreateXrayStatusTab() { TabPage tab = new TabPage("X-Ray Status"); tab.AutoScroll = true; tab.Padding = new Padding(8); TableLayoutPanel mainLayout = new TableLayoutPanel(); mainLayout.Dock = DockStyle.Fill; mainLayout.ColumnCount = 3; mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35)); mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35)); mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30)); mainLayout.RowCount = 3; mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 40)); mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 30)); mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 30)); // === Panel 1: Core X-Ray Readings === GroupBox gbCore = CreateGroupBox("Core X-Ray Readings"); TableLayoutPanel pCore = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 3, RowCount = 10, AutoScroll = true }; pCore.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40)); pCore.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30)); pCore.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30)); int row = 0; AddHeaderRow(pCore, row++, "Parameter", "Actual", "Demand"); lblKvActual = AddValueRow(pCore, row, "Kilovolts (kV)", out lblKvDemand); row++; lblUaActual = AddValueRow(pCore, row, "Microamps (µA)", out lblUaDemand); row++; lblPowerActual = AddValueRow(pCore, row, "Power (W)", out lblPowerDemand); row++; pCore.Controls.Add(CreateLabel("kV"), 0, row); pbKv = new ProgressBar { Dock = DockStyle.Fill, Maximum = 160 }; pCore.SetColumnSpan(pbKv, 2); pCore.Controls.Add(pbKv, 1, row); row++; pCore.Controls.Add(CreateLabel("µA"), 0, row); pbUa = new ProgressBar { Dock = DockStyle.Fill, Maximum = 1000 }; pCore.SetColumnSpan(pbUa, 2); pCore.Controls.Add(pbUa, 1, row); row++; pCore.Controls.Add(CreateLabel("X-Ray State"), 0, row); lblXrayState = CreateValueLabel(Color.DarkRed); pCore.SetColumnSpan(lblXrayState, 2); pCore.Controls.Add(lblXrayState, 1, row); row++; pCore.Controls.Add(CreateLabel("Interlock"), 0, row); lblInterlockXray = CreateValueLabel(Color.DarkRed); pCore.SetColumnSpan(lblInterlockXray, 2); pCore.Controls.Add(lblInterlockXray, 1, row); row++; gbCore.Controls.Add(pCore); mainLayout.Controls.Add(gbCore, 0, 0); // === Panel 2: Xodiac Source Diagnostics === GroupBox gbXodiac = CreateGroupBox("Xodiac Source Diagnostics"); TableLayoutPanel pXodiac = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 12, AutoScroll = true }; pXodiac.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 55)); pXodiac.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); row = 0; lblCathodeCurrent = AddDiagRow(pXodiac, row++, "Cathode Current"); lblFocusReal = AddDiagRow(pXodiac, row++, "Focus Real"); lblVacuum = AddDiagRow(pXodiac, row++, "Vacuum Level"); lblVacuumSetPoint = AddDiagRow(pXodiac, row++, "Vacuum Set Point"); lblFilamentOperative = AddDiagRow(pXodiac, row++, "Filament Operative"); lblFilamentMax = AddDiagRow(pXodiac, row++, "Filament Max"); lblFilamentMin = AddDiagRow(pXodiac, row++, "Filament Min"); lblFilamentDemand = AddDiagRow(pXodiac, row++, "Filament Demand"); lblFsdVolts = AddDiagRow(pXodiac, row++, "FSD Volts"); lblFsdAmps = AddDiagRow(pXodiac, row++, "FSD Amps"); lblHoursOn = AddDiagRow(pXodiac, row++, "Source Hours On"); gbXodiac.Controls.Add(pXodiac); mainLayout.Controls.Add(gbXodiac, 1, 0); // === Panel 3: Protection & Fault Status === GroupBox gbFaults = CreateGroupBox("Protection & Fault Status"); TableLayoutPanel pFaults = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 8, AutoScroll = true }; pFaults.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 60)); pFaults.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40)); row = 0; lblBeamTube = AddDiagRow(pFaults, row++, "Beam Tube Good"); lblTurboSpeed = AddDiagRow(pFaults, row++, "Turbo At Speed"); lblTurboFault = AddDiagRow(pFaults, row++, "Turbo Fault"); lblOverConverterAmps = AddDiagRow(pFaults, row++, "Over Converter Amps"); lblOverConverterVolts = AddDiagRow(pFaults, row++, "Over Converter Volts"); lblOverkV = AddDiagRow(pFaults, row++, "Over kV"); lblOvermA = AddDiagRow(pFaults, row++, "Over mA"); lblModulation = AddDiagRow(pFaults, row++, "Modulation"); gbFaults.Controls.Add(pFaults); mainLayout.Controls.Add(gbFaults, 2, 0); // === Panel 4: Controller Info === GroupBox gbController = CreateGroupBox("Controller Info"); TableLayoutPanel pCtrl = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 5 }; pCtrl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); pCtrl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 55)); row = 0; lblControllerType = AddDiagRow(pCtrl, row++, "Controller Type"); lblControllerVersion = AddDiagRow(pCtrl, row++, "Version"); lblControllerReady = AddDiagRow(pCtrl, row++, "Ready"); gbController.Controls.Add(pCtrl); mainLayout.Controls.Add(gbController, 0, 1); // === Panel 5: Head Info === GroupBox gbHead = CreateGroupBox("X-Ray Head"); TableLayoutPanel pHead = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 5 }; pHead.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); pHead.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 55)); row = 0; lblHeadType = AddDiagRow(pHead, row++, "Head Type"); lblHeadMaxKv = AddDiagRow(pHead, row++, "Max kV"); lblHeadMaxUa = AddDiagRow(pHead, row++, "Max µA"); lblHeadMaxW = AddDiagRow(pHead, row++, "Max Power (W)"); gbHead.Controls.Add(pHead); mainLayout.Controls.Add(gbHead, 1, 1); // === Panel 6: Focus & Exposure === GroupBox gbFocus = CreateGroupBox("Focus / Shift / Exposure Timer"); TableLayoutPanel pFocus = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 7 }; pFocus.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); pFocus.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); row = 0; lblFocusMode = AddDiagRow(pFocus, row++, "Focus Mode"); lblFocus = AddDiagRow(pFocus, row++, "Focus"); lblXShift = AddDiagRow(pFocus, row++, "X Shift"); lblYShift = AddDiagRow(pFocus, row++, "Y Shift"); lblExposureMode = AddDiagRow(pFocus, row++, "Exposure Mode"); lblExposurePeriod = AddDiagRow(pFocus, row++, "Exposure Period (s)"); lblExposureRemaining = AddDiagRow(pFocus, row++, "Exposure Remain (s)"); gbFocus.Controls.Add(pFocus); mainLayout.Controls.Add(gbFocus, 2, 1); tab.Controls.Add(mainLayout); return tab; } // ==================== Manipulator Status Tab ==================== private TabPage CreateManipulatorStatusTab() { TabPage tab = new TabPage("Manipulator Status"); tab.Padding = new Padding(8); TableLayoutPanel mainLayout = new TableLayoutPanel(); mainLayout.Dock = DockStyle.Fill; mainLayout.RowCount = 2; mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 55)); mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 45)); mainLayout.ColumnCount = 1; mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); // Axis data grid GroupBox gbAxes = CreateGroupBox("Axis Status (All Axes)"); dgvAxes = new DataGridView(); dgvAxes.Dock = DockStyle.Fill; dgvAxes.AllowUserToAddRows = false; dgvAxes.AllowUserToDeleteRows = false; dgvAxes.ReadOnly = true; dgvAxes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dgvAxes.RowHeadersVisible = false; dgvAxes.BackgroundColor = Color.White; dgvAxes.DefaultCellStyle.Font = new Font("Consolas", 9f); dgvAxes.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(240, 245, 255); dgvAxes.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(70, 130, 180); dgvAxes.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; dgvAxes.ColumnHeadersDefaultCellStyle.Font = new Font("Segoe UI", 9f, FontStyle.Bold); dgvAxes.EnableHeadersVisualStyles = false; dgvAxes.Columns.Add("Axis", "Axis"); dgvAxes.Columns.Add("Position", "Position (mm)"); dgvAxes.Columns.Add("Target", "Target (mm)"); dgvAxes.Columns.Add("Velocity", "Velocity"); dgvAxes.Columns.Add("Available", "Available"); dgvAxes.Columns.Add("Homed", "Homed"); dgvAxes.Columns.Add("HomeSwitch", "Home Switch"); dgvAxes.Columns.Add("Locked", "Locked"); dgvAxes.Columns.Add("MotorCurrent", "Motor Current"); dgvAxes.Columns.Add("RelativePosition", "Rel Pos"); dgvAxes.Columns.Add("RelativeZero", "Rel Zero"); dgvAxes.Columns.Add("TravelMin", "Travel Min"); dgvAxes.Columns.Add("TravelMax", "Travel Max"); dgvAxes.Columns.Add("Programmable", "Programmable"); gbAxes.Controls.Add(dgvAxes); mainLayout.Controls.Add(gbAxes, 0, 0); // Bottom panels TableLayoutPanel bottomLayout = new TableLayoutPanel(); bottomLayout.Dock = DockStyle.Fill; bottomLayout.ColumnCount = 4; bottomLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25)); bottomLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25)); bottomLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25)); bottomLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25)); bottomLayout.RowCount = 1; bottomLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // Controller Info GroupBox gbManipCtrl = CreateGroupBox("Controller"); TableLayoutPanel pManipCtrl = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 4 }; pManipCtrl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); pManipCtrl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 55)); int row2 = 0; lblManipType = AddDiagRow(pManipCtrl, row2++, "Type"); lblManipReady = AddDiagRow(pManipCtrl, row2++, "Ready"); lblManipInterlock = AddDiagRow(pManipCtrl, row2++, "Interlocks"); lblJoysticks = AddDiagRow(pManipCtrl, row2++, "Joysticks"); gbManipCtrl.Controls.Add(pManipCtrl); bottomLayout.Controls.Add(gbManipCtrl, 0, 0); // Geometry GroupBox gbGeom = CreateGroupBox("Geometry"); TableLayoutPanel pGeom = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 3 }; pGeom.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 55)); pGeom.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); row2 = 0; lblMagnification = AddDiagRow(pGeom, row2++, "Magnification"); lblSampleHeight = AddDiagRow(pGeom, row2++, "Sample Height"); lblMaxSampleHeight = AddDiagRow(pGeom, row2++, "Max Sample H."); gbGeom.Controls.Add(pGeom); bottomLayout.Controls.Add(gbGeom, 1, 0); // Door GroupBox gbDoor = CreateGroupBox("Door / Load Status"); TableLayoutPanel pDoor = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 10, AutoScroll = true }; pDoor.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); pDoor.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); row2 = 0; lblDoorState = AddDiagRow(pDoor, row2++, "State"); lblDoorFitted = AddDiagRow(pDoor, row2++, "Fitted"); lblDoorInterlocks = AddDiagRow(pDoor, row2++, "Interlocks"); lblDoorOutcome = AddDiagRow(pDoor, row2++, "Last Outcome"); lblDoorServiceMode = AddDiagRow(pDoor, row2++, "Service Mode"); lblDoorTimeout = AddDiagRow(pDoor, row2++, "Timeout"); lblDoorServiceTimeout = AddDiagRow(pDoor, row2++, "Svc Timeout"); lblDoorIsOpen = AddDiagRow(pDoor, row2++, "Is Open"); lblDoorIsClosed = AddDiagRow(pDoor, row2++, "Is Closed"); lblAtLoadPosition = AddDiagRow(pDoor, row2++, "At Load Pos"); gbDoor.Controls.Add(pDoor); bottomLayout.Controls.Add(gbDoor, 2, 0); // Orbit GroupBox gbOrbit = CreateGroupBox("Orbit"); TableLayoutPanel pOrbit = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 1 }; pOrbit.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); pOrbit.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); lblOrbitSpeed = AddDiagRow(pOrbit, 0, "Speed"); gbOrbit.Controls.Add(pOrbit); bottomLayout.Controls.Add(gbOrbit, 3, 0); mainLayout.Controls.Add(bottomLayout, 0, 1); tab.Controls.Add(mainLayout); return tab; } // ==================== X-Ray Control Tab ==================== private TabPage CreateXrayControlTab() { TabPage tab = new TabPage("X-Ray Control"); tab.Padding = new Padding(12); TableLayoutPanel main = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 2 }; main.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); main.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); main.RowStyles.Add(new RowStyle(SizeType.Percent, 50)); main.RowStyles.Add(new RowStyle(SizeType.Percent, 50)); // Generation control GroupBox gbGen = CreateGroupBox("X-Ray Generation"); FlowLayoutPanel fpGen = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, AutoScroll = true, WrapContents = false }; btnXrayOn = new Button { Text = "X-Rays ON", Size = new Size(180, 35), BackColor = Color.FromArgb(76, 175, 80), ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; btnXrayOn.Click += (s, e) => SafeCall(() => { xrayChannel.XRays.GenerationDemand(true); Log("X-Rays ON commanded"); }); btnXrayOff = new Button { Text = "X-Rays OFF", Size = new Size(180, 35), BackColor = Color.FromArgb(244, 67, 54), ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; btnXrayOff.Click += (s, e) => SafeCall(() => { xrayChannel.XRays.GenerationDemand(false); Log("X-Rays OFF commanded"); }); fpGen.Controls.AddRange(new Control[] { btnXrayOn, btnXrayOff }); gbGen.Controls.Add(fpGen); main.Controls.Add(gbGen, 0, 0); // Set points GroupBox gbSet = CreateGroupBox("Set Points"); TableLayoutPanel pSet = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 3, RowCount = 5 }; pSet.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35)); pSet.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); pSet.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20)); nudKvSet = new NumericUpDown { Minimum = 0, Maximum = 225, DecimalPlaces = 0, Dock = DockStyle.Fill }; nudUaSet = new NumericUpDown { Minimum = 0, Maximum = 2000, DecimalPlaces = 0, Dock = DockStyle.Fill }; nudPowerSet = new NumericUpDown { Minimum = 0, Maximum = 100, DecimalPlaces = 1, Dock = DockStyle.Fill }; pSet.Controls.Add(CreateLabel("kV Demand"), 0, 0); pSet.Controls.Add(nudKvSet, 1, 0); Button btnSetKv = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetKv.Click += (s, e) => SafeCall(() => { xrayChannel.XRays.KilovoltsDemand((uint)nudKvSet.Value); Log("kV set to " + nudKvSet.Value); }); pSet.Controls.Add(btnSetKv, 2, 0); pSet.Controls.Add(CreateLabel("µA Demand"), 0, 1); pSet.Controls.Add(nudUaSet, 1, 1); Button btnSetUa = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetUa.Click += (s, e) => SafeCall(() => { xrayChannel.XRays.MicroampsDemand((uint)nudUaSet.Value); Log("µA set to " + nudUaSet.Value); }); pSet.Controls.Add(btnSetUa, 2, 1); pSet.Controls.Add(CreateLabel("Power (W)"), 0, 2); pSet.Controls.Add(nudPowerSet, 1, 2); Button btnSetPow = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetPow.Click += (s, e) => SafeCall(() => { xrayChannel.XRays.WattsDemand((double)nudPowerSet.Value); Log("Power set to " + nudPowerSet.Value + " W"); }); pSet.Controls.Add(btnSetPow, 2, 2); gbSet.Controls.Add(pSet); main.Controls.Add(gbSet, 1, 0); // Source parameters GroupBox gbSrc = CreateGroupBox("Focus and X/Y Shift"); TableLayoutPanel pSrc = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 3, RowCount = 7 }; pSrc.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 28)); pSrc.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 52)); pSrc.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20)); nudFilament = new NumericUpDown { Minimum = 0, Maximum = 100, DecimalPlaces = 0, Dock = DockStyle.Fill }; nudFocus = new NumericUpDown { Minimum = 1, Maximum = 999, DecimalPlaces = 0, Dock = DockStyle.Fill }; nudXShift = new NumericUpDown { Minimum = -99, Maximum = 99, DecimalPlaces = 0, Dock = DockStyle.Fill }; nudYShift = new NumericUpDown { Minimum = -99, Maximum = 99, DecimalPlaces = 0, Dock = DockStyle.Fill }; pSrc.Controls.Add(CreateLabel("Filament"), 0, 0); pSrc.Controls.Add(nudFilament, 1, 0); Button btnSetFil = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetFil.Click += (s, e) => SafeCall(() => { xrayChannel.XRaySource.FilamentDemand((int)nudFilament.Value); Log("Filament set to " + nudFilament.Value); }); pSrc.Controls.Add(btnSetFil, 2, 0); pSrc.Controls.Add(CreateLabel("Focus"), 0, 1); pSrc.Controls.Add(nudFocus, 1, 1); Button btnSetFocus = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetFocus.Click += (s, e) => SafeCall(() => SetFocusDemand((int)nudFocus.Value)); pSrc.Controls.Add(btnSetFocus, 2, 1); lblShiftPadReadout = CreateValueLabel(Color.FromArgb(0, 80, 120)); lblShiftPadReadout.Text = "X 0 / Y 0"; pSrc.Controls.Add(CreateLabel("X/Y Shift Pad"), 0, 2); pSrc.Controls.Add(lblShiftPadReadout, 1, 2); Button btnCenterShift = new Button { Text = "Center", Dock = DockStyle.Fill }; btnCenterShift.Click += (s, e) => SafeCall(() => SetShiftValues(0, 0, true)); pSrc.Controls.Add(btnCenterShift, 2, 2); shiftPad = new ShiftPad { Dock = DockStyle.Fill, Minimum = -99, Maximum = 99 }; shiftPad.ValueChanged += (s, e) => SetShiftValuesFromPad(); pSrc.SetColumnSpan(shiftPad, 3); pSrc.Controls.Add(shiftPad, 0, 3); pSrc.RowStyles.Add(new RowStyle(SizeType.Absolute, 26)); pSrc.RowStyles.Add(new RowStyle(SizeType.Absolute, 26)); pSrc.RowStyles.Add(new RowStyle(SizeType.Absolute, 26)); pSrc.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); pSrc.Controls.Add(CreateLabel("Exact X Shift"), 0, 4); pSrc.Controls.Add(nudXShift, 1, 4); Button btnSetXS = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetXS.Click += (s, e) => SafeCall(() => SetShiftValues((int)nudXShift.Value, (int)nudYShift.Value, true)); pSrc.Controls.Add(btnSetXS, 2, 4); pSrc.Controls.Add(CreateLabel("Exact Y Shift"), 0, 5); pSrc.Controls.Add(nudYShift, 1, 5); Button btnSetYS = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSetYS.Click += (s, e) => SafeCall(() => SetShiftValues((int)nudXShift.Value, (int)nudYShift.Value, true)); pSrc.Controls.Add(btnSetYS, 2, 5); Label lblLiveNote = CreateLabel("Dragging writes X/Y shift immediately through the Inspect-X IPC controller."); pSrc.SetColumnSpan(lblLiveNote, 3); pSrc.Controls.Add(lblLiveNote, 0, 6); gbSrc.Controls.Add(pSrc); main.Controls.Add(gbSrc, 0, 1); // Head configuration GroupBox gbHeadCtrl = CreateGroupBox("Head Configuration"); TableLayoutPanel pHC = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 3, RowCount = 5 }; pHC.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35)); pHC.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); pHC.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20)); NumericUpDown nudHeadMaxKv = new NumericUpDown { Minimum = 0, Maximum = 225, Dock = DockStyle.Fill }; NumericUpDown nudHeadMaxUa = new NumericUpDown { Minimum = 0, Maximum = 2000, Dock = DockStyle.Fill }; NumericUpDown nudHeadMaxW = new NumericUpDown { Minimum = 0, Maximum = 200, Dock = DockStyle.Fill }; pHC.Controls.Add(CreateLabel("Max kV"), 0, 0); pHC.Controls.Add(nudHeadMaxKv, 1, 0); Button btnHKv = new Button { Text = "Set", Dock = DockStyle.Fill }; btnHKv.Click += (s, e) => SafeCall(() => { xrayChannel.Head.MaximumKilovolts((uint)nudHeadMaxKv.Value); Log("Head Max kV set to " + nudHeadMaxKv.Value); }); pHC.Controls.Add(btnHKv, 2, 0); pHC.Controls.Add(CreateLabel("Max µA"), 0, 1); pHC.Controls.Add(nudHeadMaxUa, 1, 1); Button btnHUa = new Button { Text = "Set", Dock = DockStyle.Fill }; btnHUa.Click += (s, e) => SafeCall(() => { xrayChannel.Head.MaximumMicroamps((uint)nudHeadMaxUa.Value); Log("Head Max µA set to " + nudHeadMaxUa.Value); }); pHC.Controls.Add(btnHUa, 2, 1); pHC.Controls.Add(CreateLabel("Max Watts"), 0, 2); pHC.Controls.Add(nudHeadMaxW, 1, 2); Button btnHW = new Button { Text = "Set", Dock = DockStyle.Fill }; btnHW.Click += (s, e) => SafeCall(() => { xrayChannel.Head.MaximumWatts((uint)nudHeadMaxW.Value); Log("Head Max Watts set to " + nudHeadMaxW.Value); }); pHC.Controls.Add(btnHW, 2, 2); gbHeadCtrl.Controls.Add(pHC); main.Controls.Add(gbHeadCtrl, 1, 1); tab.Controls.Add(main); return tab; } // ==================== Manipulator Control Tab ==================== private TabPage CreateManipulatorControlTab() { TabPage tab = new TabPage("Manipulator Control"); tab.Padding = new Padding(12); TableLayoutPanel main = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 2 }; main.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); main.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); main.RowStyles.Add(new RowStyle(SizeType.Percent, 50)); main.RowStyles.Add(new RowStyle(SizeType.Percent, 50)); // Axis movement GroupBox gbMove = CreateGroupBox("Axis Movement"); FlowLayoutPanel fpMove = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, WrapContents = false, AutoScroll = true }; Panel pAxisSel = new Panel { Size = new Size(420, 30) }; pAxisSel.Controls.Add(CreatePanelLabel("Axis:", 0, 4, 95)); cmbAxis = new ComboBox { Location = new Point(100, 0), Width = 220, DropDownStyle = ComboBoxStyle.DropDownList }; cmbAxis.Items.AddRange(new object[] { "X", "Y", "Z / Magnification", "Tilt", "Rotate", "Detector" }); cmbAxis.SelectedIndex = 0; pAxisSel.Controls.Add(cmbAxis); fpMove.Controls.Add(pAxisSel); Panel pTarget = new Panel { Size = new Size(420, 30) }; pTarget.Controls.Add(CreatePanelLabel("Target:", 0, 4, 95)); nudAxisTarget = new NumericUpDown { Location = new Point(100, 0), Width = 120, Minimum = -9999, Maximum = 9999, DecimalPlaces = 3 }; pTarget.Controls.Add(nudAxisTarget); fpMove.Controls.Add(pTarget); Panel pSpeed = new Panel { Size = new Size(420, 30) }; pSpeed.Controls.Add(CreatePanelLabel("Speed:", 0, 4, 95)); nudAxisSpeed = new NumericUpDown { Location = new Point(100, 0), Width = 120, Minimum = 0, Maximum = 100000, DecimalPlaces = 3 }; pSpeed.Controls.Add(nudAxisSpeed); Label lblSpeedHint = new Label { Text = "0 = leave current controller speed", Location = new Point(230, 4), Width = 185, Font = new Font("Segoe UI", 8f), ForeColor = Color.DimGray }; pSpeed.Controls.Add(lblSpeedHint); fpMove.Controls.Add(pSpeed); btnAxisGo = new Button { Text = "GO to Target", Size = new Size(180, 35), BackColor = Color.FromArgb(76, 175, 80), ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; btnAxisGo.Click += (s, e) => SafeCall(() => { IpcContract.Manipulator.EAxisName axis = GetSelectedAxis(); float target = (float)nudAxisTarget.Value; double speed = (double)nudAxisSpeed.Value; if (speed > 0) { TryAxisWrite(axis, speed, "Speed", "Velocity", "TargetVelocity", "MoveSpeed", "SpeedPercentage"); } manipChannel.Axis.Target(axis, target); manipChannel.Axis.Go(axis); Log("Axis " + axis + " GO to " + target + " mm" + (speed > 0 ? (" at requested speed " + speed) : " using current controller speed")); }); fpMove.Controls.Add(btnAxisGo); btnAxisHome = new Button { Text = "HOME Selected Axis", Size = new Size(180, 35), BackColor = Color.FromArgb(255, 152, 0), ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; btnAxisHome.Click += (s, e) => SafeCall(() => { IpcContract.Manipulator.EAxisName axis = GetSelectedAxis(); manipChannel.Axis.Home(axis, true, false); Log("Homing axis " + axis); }); fpMove.Controls.Add(btnAxisHome); gbMove.Controls.Add(fpMove); main.Controls.Add(gbMove, 0, 0); // Safety controls GroupBox gbSafety = CreateGroupBox("Safety & Global Controls"); FlowLayoutPanel fpSafe = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, WrapContents = false }; btnStopAll = new Button { Text = "STOP ALL AXES", Size = new Size(220, 45), BackColor = Color.FromArgb(244, 67, 54), ForeColor = Color.White, FlatStyle = FlatStyle.Flat, Font = new Font("Segoe UI", 11f, FontStyle.Bold) }; btnStopAll.Click += (s, e) => SafeCall(() => { manipChannel.Axes.Stop(); Log("ALL AXES STOPPED"); }); fpSafe.Controls.Add(btnStopAll); btnLoadPosition = new Button { Text = "Go to LOAD Position", Size = new Size(220, 35), BackColor = Color.FromArgb(33, 150, 243), ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; btnLoadPosition.Click += (s, e) => SafeCall(() => { manipChannel.Misc.LoadPositionGo(true); Log("Moving to load position"); }); fpSafe.Controls.Add(btnLoadPosition); Button btnFilamentPos = new Button { Text = "Go to Filament Change Pos", Size = new Size(220, 35), BackColor = Color.FromArgb(156, 39, 176), ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; btnFilamentPos.Click += (s, e) => SafeCall(() => { manipChannel.Misc.FilamentChangePositionGo(); Log("Moving to filament change position"); }); fpSafe.Controls.Add(btnFilamentPos); chkJoysticks = new CheckBox { Text = "Enable Joysticks", Size = new Size(200, 25), Margin = new Padding(3, 10, 3, 3) }; chkJoysticks.CheckedChanged += (s, e) => SafeCall(() => { manipChannel.Style.JoysticksEnable(chkJoysticks.Checked); Log("Joysticks " + (chkJoysticks.Checked ? "enabled" : "disabled")); }); fpSafe.Controls.Add(chkJoysticks); gbSafety.Controls.Add(fpSafe); main.Controls.Add(gbSafety, 1, 0); // Axis Locking GroupBox gbLock = CreateGroupBox("Axis Lock/Unlock"); FlowLayoutPanel fpLock = new FlowLayoutPanel { Dock = DockStyle.Fill, AutoScroll = true }; foreach (string axName in new[] { "X", "Y", "Mag", "Tilt", "Rotate", "Det" }) { IpcContract.Manipulator.EAxisName axEnum = AxisNameFromString(axName); Button btnLock = new Button { Text = "Lock " + axName, Size = new Size(90, 28), Tag = new object[] { axEnum, true } }; btnLock.Click += (s, e) => SafeCall(() => { object[] tag = (object[])((Button)s).Tag; manipChannel.Axis.Lock((IpcContract.Manipulator.EAxisName)tag[0], (bool)tag[1]); Log("Axis " + tag[0] + " " + ((bool)tag[1] ? "locked" : "unlocked")); bool newState = !(bool)tag[1]; ((Button)s).Tag = new object[] { tag[0], newState }; ((Button)s).Text = (newState ? "Lock " : "Unlock ") + axName; }); fpLock.Controls.Add(btnLock); } gbLock.Controls.Add(fpLock); main.Controls.Add(gbLock, 0, 1); // Sample height GroupBox gbSample = CreateGroupBox("Sample & Orbit Settings"); TableLayoutPanel pSample = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 3, RowCount = 3 }; pSample.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35)); pSample.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 45)); pSample.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20)); NumericUpDown nudSH = new NumericUpDown { Minimum = 0, Maximum = 500, DecimalPlaces = 1, Dock = DockStyle.Fill }; NumericUpDown nudMSH = new NumericUpDown { Minimum = 0, Maximum = 500, DecimalPlaces = 1, Dock = DockStyle.Fill }; nudOrbitSpeed = new NumericUpDown { Minimum = 0, Maximum = 100, DecimalPlaces = 0, Dock = DockStyle.Fill }; pSample.Controls.Add(CreateLabel("Sample Height"), 0, 0); pSample.Controls.Add(nudSH, 1, 0); Button btnSH = new Button { Text = "Set", Dock = DockStyle.Fill }; btnSH.Click += (s, e) => SafeCall(() => { manipChannel.Misc.SampleHeight((float)nudSH.Value); Log("Sample height set to " + nudSH.Value); }); pSample.Controls.Add(btnSH, 2, 0); pSample.Controls.Add(CreateLabel("Max Sample H."), 0, 1); pSample.Controls.Add(nudMSH, 1, 1); Button btnMSH = new Button { Text = "Set", Dock = DockStyle.Fill }; btnMSH.Click += (s, e) => SafeCall(() => { manipChannel.Misc.SampleHeightMax((float)nudMSH.Value); Log("Max sample height set to " + nudMSH.Value); }); pSample.Controls.Add(btnMSH, 2, 1); pSample.Controls.Add(CreateLabel("Orbit Speed %"), 0, 2); pSample.Controls.Add(nudOrbitSpeed, 1, 2); Button btnOS = new Button { Text = "Set", Dock = DockStyle.Fill }; btnOS.Click += (s, e) => SafeCall(() => { manipChannel.Orbit.Speed((int)nudOrbitSpeed.Value); Log("Orbit speed set to " + nudOrbitSpeed.Value + "%"); }); pSample.Controls.Add(btnOS, 2, 2); gbSample.Controls.Add(pSample); main.Controls.Add(gbSample, 1, 1); tab.Controls.Add(main); return tab; } // ==================== MiscIO Readout / Control Tab ==================== private TabPage CreateMiscIOTab() { TabPage tab = new TabPage("MiscIO Direct IO"); tab.AutoScroll = true; tab.Padding = new Padding(8); Label title = new Label(); title.Text = "Direct InspectXUtilities.MiscIO readout/control. This bypasses ImageProcessing IPC and camera acquisition."; title.Location = new Point(12, 10); title.Size = new Size(1040, 20); title.Font = new Font("Segoe UI", 9f, FontStyle.Bold); title.ForeColor = Color.DarkBlue; tab.Controls.Add(title); Label map = new Label(); map.Text = "Binary map found: IntensifierField -> DigitalOutput(1, field). IrisDemand -> AnalogOutput(0, volts). Imaging formula: volts = IrisDemandPercent * IrisDemandVoltageScaling / 100."; map.Location = new Point(12, 34); map.Size = new Size(1040, 35); map.ForeColor = Color.DimGray; tab.Controls.Add(map); GroupBox grpSession = new GroupBox(); grpSession.Text = "MiscIO session"; grpSession.Location = new Point(10, 75); grpSession.Size = new Size(1040, 80); tab.Controls.Add(grpSession); btnMiscOpen = new Button(); btnMiscOpen.Text = "Open MiscIO"; btnMiscOpen.Location = new Point(12, 28); btnMiscOpen.Size = new Size(110, 28); btnMiscOpen.Click += new EventHandler(BtnMiscOpen_Click); grpSession.Controls.Add(btnMiscOpen); btnMiscRelease = new Button(); btnMiscRelease.Text = "Release MiscIO"; btnMiscRelease.Location = new Point(132, 28); btnMiscRelease.Size = new Size(110, 28); btnMiscRelease.Click += new EventHandler(BtnMiscRelease_Click); grpSession.Controls.Add(btnMiscRelease); lblMiscIOStatus = new Label(); lblMiscIOStatus.Text = "not opened"; lblMiscIOStatus.Location = new Point(260, 33); lblMiscIOStatus.Size = new Size(740, 20); lblMiscIOStatus.ForeColor = Color.Navy; grpSession.Controls.Add(lblMiscIOStatus); GroupBox grpDigital = new GroupBox(); grpDigital.Text = "Digital IO"; grpDigital.Location = new Point(10, 165); grpDigital.Size = new Size(510, 170); tab.Controls.Add(grpDigital); Label lblD1 = new Label(); lblD1.Text = "Index/channel:"; lblD1.Location = new Point(12, 30); lblD1.AutoSize = true; grpDigital.Controls.Add(lblD1); nudMiscDigitalIndex = new NumericUpDown(); nudMiscDigitalIndex.Minimum = 0; nudMiscDigitalIndex.Maximum = 31; nudMiscDigitalIndex.Value = 1; nudMiscDigitalIndex.Location = new Point(105, 27); nudMiscDigitalIndex.Size = new Size(70, 22); grpDigital.Controls.Add(nudMiscDigitalIndex); Label lblD2 = new Label(); lblD2.Text = "Value:"; lblD2.Location = new Point(190, 30); lblD2.AutoSize = true; grpDigital.Controls.Add(lblD2); nudMiscDigitalValue = new NumericUpDown(); nudMiscDigitalValue.Minimum = 0; nudMiscDigitalValue.Maximum = 65535; nudMiscDigitalValue.Value = 0; nudMiscDigitalValue.Location = new Point(240, 27); nudMiscDigitalValue.Size = new Size(90, 22); grpDigital.Controls.Add(nudMiscDigitalValue); btnMiscDigitalRead = new Button(); btnMiscDigitalRead.Text = "Read digital"; btnMiscDigitalRead.Location = new Point(345, 25); btnMiscDigitalRead.Size = new Size(110, 26); btnMiscDigitalRead.Click += new EventHandler(BtnMiscDigitalRead_Click); grpDigital.Controls.Add(btnMiscDigitalRead); btnMiscDigitalWrite = new Button(); btnMiscDigitalWrite.Text = "Write digital"; btnMiscDigitalWrite.Location = new Point(345, 58); btnMiscDigitalWrite.Size = new Size(110, 26); btnMiscDigitalWrite.Click += new EventHandler(BtnMiscDigitalWrite_Click); grpDigital.Controls.Add(btnMiscDigitalWrite); lblMiscDigitalRead = new Label(); lblMiscDigitalRead.Text = "readback: ?"; lblMiscDigitalRead.Location = new Point(12, 65); lblMiscDigitalRead.Size = new Size(315, 20); lblMiscDigitalRead.ForeColor = Color.Navy; grpDigital.Controls.Add(lblMiscDigitalRead); Label lblDNote = new Label(); lblDNote.Text = "Known from binary: index 1 is the intensifier field-select write used by Imaging.dll. Use small values first."; lblDNote.Location = new Point(12, 100); lblDNote.Size = new Size(475, 38); lblDNote.ForeColor = Color.DimGray; grpDigital.Controls.Add(lblDNote); GroupBox grpAnalog = new GroupBox(); grpAnalog.Text = "Analog IO"; grpAnalog.Location = new Point(540, 165); grpAnalog.Size = new Size(510, 170); tab.Controls.Add(grpAnalog); Label lblA1 = new Label(); lblA1.Text = "Index/channel:"; lblA1.Location = new Point(12, 30); lblA1.AutoSize = true; grpAnalog.Controls.Add(lblA1); nudMiscAnalogIndex = new NumericUpDown(); nudMiscAnalogIndex.Minimum = 0; nudMiscAnalogIndex.Maximum = 31; nudMiscAnalogIndex.Value = 0; nudMiscAnalogIndex.Location = new Point(105, 27); nudMiscAnalogIndex.Size = new Size(70, 22); grpAnalog.Controls.Add(nudMiscAnalogIndex); Label lblA2 = new Label(); lblA2.Text = "Volts/value:"; lblA2.Location = new Point(190, 30); lblA2.AutoSize = true; grpAnalog.Controls.Add(lblA2); nudMiscAnalogValue = new NumericUpDown(); nudMiscAnalogValue.Minimum = -10; nudMiscAnalogValue.Maximum = 10; nudMiscAnalogValue.DecimalPlaces = 3; nudMiscAnalogValue.Increment = 0.100M; nudMiscAnalogValue.Value = 0; nudMiscAnalogValue.Location = new Point(270, 27); nudMiscAnalogValue.Size = new Size(75, 22); grpAnalog.Controls.Add(nudMiscAnalogValue); btnMiscAnalogRead = new Button(); btnMiscAnalogRead.Text = "Read analog"; btnMiscAnalogRead.Location = new Point(365, 25); btnMiscAnalogRead.Size = new Size(110, 26); btnMiscAnalogRead.Click += new EventHandler(BtnMiscAnalogRead_Click); grpAnalog.Controls.Add(btnMiscAnalogRead); btnMiscAnalogWrite = new Button(); btnMiscAnalogWrite.Text = "Write analog"; btnMiscAnalogWrite.Location = new Point(365, 58); btnMiscAnalogWrite.Size = new Size(110, 26); btnMiscAnalogWrite.Click += new EventHandler(BtnMiscAnalogWrite_Click); grpAnalog.Controls.Add(btnMiscAnalogWrite); lblMiscAnalogRead = new Label(); lblMiscAnalogRead.Text = "readback: ?"; lblMiscAnalogRead.Location = new Point(12, 65); lblMiscAnalogRead.Size = new Size(335, 20); lblMiscAnalogRead.ForeColor = Color.Navy; grpAnalog.Controls.Add(lblMiscAnalogRead); Label lblANote = new Label(); lblANote.Text = "Known from binary: analog index 0 is IrisDemand when Imaging uses MiscIO. Range depends on MiscIO.ini/IO board."; lblANote.Location = new Point(12, 100); lblANote.Size = new Size(475, 38); lblANote.ForeColor = Color.DimGray; grpAnalog.Controls.Add(lblANote); GroupBox grpIris = new GroupBox(); grpIris.Text = "Iris demand shortcut"; grpIris.Location = new Point(10, 345); grpIris.Size = new Size(1040, 110); tab.Controls.Add(grpIris); Label lblI1 = new Label(); lblI1.Text = "Iris demand %:"; lblI1.Location = new Point(12, 30); lblI1.AutoSize = true; grpIris.Controls.Add(lblI1); nudMiscIrisPercent = new NumericUpDown(); nudMiscIrisPercent.Minimum = 0; nudMiscIrisPercent.Maximum = 100; nudMiscIrisPercent.DecimalPlaces = 1; nudMiscIrisPercent.Increment = 1; nudMiscIrisPercent.Value = 0; nudMiscIrisPercent.Location = new Point(120, 27); nudMiscIrisPercent.Size = new Size(80, 22); grpIris.Controls.Add(nudMiscIrisPercent); Label lblI2 = new Label(); lblI2.Text = "Scaling volts @100%:"; lblI2.Location = new Point(220, 30); lblI2.AutoSize = true; grpIris.Controls.Add(lblI2); nudMiscIrisScaling = new NumericUpDown(); nudMiscIrisScaling.Minimum = 0; nudMiscIrisScaling.Maximum = 10; nudMiscIrisScaling.DecimalPlaces = 2; nudMiscIrisScaling.Increment = 0.10M; nudMiscIrisScaling.Value = 10; nudMiscIrisScaling.Location = new Point(360, 27); nudMiscIrisScaling.Size = new Size(80, 22); grpIris.Controls.Add(nudMiscIrisScaling); btnMiscIrisWrite = new Button(); btnMiscIrisWrite.Text = "Write iris demand"; btnMiscIrisWrite.Location = new Point(460, 25); btnMiscIrisWrite.Size = new Size(130, 26); btnMiscIrisWrite.Click += new EventHandler(BtnMiscIrisWrite_Click); grpIris.Controls.Add(btnMiscIrisWrite); lblMiscIrisStatus = new Label(); lblMiscIrisStatus.Text = "not written"; lblMiscIrisStatus.Location = new Point(610, 30); lblMiscIrisStatus.Size = new Size(410, 20); lblMiscIrisStatus.ForeColor = Color.Navy; grpIris.Controls.Add(lblMiscIrisStatus); Label lblINote = new Label(); lblINote.Text = "This computes volts like Imaging.dll, then writes InspectXUtilities.MiscIO.IrisDemand. With default scaling 10 V, 50% writes 5.000 V to analog channel 0."; lblINote.Location = new Point(12, 65); lblINote.Size = new Size(1000, 20); lblINote.ForeColor = Color.DimGray; grpIris.Controls.Add(lblINote); GroupBox grpSnapshot = new GroupBox(); grpSnapshot.Text = "MiscIO account / read snapshot"; grpSnapshot.Location = new Point(10, 465); grpSnapshot.Size = new Size(1040, 260); tab.Controls.Add(grpSnapshot); btnMiscSnapshot = new Button(); btnMiscSnapshot.Text = "Refresh snapshot"; btnMiscSnapshot.Location = new Point(12, 22); btnMiscSnapshot.Size = new Size(130, 26); btnMiscSnapshot.Click += new EventHandler(BtnMiscSnapshot_Click); grpSnapshot.Controls.Add(btnMiscSnapshot); txtMiscIODiag = new RichTextBox(); txtMiscIODiag.Location = new Point(12, 55); txtMiscIODiag.Size = new Size(1010, 190); txtMiscIODiag.ReadOnly = true; txtMiscIODiag.Font = new Font("Consolas", 9f); txtMiscIODiag.BackColor = Color.White; grpSnapshot.Controls.Add(txtMiscIODiag); UpdateMiscIODiagnosticText(false); return tab; } // ==================== Log Tab ==================== private TabPage CreateLogTab() { TabPage tab = new TabPage("Diagnostic Log"); txtLog = new RichTextBox { Dock = DockStyle.Fill, ReadOnly = true, Font = new Font("Consolas", 9f), BackColor = Color.FromArgb(30, 30, 30), ForeColor = Color.LightGreen }; tab.Controls.Add(txtLog); return tab; } // ==================== Native Motion / Lower DLL Tab ==================== private TabPage CreateNativeMotionTab() { TabPage tab = new TabPage("Native Motion DLL"); tab.AutoScroll = true; tab.Padding = new Padding(8); Label title = new Label(); title.Text = "Direct lower-DLL manipulator interrogation. v9 adds explicit _setAxisEnabled and an Enable+Velocity proof sequence."; title.Location = new Point(12, 10); title.Size = new Size(1020, 22); title.Font = new Font("Segoe UI", 9f, FontStyle.Bold); tab.Controls.Add(title); GroupBox grpSession = new GroupBox(); grpSession.Text = "Native DLL session"; grpSession.Location = new Point(12, 36); grpSession.Size = new Size(1040, 115); tab.Controls.Add(grpSession); Label lblDir = new Label(); lblDir.Text = "DLL folder"; lblDir.Location = new Point(12, 25); lblDir.Size = new Size(75, 20); grpSession.Controls.Add(lblDir); txtNativeMotionDllDir = new TextBox(); txtNativeMotionDllDir.Location = new Point(90, 22); txtNativeMotionDllDir.Size = new Size(610, 22); txtNativeMotionDllDir.Text = AppDomain.CurrentDomain.BaseDirectory; grpSession.Controls.Add(txtNativeMotionDllDir); Button btnBrowse = new Button(); btnBrowse.Text = "Browse"; btnBrowse.Location = new Point(708, 20); btnBrowse.Size = new Size(75, 25); btnBrowse.Click += delegate { BrowseNativeMotionDllDir(); }; grpSession.Controls.Add(btnBrowse); Label lblDll = new Label(); lblDll.Text = "DLL"; lblDll.Location = new Point(795, 25); lblDll.Size = new Size(30, 20); grpSession.Controls.Add(lblDll); cmbNativeMotionDll = new ComboBox(); cmbNativeMotionDll.Location = new Point(830, 22); cmbNativeMotionDll.Size = new Size(195, 22); cmbNativeMotionDll.DropDownStyle = ComboBoxStyle.DropDownList; cmbNativeMotionDll.Items.AddRange(new object[] { "XTMVenlo.dll", "XTekMotionCopley.dll", "XTekMotionCopleyDISABLING.dll", "XTMRevolution.dll" }); cmbNativeMotionDll.SelectedIndex = 0; grpSession.Controls.Add(cmbNativeMotionDll); Button btnLoad = new Button(); btnLoad.Text = "Load DLL"; btnLoad.Location = new Point(12, 55); btnLoad.Size = new Size(90, 28); btnLoad.Click += delegate { NativeMotionLoad(); }; grpSession.Controls.Add(btnLoad); Button btnInit = new Button(); btnInit.Text = "Initialise"; btnInit.Location = new Point(108, 55); btnInit.Size = new Size(90, 28); btnInit.Click += delegate { NativeMotionInitialise(); }; grpSession.Controls.Add(btnInit); Button btnRelease = new Button(); btnRelease.Text = "Release"; btnRelease.Location = new Point(204, 55); btnRelease.Size = new Size(90, 28); btnRelease.Click += delegate { NativeMotionRelease(true); }; grpSession.Controls.Add(btnRelease); Button btnRead = new Button(); btnRead.Text = "Read axes"; btnRead.Location = new Point(300, 55); btnRead.Size = new Size(90, 28); btnRead.Click += delegate { NativeMotionReadAxes(); }; grpSession.Controls.Add(btnRead); Button btnStop = new Button(); btnStop.Text = "STOP ALL"; btnStop.Location = new Point(396, 55); btnStop.Size = new Size(90, 28); btnStop.BackColor = Color.FromArgb(244, 67, 54); btnStop.ForeColor = Color.White; btnStop.Click += delegate { NativeMotionStopAll(); }; grpSession.Controls.Add(btnStop); Label lblInit = new Label(); lblInit.Text = "Init/card arg"; lblInit.Location = new Point(506, 61); lblInit.Size = new Size(78, 20); grpSession.Controls.Add(lblInit); nudNativeInitArg = new NumericUpDown(); nudNativeInitArg.Location = new Point(588, 57); nudNativeInitArg.Size = new Size(60, 22); nudNativeInitArg.Minimum = -32768; nudNativeInitArg.Maximum = 32767; nudNativeInitArg.Value = 0; grpSession.Controls.Add(nudNativeInitArg); Label lblBase = new Label(); lblBase.Text = "Axis base"; lblBase.Location = new Point(665, 61); lblBase.Size = new Size(65, 20); grpSession.Controls.Add(lblBase); nudNativeAxisBase = new NumericUpDown(); nudNativeAxisBase.Location = new Point(735, 57); nudNativeAxisBase.Size = new Size(50, 22); nudNativeAxisBase.Minimum = 0; nudNativeAxisBase.Maximum = 10; nudNativeAxisBase.Value = 0; grpSession.Controls.Add(nudNativeAxisBase); lblNativeMotionStatus = new Label(); lblNativeMotionStatus.Text = "not loaded"; lblNativeMotionStatus.Location = new Point(12, 88); lblNativeMotionStatus.Size = new Size(1010, 20); lblNativeMotionStatus.ForeColor = Color.Navy; grpSession.Controls.Add(lblNativeMotionStatus); GroupBox grpAxes = new GroupBox(); grpAxes.Text = "Raw axis readout"; grpAxes.Location = new Point(12, 158); grpAxes.Size = new Size(1040, 255); tab.Controls.Add(grpAxes); dgvNativeMotionAxes = new DataGridView(); dgvNativeMotionAxes.Location = new Point(10, 22); dgvNativeMotionAxes.Size = new Size(1020, 220); dgvNativeMotionAxes.AllowUserToAddRows = false; dgvNativeMotionAxes.AllowUserToDeleteRows = false; dgvNativeMotionAxes.ReadOnly = true; dgvNativeMotionAxes.RowHeadersVisible = false; dgvNativeMotionAxes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dgvNativeMotionAxes.BackgroundColor = Color.White; dgvNativeMotionAxes.Columns.Add("Axis", "Axis"); dgvNativeMotionAxes.Columns.Add("Position", "Position"); dgvNativeMotionAxes.Columns.Add("LinearEncoder", "Linear Encoder"); dgvNativeMotionAxes.Columns.Add("Velocity", "Velocity"); dgvNativeMotionAxes.Columns.Add("Target", "Target"); dgvNativeMotionAxes.Columns.Add("MotorCurrent", "Motor Current"); dgvNativeMotionAxes.Columns.Add("Idle", "Idle/Stationary"); dgvNativeMotionAxes.Columns.Add("Homed", "Homed"); dgvNativeMotionAxes.Columns.Add("Locked", "Locked"); dgvNativeMotionAxes.Columns.Add("Error", "Error"); dgvNativeMotionAxes.Columns.Add("MaxSpeed", "Max Speed"); dgvNativeMotionAxes.Columns.Add("FollowError", "Follow Error"); dgvNativeMotionAxes.Columns.Add("Returns", "Return Codes"); grpAxes.Controls.Add(dgvNativeMotionAxes); GroupBox grpMove = new GroupBox(); grpMove.Text = "Direct motion commands — Venlo API or emulated CANOpen/Revolution comms"; grpMove.Location = new Point(12, 420); grpMove.Size = new Size(1040, 135); tab.Controls.Add(grpMove); Label lblAxis = new Label(); lblAxis.Text = "Axis"; lblAxis.Location = new Point(12, 30); lblAxis.Size = new Size(40, 20); grpMove.Controls.Add(lblAxis); cmbNativeMotionAxis = new ComboBox(); cmbNativeMotionAxis.Location = new Point(58, 27); cmbNativeMotionAxis.Size = new Size(125, 22); cmbNativeMotionAxis.DropDownStyle = ComboBoxStyle.DropDownList; cmbNativeMotionAxis.Items.AddRange(new object[] { "0", "1", "2", "3", "4", "5", "6", "7" }); cmbNativeMotionAxis.SelectedIndex = 0; grpMove.Controls.Add(cmbNativeMotionAxis); Label lblTarget = new Label(); lblTarget.Text = "Target"; lblTarget.Location = new Point(202, 30); lblTarget.Size = new Size(55, 20); grpMove.Controls.Add(lblTarget); nudNativeMoveTarget = new NumericUpDown(); nudNativeMoveTarget.Location = new Point(260, 27); nudNativeMoveTarget.Size = new Size(95, 22); nudNativeMoveTarget.Minimum = -100000; nudNativeMoveTarget.Maximum = 100000; nudNativeMoveTarget.DecimalPlaces = 3; nudNativeMoveTarget.Increment = 0.1M; grpMove.Controls.Add(nudNativeMoveTarget); Label lblSpeed = new Label(); lblSpeed.Text = "Speed"; lblSpeed.Location = new Point(370, 30); lblSpeed.Size = new Size(45, 20); grpMove.Controls.Add(lblSpeed); nudNativeMoveSpeed = new NumericUpDown(); nudNativeMoveSpeed.Location = new Point(420, 27); nudNativeMoveSpeed.Size = new Size(75, 22); nudNativeMoveSpeed.Minimum = 0; nudNativeMoveSpeed.Maximum = 100000; nudNativeMoveSpeed.DecimalPlaces = 3; nudNativeMoveSpeed.Increment = 0.1M; nudNativeMoveSpeed.Value = 1; grpMove.Controls.Add(nudNativeMoveSpeed); Button btnAbs = new Button(); btnAbs.Text = "Set target + Go"; btnAbs.Location = new Point(510, 24); btnAbs.Size = new Size(120, 28); btnAbs.Click += delegate { NativeMotionMoveAbsolute(); }; grpMove.Controls.Add(btnAbs); Button btnRel = new Button(); btnRel.Text = "Go relative"; btnRel.Location = new Point(640, 24); btnRel.Size = new Size(100, 28); btnRel.Click += delegate { NativeMotionMoveRelative(); }; grpMove.Controls.Add(btnRel); Label lblVel = new Label(); lblVel.Text = "Velocity"; lblVel.Location = new Point(12, 75); lblVel.Size = new Size(60, 20); grpMove.Controls.Add(lblVel); nudNativeVelocity = new NumericUpDown(); nudNativeVelocity.Location = new Point(75, 72); nudNativeVelocity.Size = new Size(95, 22); nudNativeVelocity.Minimum = -100000; nudNativeVelocity.Maximum = 100000; nudNativeVelocity.DecimalPlaces = 3; nudNativeVelocity.Increment = 0.1M; grpMove.Controls.Add(nudNativeVelocity); Button btnVel = new Button(); btnVel.Text = "Velocity Go"; btnVel.Location = new Point(185, 69); btnVel.Size = new Size(100, 28); btnVel.Click += delegate { NativeMotionVelocityGo(); }; grpMove.Controls.Add(btnVel); Button btnHome = new Button(); btnHome.Text = "Home axis"; btnHome.Location = new Point(295, 69); btnHome.Size = new Size(90, 28); btnHome.Click += delegate { NativeMotionHome(); }; grpMove.Controls.Add(btnHome); Button btnLock = new Button(); btnLock.Text = "Lock"; btnLock.Location = new Point(395, 69); btnLock.Size = new Size(75, 28); btnLock.Click += delegate { NativeMotionSetLock(1); }; grpMove.Controls.Add(btnLock); Button btnUnlock = new Button(); btnUnlock.Text = "Unlock"; btnUnlock.Location = new Point(478, 69); btnUnlock.Size = new Size(75, 28); btnUnlock.Click += delegate { NativeMotionSetLock(0); }; grpMove.Controls.Add(btnUnlock); Button btnAxisEnable = new Button(); btnAxisEnable.Text = "Axis Enable"; btnAxisEnable.Location = new Point(562, 69); btnAxisEnable.Size = new Size(92, 28); btnAxisEnable.Click += delegate { NativeMotionSetAxisEnabled(true); }; grpMove.Controls.Add(btnAxisEnable); Button btnAxisDisable = new Button(); btnAxisDisable.Text = "Axis Disable"; btnAxisDisable.Location = new Point(660, 69); btnAxisDisable.Size = new Size(96, 28); btnAxisDisable.Click += delegate { NativeMotionSetAxisEnabled(false); }; grpMove.Controls.Add(btnAxisDisable); Button btnProof = new Button(); btnProof.Text = "Enable + Vel"; btnProof.Location = new Point(765, 69); btnProof.Size = new Size(100, 28); btnProof.BackColor = Color.FromArgb(255, 235, 156); btnProof.Click += delegate { NativeMotionEnableThenVelocity(); }; grpMove.Controls.Add(btnProof); Label lblMoveNote = new Label(); lblMoveNote.Text = "v9: try Axis Enable first. Enable+Vel does _setAxisEnabled(axis,true), clears lock bit, writes velocity reg 94+axis, then reads back. STOP ALL writes zero velocities."; lblMoveNote.Location = new Point(12, 103); lblMoveNote.Size = new Size(1010, 24); lblMoveNote.ForeColor = Color.DimGray; grpMove.Controls.Add(lblMoveNote); GroupBox grpRaw = new GroupBox(); grpRaw.Text = "Raw Copley/Revolution node IO probes"; grpRaw.Location = new Point(12, 562); grpRaw.Size = new Size(1040, 88); tab.Controls.Add(grpRaw); Label lblNode = new Label(); lblNode.Text = "Node"; lblNode.Location = new Point(12, 29); lblNode.Size = new Size(45, 20); grpRaw.Controls.Add(lblNode); nudNativeNode = new NumericUpDown(); nudNativeNode.Location = new Point(62, 26); nudNativeNode.Size = new Size(60, 22); nudNativeNode.Minimum = 0; nudNativeNode.Maximum = 255; grpRaw.Controls.Add(nudNativeNode); Button btnNodeRead = new Button(); btnNodeRead.Text = "Read node IO"; btnNodeRead.Location = new Point(134, 23); btnNodeRead.Size = new Size(105, 28); btnNodeRead.Click += delegate { NativeMotionReadNodeIO(); }; grpRaw.Controls.Add(btnNodeRead); Label lblOut = new Label(); lblOut.Text = "Output byte"; lblOut.Location = new Point(260, 29); lblOut.Size = new Size(80, 20); grpRaw.Controls.Add(lblOut); nudNativeNodeOutput = new NumericUpDown(); nudNativeNodeOutput.Location = new Point(345, 26); nudNativeNodeOutput.Size = new Size(65, 22); nudNativeNodeOutput.Minimum = 0; nudNativeNodeOutput.Maximum = 255; grpRaw.Controls.Add(nudNativeNodeOutput); Button btnNodeWrite = new Button(); btnNodeWrite.Text = "Write node output"; btnNodeWrite.Location = new Point(420, 23); btnNodeWrite.Size = new Size(125, 28); btnNodeWrite.Click += delegate { NativeMotionWriteNodeOutput(); }; grpRaw.Controls.Add(btnNodeWrite); Button btnAux = new Button(); btnAux.Text = "Read aux inputs"; btnAux.Location = new Point(560, 23); btnAux.Size = new Size(115, 28); btnAux.Click += delegate { NativeMotionReadAuxInputs(); }; grpRaw.Controls.Add(btnAux); Label lblRawNote = new Label(); lblRawNote.Text = "Node-output write is a raw byte write to the loaded native controller DLL; use only when you know the node mapping."; lblRawNote.Location = new Point(690, 26); lblRawNote.Size = new Size(330, 42); lblRawNote.ForeColor = Color.DarkRed; grpRaw.Controls.Add(lblRawNote); GroupBox grpLog = new GroupBox(); grpLog.Text = "Native motion log"; grpLog.Location = new Point(12, 658); grpLog.Size = new Size(1040, 245); tab.Controls.Add(grpLog); txtNativeMotionLog = new RichTextBox(); txtNativeMotionLog.Location = new Point(10, 22); txtNativeMotionLog.Size = new Size(1020, 210); txtNativeMotionLog.ReadOnly = true; txtNativeMotionLog.Font = new Font("Consolas", 9f); txtNativeMotionLog.BackColor = Color.White; grpLog.Controls.Add(txtNativeMotionLog); NativeMotionLog("Loaded signatures from Manipulator.dll metadata: XTMRevolution/Copley expose setComms/setCommsWrite/getCommsF. Direct velocity/target/command emulation is available for controlled tests."); return tab; } private void BrowseNativeMotionDllDir() { FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.Description = "Select folder containing Inspect-X native motion DLLs"; dlg.SelectedPath = txtNativeMotionDllDir.Text; if (dlg.ShowDialog() == DialogResult.OK) txtNativeMotionDllDir.Text = dlg.SelectedPath; } private void NativeMotionSetStatus(string text, Color color) { if (lblNativeMotionStatus != null) { lblNativeMotionStatus.Text = text; lblNativeMotionStatus.ForeColor = color; } } private void NativeMotionLog(string message) { if (txtNativeMotionLog != null) { txtNativeMotionLog.AppendText(DateTime.Now.ToString("HH:mm:ss.fff") + " " + message + "\n"); txtNativeMotionLog.ScrollToCaret(); } if (txtLog != null) Log("NativeMotion: " + message); } private void NativeMotionLoad() { try { NativeMotionRelease(false); string path = System.IO.Path.Combine(txtNativeMotionDllDir.Text, cmbNativeMotionDll.Text); if (!System.IO.File.Exists(path)) { // Helpful fallback for the uploaded package where the Copley DLL was renamed. if (cmbNativeMotionDll.Text == "XTekMotionCopley.dll") { string alt = System.IO.Path.Combine(txtNativeMotionDllDir.Text, "XTekMotionCopleyDISABLING.dll"); if (System.IO.File.Exists(alt)) path = alt; } } if (!System.IO.File.Exists(path)) { NativeMotionSetStatus("DLL not found: " + path, Color.Red); NativeMotionLog("DLL not found: " + path); return; } nativeMotion = new NativeMotionController(); if (!nativeMotion.Load(path)) { NativeMotionSetStatus("load failed: " + nativeMotion.LastError, Color.Red); NativeMotionLog("load failed: " + nativeMotion.LastError); nativeMotion = null; return; } NativeMotionSetStatus("loaded " + nativeMotion.LoadedDll + " kind=" + nativeMotion.Kind + "; exports=" + nativeMotion.ExportSummary(), Color.Green); NativeMotionLog("loaded " + path); NativeMotionLog("exports: " + nativeMotion.ExportSummary()); } catch (Exception ex) { NativeMotionSetStatus("load exception: " + ex.Message, Color.Red); NativeMotionLog("load exception: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionInitialise() { if (!EnsureNativeMotionLoaded()) return; try { string result = nativeMotion.Initialise((short)nudNativeInitArg.Value); NativeMotionSetStatus(result, Color.Green); NativeMotionLog(result); } catch (Exception ex) { NativeMotionSetStatus("initialise failed: " + ex.Message, Color.Red); NativeMotionLog("initialise failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionRelease(bool logResult) { try { if (nativeMotion != null) { nativeMotion.Release(); if (logResult) NativeMotionLog("released native motion DLL"); } } catch (Exception ex) { if (logResult) NativeMotionLog("release failed: " + ex.Message); } nativeMotion = null; if (logResult) NativeMotionSetStatus("released", Color.Navy); } private bool EnsureNativeMotionLoaded() { if (nativeMotion == null || !nativeMotion.IsLoaded) { NativeMotionLoad(); } return nativeMotion != null && nativeMotion.IsLoaded; } private int SelectedNativeAxis() { int axis = 0; try { axis = Int32.Parse(cmbNativeMotionAxis.Text); } catch { axis = cmbNativeMotionAxis.SelectedIndex; } return axis + (int)nudNativeAxisBase.Value; } private void NativeMotionReadAxes() { if (!EnsureNativeMotionLoaded()) return; try { dgvNativeMotionAxes.Rows.Clear(); NativeAxisSnapshot[] rows = nativeMotion.ReadAxes((short)nudNativeInitArg.Value, (int)nudNativeAxisBase.Value, 8); for (int i = 0; i < rows.Length; i++) { NativeAxisSnapshot a = rows[i]; dgvNativeMotionAxes.Rows.Add(new object[] { a.Axis, a.Position, a.LinearEncoder, a.Velocity, a.Target, a.MotorCurrent, a.Idle, a.Homed, a.Locked, a.Error, a.MaxSpeed, a.FollowError, a.Returns }); } NativeMotionSetStatus("axis read complete; " + rows.Length.ToString() + " rows", Color.Green); NativeMotionLog("axis read complete"); } catch (Exception ex) { NativeMotionSetStatus("axis read failed: " + ex.Message, Color.Red); NativeMotionLog("axis read failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionMoveAbsolute() { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); string result = nativeMotion.MoveAbsolute(axis, (float)nudNativeMoveTarget.Value, (float)nudNativeMoveSpeed.Value); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionLog("absolute move failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionMoveRelative() { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); string result = nativeMotion.MoveRelative(axis, (float)nudNativeMoveTarget.Value); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionLog("relative move failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionVelocityGo() { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); string result = nativeMotion.VelocityGo(axis, (float)nudNativeVelocity.Value); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionLog("velocity go failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionSetAxisEnabled(bool enabled) { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); string result = nativeMotion.SetAxisEnabled(axis, enabled); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionLog("axis enable/disable failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionEnableThenVelocity() { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); float velocity = (float)nudNativeVelocity.Value; string result = nativeMotion.EnableThenVelocity(axis, velocity); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionLog("enable+velocity failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionHome() { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); string result = nativeMotion.Home(axis); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); } catch (Exception ex) { NativeMotionLog("home failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionSetLock(int locked) { if (!EnsureNativeMotionLoaded()) return; try { int axis = SelectedNativeAxis(); string result = nativeMotion.SetLocked(axis, locked); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionLog("lock/unlock failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionStopAll() { if (!EnsureNativeMotionLoaded()) return; try { string result = nativeMotion.StopAll(); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadAxes(); } catch (Exception ex) { NativeMotionSetStatus("stop failed: " + ex.Message, Color.Red); NativeMotionLog("stop failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionReadNodeIO() { if (!EnsureNativeMotionLoaded()) return; try { string result = nativeMotion.ReadNodeIO((short)nudNativeInitArg.Value, (short)nudNativeNode.Value); NativeMotionSetStatus(result, Color.Green); NativeMotionLog(result); } catch (Exception ex) { NativeMotionLog("node IO read failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionWriteNodeOutput() { if (!EnsureNativeMotionLoaded()) return; try { string result = nativeMotion.WriteNodeOutput((short)nudNativeInitArg.Value, (short)nudNativeNode.Value, (byte)nudNativeNodeOutput.Value); NativeMotionSetStatus(result, result.IndexOf("unavailable") >= 0 ? Color.OrangeRed : Color.Green); NativeMotionLog(result); NativeMotionReadNodeIO(); } catch (Exception ex) { NativeMotionLog("node output write failed: " + ex.GetType().Name + ": " + ex.Message); } } private void NativeMotionReadAuxInputs() { if (!EnsureNativeMotionLoaded()) return; try { string result = nativeMotion.ReadAuxInputs((short)nudNativeInitArg.Value); NativeMotionSetStatus(result, Color.Green); NativeMotionLog(result); } catch (Exception ex) { NativeMotionLog("aux input read failed: " + ex.GetType().Name + ": " + ex.Message); } } // ==================== Low-Level / Native Tab ==================== private TabPage CreateLowLevelTab() { TabPage tab = new TabPage("Low-Level Diagnostics"); tab.Padding = new Padding(8); TableLayoutPanel main = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 1, RowCount = 2 }; main.RowStyles.Add(new RowStyle(SizeType.Absolute, 90)); main.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); Label warning = new Label(); warning.Dock = DockStyle.Fill; warning.ForeColor = Color.DarkRed; warning.Font = new Font("Segoe UI", 9f, FontStyle.Bold); warning.Text = "Low-level motion diagnostics are for supervised troubleshooting only. Use a two-person procedure, slow speed, and a ready E-stop. This tab does not bypass Inspect-X interlocks. Native write calls are documented here but not fired automatically."; warning.TextAlign = ContentAlignment.MiddleLeft; main.Controls.Add(warning, 0, 0); txtNativeNotes = new RichTextBox(); txtNativeNotes.Dock = DockStyle.Fill; txtNativeNotes.ReadOnly = true; txtNativeNotes.Font = new Font("Consolas", 9f); txtNativeNotes.BackColor = Color.White; txtNativeNotes.Text = "Native controller hooks discovered in the DLL analysis:\n\n" + "XTMRevolution.dll:\n" + " InitialiseCController, ExitCController\n" + " doorFitted, doorStatus, openDoor, closeDoor\n" + " getAuxInputs, getNodeInputs, getNodeOutputs, setNodeOutputs\n" + " getIdle, getJogIdle\n" + " getPos, getVel\n" + " getMaximumSpeed, getMaximumAcceleration, getMaximumDeceleration\n" + " getXFollowError, getYFollowError\n" + " getMotorCurrent\n" + " getNumberAxes, getNumberActiveAxes\n\n" + "XTekMotionCopley.dll:\n" + " getMotorCurrent\n" + " getLinearEncoderPos, resetLinearEncoderPos\n" + " setFollowMode, clearFollowMode\n" + " rotate / CT rotate availability and axis ID calls\n\n" + "XTMVenlo.dll expected APIs:\n" + " GetAxisError, GetInterlock, GetAxisStationary\n" + " GetAxisPosition, GetAxisVelocity, GetAxisTarget\n" + " GetAxisLocked, GetAxisHomed\n" + " StopAll, AxesGo, AxesHome\n\n" + "Encoder-scaling notes:\n" + " The strongest direct hooks found are getLinearEncoderPos/resetLinearEncoderPos in XTekMotionCopley and follow-error calls in XTMRevolution. The normal axis grid now also shows controller position, target, velocity, relative position, relative zero, and motor current where the IPC wrapper exposes them. For scaling diagnosis, compare commanded target delta, reported position delta, linear encoder delta, and follow error at slow speed.\n\n" + "Recommended controlled test:\n" + " 1. Confirm axis, interlocks, E-stop, and physical clearance.\n" + " 2. Use the IPC movement tab first with a very small target delta and explicit low speed.\n" + " 3. Record position/target/velocity/motor current/relative position before, during, and after motion.\n" + " 4. Only then consider native read probes. Avoid native writes until the exact controller DLL and function signatures are confirmed on the machine."; main.Controls.Add(txtNativeNotes, 0, 1); tab.Controls.Add(main); return tab; } // ==================== Helper methods ==================== private GroupBox CreateGroupBox(string title) { return new GroupBox { Text = title, Dock = DockStyle.Fill, Font = new Font("Segoe UI", 9f, FontStyle.Bold), Padding = new Padding(4) }; } private Label CreateLabel(string text) { return new Label { Text = text, Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleLeft, Font = new Font("Segoe UI", 8.5f) }; } private Label CreatePanelLabel(string text, int x, int y, int width) { return new Label { Text = text, Location = new Point(x, y), Width = width, Height = 22, TextAlign = ContentAlignment.MiddleLeft, Font = new Font("Segoe UI", 8.5f) }; } private Label CreateValueLabel(Color color) { return new Label { Text = "---", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight, Font = new Font("Consolas", 9.5f, FontStyle.Bold), ForeColor = color }; } private void AddHeaderRow(TableLayoutPanel p, int row, string c1, string c2, string c3) { Label l1 = CreateLabel(c1); l1.Font = new Font(l1.Font, FontStyle.Bold); Label l2 = CreateLabel(c2); l2.Font = new Font(l2.Font, FontStyle.Bold); l2.TextAlign = ContentAlignment.MiddleRight; Label l3 = CreateLabel(c3); l3.Font = new Font(l3.Font, FontStyle.Bold); l3.TextAlign = ContentAlignment.MiddleRight; p.Controls.Add(l1, 0, row); p.Controls.Add(l2, 1, row); p.Controls.Add(l3, 2, row); } private Label AddValueRow(TableLayoutPanel p, int row, string label, out Label demandLabel) { p.Controls.Add(CreateLabel(label), 0, row); Label actual = CreateValueLabel(Color.FromArgb(0, 100, 0)); p.Controls.Add(actual, 1, row); demandLabel = CreateValueLabel(Color.FromArgb(0, 0, 139)); p.Controls.Add(demandLabel, 2, row); return actual; } private Label AddDiagRow(TableLayoutPanel p, int row, string label) { p.Controls.Add(CreateLabel(label), 0, row); Label val = CreateValueLabel(Color.FromArgb(0, 80, 120)); p.Controls.Add(val, 1, row); return val; } private IpcContract.Manipulator.EAxisName GetSelectedAxis() { switch (cmbAxis.SelectedIndex) { case 0: return IpcContract.Manipulator.EAxisName.X; case 1: return IpcContract.Manipulator.EAxisName.Y; case 2: return IpcContract.Manipulator.EAxisName.Magnification; case 3: return IpcContract.Manipulator.EAxisName.Tilt; case 4: return IpcContract.Manipulator.EAxisName.Rotate; case 5: return IpcContract.Manipulator.EAxisName.Detector; default: return IpcContract.Manipulator.EAxisName.X; } } private IpcContract.Manipulator.EAxisName AxisNameFromString(string name) { switch (name) { case "X": return IpcContract.Manipulator.EAxisName.X; case "Y": return IpcContract.Manipulator.EAxisName.Y; case "Mag": return IpcContract.Manipulator.EAxisName.Magnification; case "Tilt": return IpcContract.Manipulator.EAxisName.Tilt; case "Rotate": return IpcContract.Manipulator.EAxisName.Rotate; case "Det": return IpcContract.Manipulator.EAxisName.Detector; default: return IpcContract.Manipulator.EAxisName.X; } } private IpcContract.Manipulator.EAxisName AxisEnumFromStatusIndex(int index) { switch (index) { case 0: return IpcContract.Manipulator.EAxisName.X; case 1: return IpcContract.Manipulator.EAxisName.Y; case 2: return IpcContract.Manipulator.EAxisName.Magnification; case 3: return IpcContract.Manipulator.EAxisName.Tilt; case 4: return IpcContract.Manipulator.EAxisName.Rotate; case 5: return IpcContract.Manipulator.EAxisName.Detector; default: return IpcContract.Manipulator.EAxisName.None; } } private object TryInvoke(object target, string methodName, params object[] args) { if (target == null) return null; try { MethodInfo mi = FindMethod(target, methodName, args); if (mi == null) return null; return mi.Invoke(target, args); } catch { return null; } } private bool TryCall(object target, string methodName, params object[] args) { if (target == null) return false; try { MethodInfo mi = FindMethod(target, methodName, args); if (mi == null) return false; mi.Invoke(target, args); return true; } catch { return false; } } private MethodInfo FindMethod(object target, string methodName, object[] args) { MethodInfo[] methods = target.GetType().GetMethods(); foreach (MethodInfo mi in methods) { if (mi.Name != methodName) continue; ParameterInfo[] ps = mi.GetParameters(); if (ps.Length != args.Length) continue; bool ok = true; for (int i = 0; i < ps.Length; i++) { if (args[i] == null) continue; Type pt = ps[i].ParameterType; Type at = args[i].GetType(); if (!pt.IsAssignableFrom(at)) { ok = false; break; } } if (ok) return mi; } return null; } private string TryAxisRead(IpcContract.Manipulator.EAxisName axis, params string[] methodNames) { foreach (string name in methodNames) { object val = TryInvoke(manipChannel.Axis, name, axis); if (val != null) return FormatOptionalValue(val); } return "n/a"; } private bool TryAxisWrite(IpcContract.Manipulator.EAxisName axis, double value, params string[] methodNames) { foreach (string name in methodNames) { if (TryCall(manipChannel.Axis, name, axis, value)) { Log("Axis " + axis + " " + name + " set to " + value); return true; } if (TryCall(manipChannel.Axis, name, axis, (float)value)) { Log("Axis " + axis + " " + name + " set to " + value); return true; } if (TryCall(manipChannel.Axis, name, axis, (int)value)) { Log("Axis " + axis + " " + name + " set to " + value); return true; } } Log("Axis speed write was not available through this IPC wrapper; continuing with current controller speed."); return false; } private string FormatOptionalValue(object value) { if (value == null) return "n/a"; if (value is bool) return ((bool)value) ? "YES" : "NO"; if (value is float) return ((float)value).ToString("F3"); if (value is double) return ((double)value).ToString("F3"); if (value is decimal) return ((decimal)value).ToString("F3"); return value.ToString(); } private void SetFocusDemand(int value) { object focus = xrayChannel.Focus; if (TryCall(focus, "Focus", value) || TryCall(focus, "Demand", value) || TryCall(focus, "Value", value)) { Log("Focus set to " + value); } else { xrayChannel.Focus.Trim(value); Log("Focus command fell back to Focus.Trim: " + value); } } private void SetShiftValues(int x, int y, bool updatePad) { xrayChannel.XRaySource.XShift(x); xrayChannel.XRaySource.YShift(y); nudXShift.Value = ClampDecimal(x, nudXShift.Minimum, nudXShift.Maximum); nudYShift.Value = ClampDecimal(y, nudYShift.Minimum, nudYShift.Maximum); if (updatePad && shiftPad != null) shiftPad.SetValues(x, y, false); if (lblShiftPadReadout != null) lblShiftPadReadout.Text = "X " + x + " / Y " + y; Log("X/Y shift set to " + x + " / " + y); } private void SetShiftValuesFromPad() { if (!connected || xrayChannel == null) return; try { SetShiftValues(shiftPad.XValue, shiftPad.YValue, false); lastShiftPadError = ""; } catch (Exception ex) { string msg = ex.GetType().Name + ": " + ex.Message; if (msg != lastShiftPadError) { lastShiftPadError = msg; Log("X/Y shift pad write failed: " + msg); } statusLabel.Text = "X/Y shift pad write failed - see Diagnostic Log"; } } private decimal ClampDecimal(int value, decimal min, decimal max) { decimal d = value; if (d < min) return min; if (d > max) return max; return d; } private void SetBoolLabel(Label lbl, bool value) { SetBoolLabel(lbl, value, "YES", "NO", true); } private void SetBoolLabel(Label lbl, bool value, string trueText, string falseText) { SetBoolLabel(lbl, value, trueText, falseText, true); } private void SetBoolLabel(Label lbl, bool value, string trueText, string falseText, bool trueIsGood) { lbl.Text = value ? trueText : falseText; if (trueIsGood) lbl.ForeColor = value ? Color.Green : Color.Red; else lbl.ForeColor = value ? Color.Red : Color.Green; } // ==================== Connection ==================== private void DiagnosticForm_Load(object sender, EventArgs e) { Log("InspectX Advanced Diagnostic Tool started"); Log("Uses IpcContractClientInterface (official Nikon IPC wrapper)"); Log("Attempting to connect to InspectX..."); Connect(); } private void Connect() { try { Disconnect(); // Use the official IpcContractClientInterface wrappers // These handle all WCF channel setup internally appChannel = new IpcContractClientInterface.CommunicationsChannel_Application( IpcContract.Addresses.ContractEndpointPipe.InspectX_Application); xrayChannel = new IpcContractClientInterface.CommunicationsChannel_XRay( IpcContract.Addresses.ContractEndpointPipe.InspectX_XRay); manipChannel = new IpcContractClientInterface.CommunicationsChannel_Manipulator( IpcContract.Addresses.ContractEndpointPipe.InspectX_Manipulator); // ImageProcessing channel - tolerated as optional. If this // throws (older install missing the IP service), we leave // imageChannel null and the rest of the diagnostic still works. try { imageChannel = new IpcContractClientInterface.CommunicationsChannel_ImageProcessing( IpcContract.Addresses.ContractEndpointPipe.InspectX_ImageProcessing); imageConnected = imageChannel.Heartbeat(); Log("ImageProcessing channel: heartbeat " + (imageConnected ? "OK" : "no reply")); } catch (Exception exIp) { imageChannel = null; imageConnected = false; Log("ImageProcessing channel unavailable: " + exIp.GetType().Name + ": " + exIp.Message); } // Test connection with heartbeat bool appAlive = appChannel.Heartbeat(); if (appAlive) { connected = true; connectionLabel.Text = "Connected via IPC"; connectionLabel.ForeColor = Color.Green; statusLabel.Text = "Connected to InspectX - Refreshing every 500ms"; Log("Successfully connected to InspectX"); // Get app version info try { var appStatus = appChannel.GetApplicationEntireStatus(); if (appStatus != null) { Log("InspectX version: " + appStatus.ProductVersion + " (" + appStatus.Product + ")"); Log("Path: " + appStatus.Path); Log("Compiled: " + appStatus.DateCompiled); Log("Modules - XRay: " + appStatus.ModulesStatus.XRay + ", Manip: " + appStatus.ModulesStatus.Manipulator + ", ImgProc: " + appStatus.ModulesStatus.ImageProcessing + ", Insp: " + appStatus.ModulesStatus.Inspections); } } catch (Exception ex) { Log("Could not get app status: " + ex.Message); } refreshTimer.Start(); RefreshAll(); } else { Log("Heartbeat failed - InspectX may not be fully initialized"); connected = false; } } catch (EndpointNotFoundException) { connected = false; connectionLabel.Text = "Disconnected"; connectionLabel.ForeColor = Color.Red; statusLabel.Text = "InspectX not found - Is it running?"; Log("Endpoint not found. InspectX does not appear to be running."); Log("Start InspectX first, then use File > Connect (F5)."); } catch (Exception ex) { connected = false; connectionLabel.Text = "Disconnected"; connectionLabel.ForeColor = Color.Red; statusLabel.Text = "Connection failed"; Log("Connection failed: " + ex.GetType().Name + ": " + ex.Message); Log("You can retry with File > Connect or F5"); } } private void Disconnect() { refreshTimer.Stop(); try { if (xrayChannel != null) try { xrayChannel.Close(); } catch { } if (manipChannel != null) try { manipChannel.Close(); } catch { } if (appChannel != null) try { appChannel.Close(); } catch { } if (imageChannel != null) try { imageChannel.Close(); } catch { } ReleaseDirectMiscIO(false); NativeMotionRelease(false); } catch { } xrayChannel = null; manipChannel = null; appChannel = null; imageChannel = null; imageConnected = false; connected = false; connectionLabel.Text = "Disconnected"; connectionLabel.ForeColor = Color.Red; } // ==================== Refresh ==================== private void RefreshAll() { if (!connected) return; try { RefreshXray(); RefreshManipulator(); if (imageChannel != null) RefreshIntensifier(); refreshCount++; if (refreshCount % 20 == 0) { statusLabel.Text = "Connected - Cycle #" + refreshCount + " @ " + DateTime.Now.ToString("HH:mm:ss"); } } catch (CommunicationObjectFaultedException) { Log("Connection lost (server faulted)"); connected = false; connectionLabel.Text = "Connection Lost"; connectionLabel.ForeColor = Color.Orange; refreshTimer.Stop(); } catch (Exception ex) { Log("Refresh error: " + ex.Message); connected = false; connectionLabel.Text = "Connection Lost"; connectionLabel.ForeColor = Color.Orange; refreshTimer.Stop(); } } private void RefreshXray() { if (xrayChannel == null) return; try { IpcContract.XRay.EntireStatus status = xrayChannel.GetXRayEntireStatus(); if (status == null) return; // Core readings uint kvA = status.XRaysStatus.KilovoltsActual; uint kvD = status.XRaysStatus.KilovoltsDemand; uint uaA = status.XRaysStatus.MicroampsActual; uint uaD = status.XRaysStatus.MicroampsDemand; double wA = status.XRaysStatus.WattsActual; double wD = status.XRaysStatus.WattsDemand; lblKvActual.Text = kvA.ToString() + " kV"; lblKvDemand.Text = kvD.ToString() + " kV"; lblUaActual.Text = uaA.ToString() + " µA"; lblUaDemand.Text = uaD.ToString() + " µA"; lblPowerActual.Text = wA.ToString("F1") + " W"; lblPowerDemand.Text = wD.ToString("F1") + " W"; pbKv.Value = Math.Min((int)kvA, pbKv.Maximum); pbUa.Value = Math.Min((int)uaA, pbUa.Maximum); // Color-code actual vs demand mismatch lblKvActual.ForeColor = (Math.Abs((int)kvA - (int)kvD) > 2) ? Color.OrangeRed : Color.Green; lblUaActual.ForeColor = (Math.Abs((int)uaA - (int)uaD) > 5) ? Color.OrangeRed : Color.Green; // Generation state var genState = status.XRaysStatus.GenerationStatus; lblXrayState.Text = genState.State.ToString(); lblXrayState.ForeColor = genState.Generation ? Color.Red : Color.DarkGreen; SetBoolLabel(lblInterlockXray, status.XRaysStatus.Interlocks, "MADE", "BROKEN"); // Controller lblControllerType.Text = status.ControllerStatus.Type.ToString(); lblControllerVersion.Text = status.ControllerStatus.Version ?? "N/A"; SetBoolLabel(lblControllerReady, status.ControllerStatus.Ready); // Xodiac diagnostics var xodiac = status.ControllerXodiacStatus; lblCathodeCurrent.Text = xodiac.CathodeCurrent.ToString(); lblFocusReal.Text = xodiac.FocusReal.ToString(); SetBoolLabel(lblFilamentOperative, xodiac.FilamentOperative); lblFilamentMax.Text = xodiac.FilamentMax.ToString("F2"); lblFilamentMin.Text = xodiac.FilamentMin.ToString("F2"); SetBoolLabel(lblVacuumSetPoint, xodiac.VacuumSetPoint); SetBoolLabel(lblBeamTube, xodiac.BeamTubeGood); SetBoolLabel(lblTurboSpeed, xodiac.TurboSpeed); SetBoolLabel(lblTurboFault, xodiac.TurboFault, "FAULT", "OK", false); SetBoolLabel(lblOverConverterAmps, xodiac.ConverterOverAmps, "OVER", "OK", false); SetBoolLabel(lblOverConverterVolts, xodiac.ConverterOverVolts, "OVER", "OK", false); SetBoolLabel(lblOverkV, xodiac.OutputOverVolts, "OVER", "OK", false); SetBoolLabel(lblOvermA, xodiac.OutputOverAmps, "OVER", "OK", false); lblFsdVolts.Text = xodiac.FsdVolts.ToString(); lblFsdAmps.Text = xodiac.FsdAmps.ToString(); // Source - use individual calls for extra data try { lblFilamentDemand.Text = xrayChannel.XRaySource.FilamentDemand().ToString(); lblHoursOn.Text = xrayChannel.XRaySource.HoursOn().ToString("F1") + " hrs"; lblModulation.Text = xrayChannel.XRaySource.Modulation() ? "ON" : "OFF"; int xShift = xrayChannel.XRaySource.XShift(); int yShift = xrayChannel.XRaySource.YShift(); lblXShift.Text = xShift.ToString(); lblYShift.Text = yShift.ToString(); if (!nudXShift.Focused) nudXShift.Value = ClampDecimal(xShift, nudXShift.Minimum, nudXShift.Maximum); if (!nudYShift.Focused) nudYShift.Value = ClampDecimal(yShift, nudYShift.Minimum, nudYShift.Maximum); if (shiftPad != null && !shiftPad.IsDragging) shiftPad.SetValues(xShift, yShift, false); if (lblShiftPadReadout != null) lblShiftPadReadout.Text = "X " + xShift + " / Y " + yShift; lblVacuum.Text = xrayChannel.XRaySource.Vacuum().ToString(); } catch { } // Focus lblFocusMode.Text = status.FocusStatus.Mode.ToString(); try { object focusValue = TryInvoke(xrayChannel.Focus, "Focus"); if (focusValue == null) focusValue = TryInvoke(xrayChannel.Focus, "Demand"); if (focusValue == null) focusValue = TryInvoke(xrayChannel.Focus, "Value"); if (focusValue == null) focusValue = xrayChannel.Focus.Trim(); lblFocus.Text = FormatOptionalValue(focusValue); int parsedFocus; if (int.TryParse(focusValue.ToString(), out parsedFocus) && !nudFocus.Focused) nudFocus.Value = ClampDecimal(parsedFocus, nudFocus.Minimum, nudFocus.Maximum); } catch { } // Head var head = status.HeadsStatus.HeadStatus; lblHeadType.Text = head.TypeDescription ?? "N/A"; lblHeadMaxKv.Text = head.MaximumKilovolts.ToString() + " kV"; lblHeadMaxUa.Text = head.MaximumMicroamps.ToString() + " µA"; lblHeadMaxW.Text = head.MaximumWatts.ToString() + " W"; // Exposure lblExposureMode.Text = status.ExposureTimerStatus.Mode.ToString(); lblExposurePeriod.Text = status.ExposureTimerStatus.Period.ToString(); lblExposureRemaining.Text = status.ExposureTimerStatus.Remaining.ToString(); } catch (Exception ex) { Log("X-Ray refresh error: " + ex.Message); } } private void RefreshManipulator() { if (manipChannel == null) return; try { IpcContract.Manipulator.EntireStatus status = manipChannel.GetManipulatorEntireStatus(); if (status == null) return; // Controller info lblManipType.Text = status.ManipulatorType.Type.ToString(); SetBoolLabel(lblManipReady, status.ControllerStatus.Ready); SetBoolLabel(lblManipInterlock, status.AxesStatus.Interlocks, "MADE", "BROKEN"); SetBoolLabel(lblJoysticks, status.StyleStatus.JoysticksEnabled, "Enabled", "Disabled"); // Geometry lblMagnification.Text = status.MiscStatus.Magnification.ToString("F2") + "x"; lblSampleHeight.Text = status.MiscStatus.SampleHeight.ToString("F1") + " mm"; lblMaxSampleHeight.Text = status.MiscStatus.SampleHeightMax.ToString("F1") + " mm"; // Door lblDoorState.Text = status.DoorStatus.State.ToString(); lblDoorState.ForeColor = (status.DoorStatus.State == IpcContract.Manipulator.EDoorState.Closed) ? Color.Green : Color.OrangeRed; lblDoorFitted.Text = status.DoorStatus.Fitted ? "Yes" : "No"; lblDoorOutcome.Text = status.DoorStatus.Outcome.ToString(); lblDoorInterlocks.Text = TryInvoke(manipChannel.Door, "Interlocks") != null ? TryInvoke(manipChannel.Door, "Interlocks").ToString() : "n/a"; lblDoorServiceMode.Text = FormatOptionalValue(TryInvoke(manipChannel.Door, "InServiceMode")); lblDoorTimeout.Text = FormatOptionalValue(TryInvoke(manipChannel.Door, "Timeout")); lblDoorServiceTimeout.Text = FormatOptionalValue(TryInvoke(manipChannel.Door, "ServiceModeTimeout")); lblDoorIsOpen.Text = FormatOptionalValue(TryInvoke(manipChannel.Door, "IsOpen")); lblDoorIsClosed.Text = FormatOptionalValue(TryInvoke(manipChannel.Door, "IsClosed")); lblAtLoadPosition.Text = FormatOptionalValue(TryInvoke(manipChannel.Door, "ManipulatorIsAtLoadPosition")); // Orbit lblOrbitSpeed.Text = status.OrbitStatus.SpeedPercentage.ToString() + "%"; // Axes if (status.AxisStatus != null) { // Resize grid to match while (dgvAxes.Rows.Count < status.AxisStatus.Length) dgvAxes.Rows.Add(); while (dgvAxes.Rows.Count > status.AxisStatus.Length && dgvAxes.Rows.Count > 0) dgvAxes.Rows.RemoveAt(dgvAxes.Rows.Count - 1); for (int i = 0; i < status.AxisStatus.Length; i++) { var ax = status.AxisStatus[i]; DataGridViewRow r = dgvAxes.Rows[i]; r.Cells["Axis"].Value = ax.AxisName ?? ("Axis " + i); r.Cells["Position"].Value = ax.Position.ToString("F3"); r.Cells["Target"].Value = ax.Target.ToString("F3"); r.Cells["Velocity"].Value = ax.Velocity.ToString("F2"); IpcContract.Manipulator.EAxisName axisEnum = AxisEnumFromStatusIndex(i); r.Cells["Available"].Value = TryAxisRead(axisEnum, "Available"); r.Cells["Homed"].Value = ax.Homed ? "YES" : "NO"; r.Cells["HomeSwitch"].Value = TryAxisRead(axisEnum, "HomeSwitch", "HomeSwitchActive", "AtHomeSwitch", "HomeSensor", "HomeInput"); r.Cells["Locked"].Value = ax.Locked ? "LOCKED" : "Free"; r.Cells["MotorCurrent"].Value = TryAxisRead(axisEnum, "MotorCurrent"); r.Cells["RelativePosition"].Value = TryAxisRead(axisEnum, "RelativePosition"); r.Cells["RelativeZero"].Value = TryAxisRead(axisEnum, "RelativeZero"); r.Cells["TravelMin"].Value = ax.TravelMin.ToString("F1"); r.Cells["TravelMax"].Value = ax.TravelMax.ToString("F1"); r.Cells["Programmable"].Value = ax.Programmable ? "YES" : "NO"; // Color homed status r.Cells["Homed"].Style.ForeColor = ax.Homed ? Color.Green : Color.Red; r.Cells["Locked"].Style.ForeColor = ax.Locked ? Color.Orange : Color.Green; } } } catch (Exception ex) { Log("Manipulator refresh error: " + ex.Message); } } // ==================== Utility ==================== private void SafeCall(Action action) { if (!connected) { MessageBox.Show("Not connected to InspectX. Use File > Connect first.", "Not Connected", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { action(); } catch (Exception ex) { Log("Error: " + ex.Message); MessageBox.Show("Operation failed: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Log(string message) { if (InvokeRequired) { BeginInvoke(new Action(Log), message); return; } string line = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + message + "\n"; txtLog.AppendText(line); txtLog.ScrollToCaret(); } private void ExportLog() { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; sfd.FileName = "InspectX_Diagnostic_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"; if (sfd.ShowDialog() == DialogResult.OK) { System.IO.File.WriteAllText(sfd.FileName, txtLog.Text); Log("Log exported to " + sfd.FileName); } } // ==================== Intensifier Tab ==================== private TabPage CreateIntensifierTab() { TabPage tab = new TabPage("Intensifier / ImageProcessing"); tab.AutoScroll = true; tab.Padding = new Padding(8); // ---------- Service / readback status ---------- GroupBox grpStatus = new GroupBox(); grpStatus.Text = "Service and field readbacks"; grpStatus.Location = new Point(10, 10); grpStatus.Size = new Size(360, 210); tab.Controls.Add(grpStatus); int y = 22; lblIntStatus = AddRowLabel(grpStatus, "Heartbeat:", "?", ref y); lblIntChannelOpen = AddRowLabel(grpStatus, "WCF channel:", "?", ref y); lblIntGetStatus = AddRowLabel(grpStatus, "GetStatus:", "?", ref y); lblIntFieldCount = AddRowLabel(grpStatus, "FieldCount call:", "?", ref y); lblIntFieldCurrent = AddRowLabel(grpStatus, "Field call:", "?", ref y); lblIntFieldStatusCount = AddRowLabel(grpStatus, "Status FieldCount:", "?", ref y); lblIntFieldStatusCurrent = AddRowLabel(grpStatus, "Status Field:", "?", ref y); btnIntRefresh = new Button(); btnIntRefresh.Text = "Refresh now"; btnIntRefresh.Location = new Point(246, 176); btnIntRefresh.Size = new Size(96, 24); btnIntRefresh.Click += new EventHandler(BtnIntRefresh_Click); grpStatus.Controls.Add(btnIntRefresh); // ---------- Controller status ---------- GroupBox grpController = new GroupBox(); grpController.Text = "ImageProcessing controller"; grpController.Location = new Point(380, 10); grpController.Size = new Size(360, 210); tab.Controls.Add(grpController); y = 22; lblIntControllerReady = AddRowLabel(grpController, "Ready:", "?", ref y); lblIntControllerComms = AddRowLabel(grpController, "Communications:", "?", ref y); lblIntControllerType = AddRowLabel(grpController, "Type:", "?", ref y); lblIntControllerVersion = AddRowLabel(grpController, "Version:", "?", ref y); lblIntControllerMode = AddRowLabel(grpController, "OperationMode:", "?", ref y); lblIntControllerVisible = AddRowLabel(grpController, "Visible:", "?", ref y); btnIntControllerInitialise = new Button(); btnIntControllerInitialise.Text = "Initialise"; btnIntControllerInitialise.Location = new Point(12, 176); btnIntControllerInitialise.Size = new Size(90, 24); btnIntControllerInitialise.Click += new EventHandler(BtnIntControllerInitialise_Click); grpController.Controls.Add(btnIntControllerInitialise); btnIntControllerClose = new Button(); btnIntControllerClose.Text = "Close"; btnIntControllerClose.Location = new Point(112, 176); btnIntControllerClose.Size = new Size(90, 24); btnIntControllerClose.Click += new EventHandler(BtnIntControllerClose_Click); grpController.Controls.Add(btnIntControllerClose); btnIntLogInterfaces = new Button(); btnIntLogInterfaces.Text = "Log interfaces"; btnIntLogInterfaces.Location = new Point(212, 176); btnIntLogInterfaces.Size = new Size(116, 24); btnIntLogInterfaces.Click += new EventHandler(BtnIntLogInterfaces_Click); grpController.Controls.Add(btnIntLogInterfaces); // ---------- Field control ---------- GroupBox grpField = new GroupBox(); grpField.Text = "Field control"; grpField.Location = new Point(750, 10); grpField.Size = new Size(300, 210); tab.Controls.Add(grpField); Label lblPick = new Label(); lblPick.Text = "Field:"; lblPick.Location = new Point(12, 26); lblPick.AutoSize = true; grpField.Controls.Add(lblPick); cmbIntField = new ComboBox(); cmbIntField.Location = new Point(62, 22); cmbIntField.Size = new Size(130, 22); cmbIntField.DropDownStyle = ComboBoxStyle.DropDownList; grpField.Controls.Add(cmbIntField); btnIntSetField = new Button(); btnIntSetField.Text = "Write + verify"; btnIntSetField.Location = new Point(198, 21); btnIntSetField.Size = new Size(90, 25); btnIntSetField.Click += new EventHandler(BtnIntSetField_Click); grpField.Controls.Add(btnIntSetField); btnIntProbeFields = new Button(); btnIntProbeFields.Text = "Probe reported fields"; btnIntProbeFields.Location = new Point(62, 52); btnIntProbeFields.Size = new Size(226, 25); btnIntProbeFields.Click += new EventHandler(BtnIntProbeFields_Click); grpField.Controls.Add(btnIntProbeFields); chkIntMirrorReadback = new CheckBox(); chkIntMirrorReadback.Text = "Mirror readback when dropdown is not focused"; chkIntMirrorReadback.Location = new Point(12, 84); chkIntMirrorReadback.Size = new Size(270, 22); chkIntMirrorReadback.Checked = true; grpField.Controls.Add(chkIntMirrorReadback); Label lblHelp = new Label(); lblHelp.Text = "This build treats FieldCount as zero-based.\r\n" + "If FieldCount is 1, the only reported field is 0.\r\n" + "A write is now verified by immediate and delayed\r\n" + "readback. If it returns to 0, the controller/service\r\n" + "did not accept another field as active."; lblHelp.Location = new Point(12, 112); lblHelp.Size = new Size(274, 82); lblHelp.ForeColor = Color.DimGray; grpField.Controls.Add(lblHelp); // ---------- Detector status ---------- GroupBox grpDetector = new GroupBox(); grpDetector.Text = "Detector and image status"; grpDetector.Location = new Point(10, 230); grpDetector.Size = new Size(360, 150); tab.Controls.Add(grpDetector); y = 22; lblIntDetectorName = AddRowLabel(grpDetector, "Detector:", "?", ref y); lblIntDetectorSize = AddRowLabel(grpDetector, "Size:", "?", ref y); lblIntDetectorResolution = AddRowLabel(grpDetector, "Resolution:", "?", ref y); lblIntImageLiveAvailable = AddRowLabel(grpDetector, "Live available:", "?", ref y); lblIntImageLiveActive = AddRowLabel(grpDetector, "Live active:", "?", ref y); lblIntGeometryDsd = AddRowLabel(grpDetector, "Source-detector:","?", ref y); // ---------- Detector parameter box ---------- GroupBox grpDet = new GroupBox(); grpDet.Text = "Detector parameters"; grpDet.Location = new Point(380, 230); grpDet.Size = new Size(360, 235); tab.Controls.Add(grpDet); AddDetHeader(grpDet); int dy = 44; lblIntExpRead = AddDetRow(grpDet, "Exposure", out nudIntExposure, 0, 10000000, 0, dy); dy += 26; lblIntGainRead = AddDetRow(grpDet, "Gain", out nudIntGain, 0, 100000, 0, dy); dy += 26; lblIntDigGainRead = AddDetRow(grpDet, "DigitalGain", out nudIntDigGain, 0, 100000, 0, dy); dy += 26; lblIntBrightRead = AddDetRow(grpDet, "Brightness", out nudIntBrightness, -100000, 100000, 0, dy); dy += 26; lblIntBinningRead = AddDetRow(grpDet, "Binning", out nudIntBinning, 0, 64, 0, dy); dy += 26; lblIntAccumRead = AddDetRow(grpDet, "Accumulation", out nudIntAccum, 0, 1000, 0, dy); dy += 30; btnIntApplyDet = new Button(); btnIntApplyDet.Text = "Apply + verify detector parameters"; btnIntApplyDet.Location = new Point(12, dy); btnIntApplyDet.Size = new Size(250, 26); btnIntApplyDet.Click += new EventHandler(BtnIntApplyDet_Click); grpDet.Controls.Add(btnIntApplyDet); // ---------- Image command box ---------- GroupBox grpImg = new GroupBox(); grpImg.Text = "Image commands"; grpImg.Location = new Point(750, 230); grpImg.Size = new Size(300, 150); tab.Controls.Add(grpImg); btnIntLive = new Button(); btnIntLive.Text = "Live / toggle"; btnIntLive.Location = new Point(12, 24); btnIntLive.Size = new Size(100, 28); btnIntLive.Click += new EventHandler(BtnIntLive_Click); grpImg.Controls.Add(btnIntLive); btnIntCapture = new Button(); btnIntCapture.Text = "Capture"; btnIntCapture.Location = new Point(122, 24); btnIntCapture.Size = new Size(80, 28); btnIntCapture.Click += new EventHandler(BtnIntCapture_Click); grpImg.Controls.Add(btnIntCapture); btnIntAverage = new Button(); btnIntAverage.Text = "Average"; btnIntAverage.Location = new Point(12, 62); btnIntAverage.Size = new Size(80, 28); btnIntAverage.Click += new EventHandler(BtnIntAverage_Click); grpImg.Controls.Add(btnIntAverage); nudIntAvgFrames = new NumericUpDown(); nudIntAvgFrames.Location = new Point(102, 65); nudIntAvgFrames.Size = new Size(70, 22); nudIntAvgFrames.Minimum = 2; nudIntAvgFrames.Maximum = 512; nudIntAvgFrames.Value = 8; grpImg.Controls.Add(nudIntAvgFrames); Label lblFrames = new Label(); lblFrames.Text = "frames"; lblFrames.Location = new Point(178, 68); lblFrames.AutoSize = true; grpImg.Controls.Add(lblFrames); btnIntSaveTiff = new Button(); btnIntSaveTiff.Text = "Save TIFF..."; btnIntSaveTiff.Location = new Point(12, 100); btnIntSaveTiff.Size = new Size(100, 28); btnIntSaveTiff.Click += new EventHandler(BtnIntSaveTiff_Click); grpImg.Controls.Add(btnIntSaveTiff); // ---------- Direct MiscIO field switch ---------- GroupBox grpDirect = new GroupBox(); grpDirect.Text = "Direct field switch through InspectXUtilities.MiscIO"; grpDirect.Location = new Point(10, 475); grpDirect.Size = new Size(1040, 160); tab.Controls.Add(grpDirect); Label lblDirect1 = new Label(); lblDirect1.Text = "This bypasses ImageProcessing IPC and MIL/Sapera. It writes MiscIO.DigitalOutput(channel 1, field)."; lblDirect1.Location = new Point(12, 22); lblDirect1.Size = new Size(820, 18); lblDirect1.ForeColor = Color.DimGray; grpDirect.Controls.Add(lblDirect1); Label lblDirect2 = new Label(); lblDirect2.Text = "Field:"; lblDirect2.Location = new Point(12, 52); lblDirect2.AutoSize = true; grpDirect.Controls.Add(lblDirect2); cmbDirectField = new ComboBox(); cmbDirectField.Location = new Point(60, 48); cmbDirectField.Size = new Size(180, 22); cmbDirectField.DropDownStyle = ComboBoxStyle.DropDownList; cmbDirectField.Items.Add(new FieldChoice(0, "0 - largest / default")); cmbDirectField.Items.Add(new FieldChoice(1, "1 - second field")); cmbDirectField.Items.Add(new FieldChoice(2, "2 - third field")); cmbDirectField.Items.Add(new FieldChoice(3, "3 - fourth field")); cmbDirectField.SelectedIndex = 0; grpDirect.Controls.Add(cmbDirectField); btnDirectInit = new Button(); btnDirectInit.Text = "Open direct IO"; btnDirectInit.Location = new Point(255, 47); btnDirectInit.Size = new Size(110, 25); btnDirectInit.Click += new EventHandler(BtnDirectInit_Click); grpDirect.Controls.Add(btnDirectInit); btnDirectWrite = new Button(); btnDirectWrite.Text = "Write direct"; btnDirectWrite.Location = new Point(375, 47); btnDirectWrite.Size = new Size(100, 25); btnDirectWrite.Click += new EventHandler(BtnDirectWrite_Click); grpDirect.Controls.Add(btnDirectWrite); btnDirectRelease = new Button(); btnDirectRelease.Text = "Release IO"; btnDirectRelease.Location = new Point(485, 47); btnDirectRelease.Size = new Size(90, 25); btnDirectRelease.Click += new EventHandler(BtnDirectRelease_Click); grpDirect.Controls.Add(btnDirectRelease); Label lblDirectStatusCaption = new Label(); lblDirectStatusCaption.Text = "Direct IO status:"; lblDirectStatusCaption.Location = new Point(12, 86); lblDirectStatusCaption.AutoSize = true; grpDirect.Controls.Add(lblDirectStatusCaption); lblDirectMiscIOStatus = new Label(); lblDirectMiscIOStatus.Text = "not opened"; lblDirectMiscIOStatus.Location = new Point(125, 86); lblDirectMiscIOStatus.Size = new Size(880, 18); lblDirectMiscIOStatus.ForeColor = Color.Navy; grpDirect.Controls.Add(lblDirectMiscIOStatus); Label lblToggleCaption = new Label(); lblToggleCaption.Text = "Debug toggle 0 <-> 1:"; lblToggleCaption.Location = new Point(600, 52); lblToggleCaption.AutoSize = true; grpDirect.Controls.Add(lblToggleCaption); cmbDirectToggleInterval = new ComboBox(); cmbDirectToggleInterval.Location = new Point(735, 48); cmbDirectToggleInterval.Size = new Size(85, 22); cmbDirectToggleInterval.DropDownStyle = ComboBoxStyle.DropDownList; cmbDirectToggleInterval.Items.Add("1 sec"); cmbDirectToggleInterval.Items.Add("5 sec"); cmbDirectToggleInterval.SelectedIndex = 1; grpDirect.Controls.Add(cmbDirectToggleInterval); btnDirectToggleStart = new Button(); btnDirectToggleStart.Text = "Start toggle"; btnDirectToggleStart.Location = new Point(830, 47); btnDirectToggleStart.Size = new Size(95, 25); btnDirectToggleStart.Click += new EventHandler(BtnDirectToggleStart_Click); grpDirect.Controls.Add(btnDirectToggleStart); btnDirectToggleStop = new Button(); btnDirectToggleStop.Text = "Stop"; btnDirectToggleStop.Location = new Point(930, 47); btnDirectToggleStop.Size = new Size(70, 25); btnDirectToggleStop.Click += new EventHandler(BtnDirectToggleStop_Click); grpDirect.Controls.Add(btnDirectToggleStop); lblDirectToggleStatus = new Label(); lblDirectToggleStatus.Text = "toggle stopped"; lblDirectToggleStatus.Location = new Point(600, 86); lblDirectToggleStatus.Size = new Size(400, 18); lblDirectToggleStatus.ForeColor = Color.Navy; grpDirect.Controls.Add(lblDirectToggleStatus); Label lblToggleNote = new Label(); lblToggleNote.Text = "Writes field 0 then 1 repeatedly until Stop. Direct IO is opened automatically if needed."; lblToggleNote.Location = new Point(12, 120); lblToggleNote.Size = new Size(980, 18); lblToggleNote.ForeColor = Color.DimGray; grpDirect.Controls.Add(lblToggleNote); directFieldToggleTimer = new System.Windows.Forms.Timer(); directFieldToggleTimer.Tick += new EventHandler(DirectFieldToggleTimer_Tick); // ---------- Diagnostic explanation / snapshot ---------- GroupBox grpDiag = new GroupBox(); grpDiag.Text = "Interpretation and raw snapshot"; grpDiag.Location = new Point(10, 650); grpDiag.Size = new Size(1040, 195); tab.Controls.Add(grpDiag); txtIntDiag = new RichTextBox(); txtIntDiag.Dock = DockStyle.Fill; txtIntDiag.ReadOnly = true; txtIntDiag.Font = new Font("Consolas", 9f); txtIntDiag.BackColor = Color.White; grpDiag.Controls.Add(txtIntDiag); return tab; } // -- helper: add a "label : value" row inside a groupbox -- private Label AddRowLabel(Control parent, string caption, string initial, ref int y) { Label cap = new Label(); cap.Text = caption; cap.Location = new Point(12, y); cap.AutoSize = true; parent.Controls.Add(cap); Label val = new Label(); val.Text = initial; val.Location = new Point(145, y); val.AutoSize = true; val.ForeColor = Color.Navy; parent.Controls.Add(val); y += 20; return val; } // -- helper: detector-param header -- private void AddDetHeader(Control parent) { int x0 = 12, x1 = 132, x2 = 228; Label[] h = new Label[] { MkHeader("Parameter", x0, 22), MkHeader("Current", x1, 22), MkHeader("New value", x2, 22) }; foreach (Label l in h) parent.Controls.Add(l); } private Label MkHeader(string t, int x, int y) { Label l = new Label(); l.Text = t; l.Location = new Point(x, y); l.AutoSize = true; l.Font = new Font(Font, FontStyle.Bold); return l; } // -- helper: one detector-param row -- private Label AddDetRow(Control parent, string name, out NumericUpDown nud, decimal min, decimal max, decimal def, int y) { Label nm = new Label(); nm.Text = name; nm.Location = new Point(12, y + 3); nm.AutoSize = true; parent.Controls.Add(nm); Label read = new Label(); read.Text = "?"; read.Location = new Point(132, y + 3); read.AutoSize = true; read.ForeColor = Color.Navy; parent.Controls.Add(read); nud = new NumericUpDown(); nud.Location = new Point(228, y); nud.Size = new Size(110, 22); nud.Minimum = min; nud.Maximum = max; nud.Value = def; parent.Controls.Add(nud); return read; } private class FieldChoice { public uint Value; private string mText; public FieldChoice(uint value, string text) { Value = value; mText = text; } public override string ToString() { return mText; } } // -- button handlers -- private void BtnDirectInit_Click(object sender, EventArgs e) { OpenDirectMiscIO(true); } private void BtnDirectWrite_Click(object sender, EventArgs e) { uint field; if (!TryGetSelectedDirectField(out field)) { Log("Direct MiscIO: select a field first."); return; } WriteDirectIntensifierField(field, "manual"); } private void BtnDirectToggleStart_Click(object sender, EventArgs e) { if (!OpenDirectMiscIO(true)) return; int intervalMs = 5000; if (cmbDirectToggleInterval != null && cmbDirectToggleInterval.SelectedIndex == 0) intervalMs = 1000; directFieldToggleState = false; directFieldToggleWrites = 0; directFieldToggleTimer.Interval = intervalMs; directFieldToggleTimer.Start(); if (btnDirectToggleStart != null) btnDirectToggleStart.Enabled = false; if (btnDirectToggleStop != null) btnDirectToggleStop.Enabled = true; SetDirectToggleStatus("toggle running every " + (intervalMs / 1000).ToString() + " sec; next write field 0", Color.Green); Log("Direct MiscIO toggle started: writing field 0 and field 1 alternately every " + (intervalMs / 1000).ToString() + " second(s). Use Stop to end it."); // Fire the first write immediately so you do not have to wait for the first timer tick. DirectFieldToggleTimer_Tick(sender, e); } private void BtnDirectToggleStop_Click(object sender, EventArgs e) { StopDirectFieldToggle("user stopped"); } private void DirectFieldToggleTimer_Tick(object sender, EventArgs e) { uint field = directFieldToggleState ? (uint)1 : (uint)0; directFieldToggleState = !directFieldToggleState; directFieldToggleWrites++; bool ok = WriteDirectIntensifierField(field, "toggle #" + directFieldToggleWrites.ToString()); if (ok) { SetDirectToggleStatus("toggle running: wrote field " + field + " at " + DateTime.Now.ToString("HH:mm:ss") + "; next " + (directFieldToggleState ? "1" : "0"), Color.Green); } else { StopDirectFieldToggle("stopped after failed write"); } } private void StopDirectFieldToggle(string reason) { if (directFieldToggleTimer != null) directFieldToggleTimer.Stop(); if (btnDirectToggleStart != null) btnDirectToggleStart.Enabled = true; if (btnDirectToggleStop != null) btnDirectToggleStop.Enabled = true; SetDirectToggleStatus("toggle stopped: " + reason, Color.Navy); Log("Direct MiscIO toggle stopped: " + reason + "; total writes=" + directFieldToggleWrites.ToString()); } private bool WriteDirectIntensifierField(uint field, string source) { if (!OpenDirectMiscIO(true)) return false; try { PropertyInfo pi = directMiscIO.GetType().GetProperty("IntensifierField"); if (pi == null || !pi.CanWrite) { SetDirectMiscIOStatus("InspectXUtilities.MiscIO.IntensifierField setter not found", Color.Red); Log("Direct MiscIO: IntensifierField setter not found."); return false; } pi.SetValue(directMiscIO, (int)field, null); SetDirectMiscIOStatus("wrote field " + field + " through MiscIO.DigitalOutput(1, " + field + ")", Color.Green); Log("Direct MiscIO " + source + ": wrote IntensifierField=" + field + " at " + DateTime.Now.ToString("HH:mm:ss.fff") + " (MiscIO.DigitalOutput channel 1). This path has no readback property."); return true; } catch (Exception ex) { Exception ux = UnwrapException(ex); string msg = ux.GetType().Name + ": " + ux.Message; SetDirectMiscIOStatus("direct write failed: " + msg, Color.Red); Log("Direct MiscIO " + source + " write failed: " + msg); return false; } } private void BtnDirectRelease_Click(object sender, EventArgs e) { StopDirectFieldToggle("IO released"); ReleaseDirectMiscIO(true); } private bool TryGetSelectedDirectField(out uint value) { value = 0; if (cmbDirectField == null || cmbDirectField.SelectedItem == null) return false; FieldChoice fc = cmbDirectField.SelectedItem as FieldChoice; if (fc != null) { value = fc.Value; return true; } return UInt32.TryParse(cmbDirectField.SelectedItem.ToString(), out value); } private bool OpenDirectMiscIO(bool logResult) { if (directMiscIO != null) { if (logResult) SetDirectMiscIOStatus("already open", Color.Green); return true; } try { string baseDir = AppDomain.CurrentDomain.BaseDirectory; string dllPath = System.IO.Path.Combine(baseDir, "InspectXUtilities.dll"); if (!System.IO.File.Exists(dllPath)) dllPath = System.IO.Path.Combine(Environment.CurrentDirectory, "InspectXUtilities.dll"); if (!System.IO.File.Exists(dllPath)) dllPath = @"C:\Program Files\Nikon Metrology\Inspect-X\InspectXUtilities.dll"; if (!System.IO.File.Exists(dllPath)) dllPath = @"C:\Program Files (x86)\Nikon Metrology\Inspect-X\InspectXUtilities.dll"; if (!System.IO.File.Exists(dllPath)) { SetDirectMiscIOStatus("InspectXUtilities.dll not found", Color.Red); if (logResult) Log("Direct MiscIO: InspectXUtilities.dll not found beside this executable or in the common Inspect-X folders."); return false; } Assembly asm = Assembly.LoadFrom(dllPath); Type t = asm.GetType("InspectXUtilities.MiscIO"); if (t == null) { SetDirectMiscIOStatus("InspectXUtilities.MiscIO type not found in " + dllPath, Color.Red); if (logResult) Log("Direct MiscIO: type InspectXUtilities.MiscIO not found in " + dllPath); return false; } directMiscIO = Activator.CreateInstance(t); SetDirectMiscIOStatus("open via " + dllPath, Color.Green); SetMiscIOStatus("open via " + dllPath, Color.Green); if (logResult) { Log("Direct MiscIO opened from " + dllPath); Log("Direct MiscIO path: InspectXUtilities.MiscIO.IntensifierField -> native MiscIO.dll DigitalOutput(1, field)."); } return true; } catch (Exception ex) { Exception ux = UnwrapException(ex); string msg = ux.GetType().Name + ": " + ux.Message; directMiscIO = null; SetDirectMiscIOStatus("open failed: " + msg, Color.Red); SetMiscIOStatus("open failed: " + msg, Color.Red); if (logResult) Log("Direct MiscIO open failed: " + msg); return false; } } private void ReleaseDirectMiscIO(bool logResult) { if (directFieldToggleTimer != null && directFieldToggleTimer.Enabled) StopDirectFieldToggle("IO released"); if (directMiscIO == null) { if (logResult) SetDirectMiscIOStatus("not open", Color.Navy); return; } try { IDisposable d = directMiscIO as IDisposable; if (d != null) d.Dispose(); else TryCall(directMiscIO, "Dispose"); if (logResult) Log("Direct MiscIO released."); } catch (Exception ex) { if (logResult) Log("Direct MiscIO release failed: " + UnwrapException(ex).Message); } directMiscIO = null; SetDirectMiscIOStatus("released", Color.Navy); SetMiscIOStatus("released", Color.Navy); } private void SetDirectMiscIOStatus(string text, Color color) { if (lblDirectMiscIOStatus != null) { lblDirectMiscIOStatus.Text = text; lblDirectMiscIOStatus.ForeColor = color; } } private void SetDirectToggleStatus(string text, Color color) { if (lblDirectToggleStatus != null) { lblDirectToggleStatus.Text = text; lblDirectToggleStatus.ForeColor = color; } } private void BtnMiscOpen_Click(object sender, EventArgs e) { if (OpenDirectMiscIO(true)) { SetMiscIOStatus("open", Color.Green); UpdateMiscIODiagnosticText(false); } } private void BtnMiscRelease_Click(object sender, EventArgs e) { ReleaseDirectMiscIO(true); SetMiscIOStatus("released", Color.Navy); UpdateMiscIODiagnosticText(false); } private void BtnMiscDigitalRead_Click(object sender, EventArgs e) { if (!OpenDirectMiscIO(true)) return; int index = (int)nudMiscDigitalIndex.Value; object value; if (TryInvokeMiscIOMethod("DigitalInput", out value, index)) { string s = FormatOptionalValue(value); lblMiscDigitalRead.Text = "readback index " + index.ToString() + ": " + s; lblMiscDigitalRead.ForeColor = Color.Green; Log("MiscIO.DigitalInput(" + index.ToString() + ") -> " + s); } else { lblMiscDigitalRead.Text = "DigitalInput not available or failed"; lblMiscDigitalRead.ForeColor = Color.Red; Log("MiscIO.DigitalInput(" + index.ToString() + ") failed or method unavailable."); } } private void BtnMiscDigitalWrite_Click(object sender, EventArgs e) { if (!OpenDirectMiscIO(true)) return; int index = (int)nudMiscDigitalIndex.Value; int value = (int)nudMiscDigitalValue.Value; object ignored; if (TryInvokeMiscIOMethod("DigitalOutput", out ignored, index, value)) { lblMiscDigitalRead.Text = "wrote DigitalOutput(" + index.ToString() + ", " + value.ToString() + ")"; lblMiscDigitalRead.ForeColor = Color.Green; Log("MiscIO.DigitalOutput(" + index.ToString() + ", " + value.ToString() + ") wrote at " + DateTime.Now.ToString("HH:mm:ss.fff")); } else { lblMiscDigitalRead.Text = "DigitalOutput not available or failed"; lblMiscDigitalRead.ForeColor = Color.Red; Log("MiscIO.DigitalOutput(" + index.ToString() + ", " + value.ToString() + ") failed or method unavailable."); } } private void BtnMiscAnalogRead_Click(object sender, EventArgs e) { if (!OpenDirectMiscIO(true)) return; int index = (int)nudMiscAnalogIndex.Value; object value; if (TryInvokeMiscIOMethod("AnalogInput", out value, index)) { string s = FormatOptionalValue(value); lblMiscAnalogRead.Text = "readback index " + index.ToString() + ": " + s; lblMiscAnalogRead.ForeColor = Color.Green; Log("MiscIO.AnalogInput(" + index.ToString() + ") -> " + s); } else { lblMiscAnalogRead.Text = "AnalogInput not available or failed"; lblMiscAnalogRead.ForeColor = Color.Red; Log("MiscIO.AnalogInput(" + index.ToString() + ") failed or method unavailable."); } } private void BtnMiscAnalogWrite_Click(object sender, EventArgs e) { if (!OpenDirectMiscIO(true)) return; int index = (int)nudMiscAnalogIndex.Value; float value = (float)nudMiscAnalogValue.Value; object ignored; if (TryInvokeMiscIOMethod("AnalogOutput", out ignored, index, value)) { lblMiscAnalogRead.Text = "wrote AnalogOutput(" + index.ToString() + ", " + value.ToString("F3") + ")"; lblMiscAnalogRead.ForeColor = Color.Green; Log("MiscIO.AnalogOutput(" + index.ToString() + ", " + value.ToString("F3") + ") wrote at " + DateTime.Now.ToString("HH:mm:ss.fff")); } else { lblMiscAnalogRead.Text = "AnalogOutput not available or failed"; lblMiscAnalogRead.ForeColor = Color.Red; Log("MiscIO.AnalogOutput(" + index.ToString() + ", " + value.ToString("F3") + ") failed or method unavailable."); } } private void BtnMiscIrisWrite_Click(object sender, EventArgs e) { if (!OpenDirectMiscIO(true)) return; decimal percent = nudMiscIrisPercent.Value; decimal scaling = nudMiscIrisScaling.Value; float volts = (float)((percent * scaling) / 100M); if (WriteDirectIrisDemand(volts, "manual iris shortcut")) { SetMiscIrisStatus("wrote " + volts.ToString("F3") + " V from " + percent.ToString("F1") + "% @ " + scaling.ToString("F2") + " V scale", Color.Green); } else { SetMiscIrisStatus("iris write failed", Color.Red); } } private void BtnMiscSnapshot_Click(object sender, EventArgs e) { UpdateMiscIODiagnosticText(true); } private void SetMiscIOStatus(string text, Color color) { if (lblMiscIOStatus != null) { lblMiscIOStatus.Text = text; lblMiscIOStatus.ForeColor = color; } } private void SetMiscIrisStatus(string text, Color color) { if (lblMiscIrisStatus != null) { lblMiscIrisStatus.Text = text; lblMiscIrisStatus.ForeColor = color; } } private bool WriteDirectIrisDemand(float volts, string source) { if (!OpenDirectMiscIO(true)) return false; try { PropertyInfo pi = directMiscIO.GetType().GetProperty("IrisDemand", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); if (pi != null) { MethodInfo setter = pi.GetSetMethod(true); if (setter != null) { object target = setter.IsStatic ? null : directMiscIO; pi.SetValue(target, volts, null); Log("Direct MiscIO " + source + ": set IrisDemand=" + volts.ToString("F3") + " V. Binary path: MiscIO.IrisDemand -> AnalogOutput(0, volts)."); return true; } } object ignored; if (TryInvokeMiscIOMethod("AnalogOutput", out ignored, 0, volts)) { Log("Direct MiscIO " + source + ": fallback AnalogOutput(0, " + volts.ToString("F3") + ") wrote."); return true; } Log("Direct MiscIO " + source + ": IrisDemand setter and AnalogOutput fallback were not available."); return false; } catch (Exception ex) { Exception ux = UnwrapException(ex); Log("Direct MiscIO " + source + " iris write failed: " + ux.GetType().Name + ": " + ux.Message); return false; } } private bool TryInvokeMiscIOMethod(string methodName, out object returnValue, params object[] args) { returnValue = null; if (directMiscIO == null) return false; try { MethodInfo mi = FindMiscIOMethod(methodName, args.Length); if (mi == null) return false; object target = mi.IsStatic ? null : directMiscIO; returnValue = mi.Invoke(target, args); return true; } catch (Exception ex) { Exception ux = UnwrapException(ex); Log("MiscIO." + methodName + " failed: " + ux.GetType().Name + ": " + ux.Message); return false; } } private MethodInfo FindMiscIOMethod(string methodName, int parameterCount) { if (directMiscIO == null) return null; BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; MethodInfo[] methods = directMiscIO.GetType().GetMethods(flags); foreach (MethodInfo mi in methods) { if (mi.Name != methodName) continue; ParameterInfo[] ps = mi.GetParameters(); if (ps.Length == parameterCount) return mi; } return null; } private void UpdateMiscIODiagnosticText(bool readNow) { if (txtMiscIODiag == null) return; StringBuilder sb = new StringBuilder(); sb.AppendLine("MiscIO binary account"); sb.AppendLine("====================="); sb.AppendLine("Managed wrapper: InspectXUtilities.MiscIO"); sb.AppendLine("Native DLL: MiscIO.dll"); sb.AppendLine("Native exported functions: Initialise, Terminate, DigitalOutput, DigitalInput, AnalogOutput, AnalogInput"); sb.AppendLine(); sb.AppendLine("Managed methods/properties discovered:"); sb.AppendLine(" new MiscIO() -> calls Initialise(); throws if it returns false"); sb.AppendLine(" Dispose() -> calls Terminate()"); sb.AppendLine(" DigitalOutput(int index, int value)"); sb.AppendLine(" DigitalInput(int index) -> int"); sb.AppendLine(" AnalogOutput(int index, float value)"); sb.AppendLine(" AnalogInput(int index) -> float"); sb.AppendLine(" IntensifierField setter -> DigitalOutput(1, field)"); sb.AppendLine(" IrisDemand setter -> AnalogOutput(0, volts)"); sb.AppendLine(); sb.AppendLine("Imaging.dll paths discovered:"); sb.AppendLine(" ImageProcessingControl.IntensifierField = n -> mMiscIO.IntensifierField = n, if UseMiscIO is enabled"); sb.AppendLine(" ImageProcessingControl.IrisDemand = percent -> mMiscIO.IrisDemand = IrisDemandVoltageScaling * percent / 100"); sb.AppendLine(" ImageProcessingControl creates MiscIO early in Initialise(), before most camera acquisition setup, when UseMiscIO is enabled"); sb.AppendLine(); sb.AppendLine("MiscIO.dll configuration strings found:"); sb.AppendLine(" MiscIO.ini, Type, Devices, Count, Ports, Port%i, DigitalIOs, DigitalIO%i, AnalogIOs, AnalogIO%i"); sb.AppendLine(" Digital entries include Device, DevicePort, Direction, Invert, Port, Bit0, Bits, Usage"); sb.AppendLine(" Analog entries include Channel and Range"); sb.AppendLine(); sb.AppendLine("Practical meaning:"); sb.AppendLine(" Iris can be controlled outside the Imaging module through MiscIO analog output channel 0 if MiscIO initialises on this PC."); sb.AppendLine(" This is independent of MIL/Sapera live image acquisition, but it still depends on the configured IO board and MiscIO.ini/device drivers."); sb.AppendLine(" Field switching through MiscIO writes digital output index 1, but your measured wiring may be on a different output or downstream relay path."); sb.AppendLine(); if (readNow) { sb.AppendLine("Read snapshot"); sb.AppendLine("-------------"); if (!OpenDirectMiscIO(true)) { sb.AppendLine("Could not open MiscIO; see Diagnostic Log for the exception."); } else { sb.AppendLine("Digital inputs 0..7:"); for (int i = 0; i < 8; i++) { object value; if (TryInvokeMiscIOMethod("DigitalInput", out value, i)) sb.AppendLine(" D" + i.ToString() + " = " + FormatOptionalValue(value)); else sb.AppendLine(" D" + i.ToString() + " = read failed/unavailable"); } sb.AppendLine("Analog inputs 0..3:"); for (int i = 0; i < 4; i++) { object value; if (TryInvokeMiscIOMethod("AnalogInput", out value, i)) sb.AppendLine(" A" + i.ToString() + " = " + FormatOptionalValue(value)); else sb.AppendLine(" A" + i.ToString() + " = read failed/unavailable"); } } } else { sb.AppendLine("Click Refresh snapshot to try DigitalInput 0..7 and AnalogInput 0..3."); } txtMiscIODiag.Text = sb.ToString(); } private Exception UnwrapException(Exception ex) { while (ex is TargetInvocationException && ex.InnerException != null) ex = ex.InnerException; return ex; } private void BtnIntRefresh_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } try { RefreshIntensifier(); } catch (Exception ex) { Log("Intensifier refresh failed: " + ex.Message); } } private void BtnIntSetField_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } uint target; if (!TryGetSelectedField(out target)) { Log("Select a reported field first."); return; } SafeCall(delegate { WriteIntensifierFieldAndVerify(target, "manual selected field"); }); } private void BtnIntProbeFields_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } SafeCall(delegate { uint count; if (!TryReadUInt32(imageChannel.Intensifier, "FieldCount", out count)) count = 0; uint original; bool haveOriginal = TryReadUInt32(imageChannel.Intensifier, "Field", out original); uint max = count; if (max == 0) max = 1; if (max > 16) max = 16; Log("Probing Intensifier.Field writes for reported zero-based range 0.." + (max - 1).ToString() + " (FieldCount=" + count + ")"); for (uint i = 0; i < max; i++) { WriteIntensifierFieldAndVerify(i, "probe"); } if (haveOriginal) { Log("Restoring original field readback " + original); WriteIntensifierFieldAndVerify(original, "restore after probe"); } }); } private void BtnIntControllerInitialise_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } SafeCall(delegate { Log("Controller.Initialise() ..."); if (TryCall(imageChannel.Controller, "Initialise")) Log(" Controller.Initialise -> ok"); else Log(" Controller.Initialise method is not exposed by this IPC wrapper."); System.Threading.Thread.Sleep(250); RefreshIntensifier(); }); } private void BtnIntControllerClose_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } SafeCall(delegate { Log("Controller.Close() ..."); if (TryCall(imageChannel.Controller, "Close")) Log(" Controller.Close -> ok"); else Log(" Controller.Close method is not exposed by this IPC wrapper."); System.Threading.Thread.Sleep(250); RefreshIntensifier(); }); } private void BtnIntLogInterfaces_Click(object sender, EventArgs e) { LogImageProcessingInterfaces(); } private void BtnIntApplyDet_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } SafeCall(delegate { ApplyIntOne("Exposure", (int)nudIntExposure.Value); ApplyIntOne("Gain", (int)nudIntGain.Value); ApplyIntOne("DigitalGain", (int)nudIntDigGain.Value); ApplyIntOne("Brightness", (int)nudIntBrightness.Value); ApplyIntOne("Binning", (int)nudIntBinning.Value); ApplyIntOne("Accumulation", (int)nudIntAccum.Value); RefreshIntensifier(); }); } private void ApplyIntOne(string name, int value) { object before = TryInvoke(imageChannel.DetectorParameters, name); bool ok = TryCall(imageChannel.DetectorParameters, name, value); System.Threading.Thread.Sleep(60); object after = TryInvoke(imageChannel.DetectorParameters, name); if (ok) Log("DetectorParameters." + name + "(" + value + ") -> ok; readback " + FormatOptionalValue(before) + " -> " + FormatOptionalValue(after)); else Log("DetectorParameters." + name + " setter is not exposed or rejected; readback remains " + FormatOptionalValue(after)); } private void BtnIntLive_Click(object sender, EventArgs e) { RunImageCommand("Image.Live", delegate { return TryCall(imageChannel.Image, "Live"); }); } private void BtnIntCapture_Click(object sender, EventArgs e) { RunImageCommand("Image.Capture", delegate { return TryCall(imageChannel.Image, "Capture"); }); } private void BtnIntAverage_Click(object sender, EventArgs e) { int n = (int)nudIntAvgFrames.Value; RunImageCommand("Image.Average(" + n + ")", delegate { return TryCall(imageChannel.Image, "Average", n, true); }); } private delegate bool ImageCommandInvoker(); private void RunImageCommand(string name, ImageCommandInvoker call) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } SafeCall(delegate { object beforeActive = GetImageStatusProperty("LiveActive"); Log(name + " ... LiveActive before=" + FormatOptionalValue(beforeActive)); bool ok = call(); System.Threading.Thread.Sleep(200); RefreshIntensifier(); object afterActive = GetImageStatusProperty("LiveActive"); Log(" " + name + (ok ? " -> ok" : " -> method not exposed or rejected") + "; LiveActive after=" + FormatOptionalValue(afterActive)); }); } private void BtnIntSaveTiff_Click(object sender, EventArgs e) { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } using (SaveFileDialog sfd = new SaveFileDialog()) { sfd.Filter = "TIFF|*.tif;*.tiff"; sfd.FileName = "frame.tif"; if (sfd.ShowDialog(this) != DialogResult.OK) return; string path = sfd.FileName; SafeCall(delegate { bool ok = TryCall(imageChannel.Image, "SaveAsTiff", path, true, true, true); Log("Image.SaveAsTiff(\"" + path + "\")" + (ok ? " -> ok" : " -> method not exposed or rejected")); }); } } // ==================== Intensifier refresh ==================== private void RefreshIntensifier() { if (imageChannel == null) return; object entireStatus = null; object controllerStatus = null; object detectorStatus = null; object detectorParametersStatus = null; object intensifierStatus = null; object geometryStatus = null; object imageStatus = null; // Service heartbeat: proves the WCF ImageProcessing service endpoint answered. try { bool hb = imageChannel.Heartbeat(); lblIntStatus.Text = hb ? "alive" : "no heartbeat"; lblIntStatus.ForeColor = hb ? Color.Green : Color.Red; } catch (Exception ex) { lblIntStatus.Text = "err: " + ShortError(ex); lblIntStatus.ForeColor = Color.Red; } try { lblIntChannelOpen.Text = imageChannel.IsOpen() ? "open" : "not open"; lblIntChannelOpen.ForeColor = imageChannel.IsOpen() ? Color.Green : Color.Red; } catch (Exception ex) { lblIntChannelOpen.Text = "err: " + ShortError(ex); lblIntChannelOpen.ForeColor = Color.Red; } entireStatus = TryInvoke(imageChannel, "GetStatus"); if (entireStatus == null) entireStatus = TryInvoke(imageChannel, "GetImageProcessingEntireStatus"); lblIntGetStatus.Text = entireStatus == null ? "not returned" : entireStatus.GetType().Name; lblIntGetStatus.ForeColor = entireStatus == null ? Color.OrangeRed : Color.Green; if (entireStatus != null) { controllerStatus = TryGetProperty(entireStatus, "ControllerStatus"); detectorStatus = TryGetProperty(entireStatus, "DetectorStatus"); detectorParametersStatus = TryGetProperty(entireStatus, "DetectorParametersStatus"); intensifierStatus = TryGetProperty(entireStatus, "IntensifierStatus"); geometryStatus = TryGetProperty(entireStatus, "GeometryStatus"); imageStatus = TryGetProperty(entireStatus, "ImageStatus"); } RefreshControllerReadback(controllerStatus); RefreshIntensifierReadback(intensifierStatus); RefreshDetectorReadback(detectorStatus, geometryStatus, imageStatus); RefreshDetectorParameterReadback(detectorParametersStatus); UpdateIntensifierDiagnosticText(entireStatus, controllerStatus, detectorStatus, detectorParametersStatus, intensifierStatus, geometryStatus, imageStatus); } private void RefreshControllerReadback(object controllerStatus) { object ready = FirstNonNull(TryInvoke(imageChannel.Controller, "Ready"), TryGetProperty(controllerStatus, "Ready")); object comms = FirstNonNull(TryInvoke(imageChannel.Controller, "Communications"), TryGetProperty(controllerStatus, "Communications")); object type = FirstNonNull(TryInvoke(imageChannel.Controller, "Type"), TryGetProperty(controllerStatus, "Type")); object version = FirstNonNull(TryInvoke(imageChannel.Controller, "Version"), TryGetProperty(controllerStatus, "Version")); object mode = FirstNonNull(TryInvoke(imageChannel.Controller, "OperationMode"), TryGetProperty(controllerStatus, "OperationMode")); object visible = FirstNonNull(TryInvoke(imageChannel.Controller, "Visible"), TryGetProperty(controllerStatus, "Visible")); SetLabelValue(lblIntControllerReady, ready, true); SetLabelValue(lblIntControllerComms, comms, true); SetLabelValue(lblIntControllerType, type, false); SetLabelValue(lblIntControllerVersion, version, false); SetLabelValue(lblIntControllerMode, mode, false); SetLabelValue(lblIntControllerVisible, visible, false); } private void RefreshIntensifierReadback(object intensifierStatus) { uint count = 0, cur = 0, statusCount = 0, statusCur = 0; bool gotCount = TryReadUInt32(imageChannel.Intensifier, "FieldCount", out count); bool gotCur = TryReadUInt32(imageChannel.Intensifier, "Field", out cur); bool gotStatusCount = TryObjectToUInt32(TryGetProperty(intensifierStatus, "FieldCount"), out statusCount); bool gotStatusCur = TryObjectToUInt32(TryGetProperty(intensifierStatus, "Field"), out statusCur); lblIntFieldCount.Text = gotCount ? count.ToString() : "n/a"; lblIntFieldCurrent.Text = gotCur ? cur.ToString() : "n/a"; lblIntFieldStatusCount.Text = gotStatusCount ? statusCount.ToString() : "n/a"; lblIntFieldStatusCurrent.Text = gotStatusCur ? statusCur.ToString() : "n/a"; uint effectiveCount = gotCount ? count : (gotStatusCount ? statusCount : 0); uint effectiveField = gotCur ? cur : (gotStatusCur ? statusCur : 0); RebuildFieldDropDown(effectiveCount, effectiveField); } private void RefreshDetectorReadback(object detectorStatus, object geometryStatus, object imageStatus) { object name = FirstNonNull(TryInvoke(imageChannel.Detector, "Name"), TryGetProperty(detectorStatus, "Name")); object width = FirstNonNull(TryInvoke(imageChannel.Detector, "Width"), TryGetProperty(detectorStatus, "Width")); object height = FirstNonNull(TryInvoke(imageChannel.Detector, "Height"), TryGetProperty(detectorStatus, "Height")); object dim = FirstNonNull(TryInvoke(imageChannel.Detector, "Dimension2D"), TryGetProperty(detectorStatus, "Dimension2D")); object res = FirstNonNull(TryInvoke(imageChannel.Detector, "Resolution"), TryGetProperty(detectorStatus, "Resolution")); object liveAvail = TryGetProperty(imageStatus, "LiveAvailable"); object liveActive = TryGetProperty(imageStatus, "LiveActive"); object dsd = FirstNonNull(TryInvoke(imageChannel.Geometry, "DistanceSourceToDetector"), TryGetProperty(geometryStatus, "DistanceSourceToDetector")); lblIntDetectorName.Text = FormatOptionalValue(name); lblIntDetectorSize.Text = FormatOptionalValue(width) + " x " + FormatOptionalValue(height) + "; 2D=" + FormatOptionalValue(dim); lblIntDetectorResolution.Text = FormatOptionalValue(res); SetLabelValue(lblIntImageLiveAvailable, liveAvail, true); SetLabelValue(lblIntImageLiveActive, liveActive, true); lblIntGeometryDsd.Text = FormatOptionalValue(dsd); } private void RefreshDetectorParameterReadback(object detectorParametersStatus) { RefreshDetectorParamOne("Exposure", lblIntExpRead, nudIntExposure, detectorParametersStatus, "ExposureIndex"); RefreshDetectorParamOne("Gain", lblIntGainRead, nudIntGain, detectorParametersStatus, "GainIndex"); RefreshDetectorParamOne("DigitalGain", lblIntDigGainRead, nudIntDigGain, detectorParametersStatus, "DigitalGainIndex"); RefreshDetectorParamOne("Brightness", lblIntBrightRead, nudIntBrightness, detectorParametersStatus, "BrightnessIndex"); RefreshDetectorParamOne("Binning", lblIntBinningRead, nudIntBinning, detectorParametersStatus, "BinningIndex"); RefreshDetectorParamOne("Accumulation", lblIntAccumRead, nudIntAccum, detectorParametersStatus, "AccumulationIndex"); } private void RefreshDetectorParamOne(string methodName, Label label, NumericUpDown nud, object detectorParametersStatus, string statusPropertyName) { object val = FirstNonNull(TryInvoke(imageChannel.DetectorParameters, methodName), ExtractIndexedValue(TryGetProperty(detectorParametersStatus, statusPropertyName))); label.Text = FormatOptionalValue(val); SetNumericIfPossible(nud, val); } private object ExtractIndexedValue(object valueAndRange) { if (valueAndRange == null) return null; object value = TryGetProperty(valueAndRange, "Value"); if (value != null) return value; return valueAndRange; } private void RebuildFieldDropDown(uint count, uint current) { if (cmbIntField == null) return; if (count != cachedFieldCount) { cachedFieldCount = count; cmbIntField.BeginUpdate(); cmbIntField.Items.Clear(); if (count == 0) { cmbIntField.Items.Add(new FieldChoice(0, "0 (no fields reported)")); } else { for (uint i = 0; i < count; i++) { cmbIntField.Items.Add(new FieldChoice(i, i.ToString() + " (field " + i.ToString() + ")")); } } cmbIntField.EndUpdate(); } bool userEditing = cmbIntField.Focused || cmbIntField.DroppedDown; if ((chkIntMirrorReadback == null || chkIntMirrorReadback.Checked) && !userEditing) { SelectFieldChoice(current); } } private void SelectFieldChoice(uint value) { for (int i = 0; i < cmbIntField.Items.Count; i++) { FieldChoice fc = cmbIntField.Items[i] as FieldChoice; if (fc != null && fc.Value == value) { cmbIntField.SelectedIndex = i; return; } } } private bool TryGetSelectedField(out uint value) { value = 0; if (cmbIntField == null || cmbIntField.SelectedItem == null) return false; FieldChoice fc = cmbIntField.SelectedItem as FieldChoice; if (fc != null) { value = fc.Value; return true; } return UInt32.TryParse(cmbIntField.SelectedItem.ToString(), out value); } private void WriteIntensifierFieldAndVerify(uint target, string source) { object before = TryInvoke(imageChannel.Intensifier, "Field"); bool wrote = TryCall(imageChannel.Intensifier, "Field", target); if (!wrote && target <= Int32.MaxValue) wrote = TryCall(imageChannel.Intensifier, "Field", (int)target); Log("Intensifier.Field(" + target + ") from " + source + "; before=" + FormatOptionalValue(before) + "; send=" + (wrote ? "ok" : "not exposed/rejected")); if (!wrote) return; System.Threading.Thread.Sleep(150); object after150 = TryInvoke(imageChannel.Intensifier, "Field"); System.Threading.Thread.Sleep(500); object after650 = TryInvoke(imageChannel.Intensifier, "Field"); Log(" readback +150ms=" + FormatOptionalValue(after150) + "; +650ms=" + FormatOptionalValue(after650)); uint readback; if (TryObjectToUInt32(after650, out readback) && readback != target) { Log(" readback did not hold target " + target + ". Treat this as rejected/invalid field, controller not ready, or service-side policy override."); } RefreshIntensifier(); } private object GetImageStatusProperty(string propertyName) { object entireStatus = TryInvoke(imageChannel, "GetStatus"); object imageStatus = TryGetProperty(entireStatus, "ImageStatus"); return TryGetProperty(imageStatus, propertyName); } private bool TryReadUInt32(object target, string methodName, out uint value) { return TryObjectToUInt32(TryInvoke(target, methodName), out value); } private bool TryObjectToUInt32(object obj, out uint value) { value = 0; if (obj == null) return false; try { value = Convert.ToUInt32(obj); return true; } catch { return UInt32.TryParse(obj.ToString(), out value); } } private object TryGetProperty(object target, string propertyName) { if (target == null) return null; try { PropertyInfo pi = target.GetType().GetProperty(propertyName); if (pi == null) return null; return pi.GetValue(target, null); } catch { return null; } } private object FirstNonNull(params object[] values) { foreach (object value in values) { if (value != null) return value; } return null; } private void SetLabelValue(Label label, object value, bool colorBool) { label.Text = FormatOptionalValue(value); if (colorBool && value is bool) { label.ForeColor = ((bool)value) ? Color.Green : Color.Red; } else { label.ForeColor = Color.Navy; } } private void SetNumericIfPossible(NumericUpDown nud, object value) { if (nud == null || nud.Focused || value == null) return; try { decimal d = Convert.ToDecimal(value); if (d < nud.Minimum) d = nud.Minimum; if (d > nud.Maximum) d = nud.Maximum; nud.Value = d; } catch { } } private string ShortError(Exception ex) { if (ex == null) return ""; string msg = ex.Message == null ? "" : ex.Message; if (msg.Length > 70) msg = msg.Substring(0, 70) + "..."; return ex.GetType().Name + ": " + msg; } private void UpdateIntensifierDiagnosticText(object entireStatus, object controllerStatus, object detectorStatus, object detectorParametersStatus, object intensifierStatus, object geometryStatus, object imageStatus) { if (txtIntDiag == null) return; StringBuilder sb = new StringBuilder(); sb.AppendLine("Meaning of the main readbacks:"); sb.AppendLine(" Heartbeat alive = the ImageProcessing WCF endpoint answered."); sb.AppendLine(" Controller Ready/Communications = the IP service says its controller/driver side is ready."); sb.AppendLine(" Type/Version n/a = this wrapper may not expose those methods; use GetStatus below if available."); sb.AppendLine(" FieldCount is handled as zero-based: valid reported fields are 0..FieldCount-1."); sb.AppendLine(" Direct MiscIO writes bypass the ImageProcessing IPC service and call the same low-level field-output path used by Imaging.dll."); sb.AppendLine(); sb.AppendLine("If an IPC Field write immediately reads back as 0, the dropdown is no longer the cause. It means the ImageProcessing service/control did not accept or retain the requested field."); sb.AppendLine("Direct MiscIO is write-only through the exposed wrapper; verify it by observing the separate live viewer or external state."); sb.AppendLine(); sb.AppendLine("Status object snapshots:"); AppendStatusLine(sb, "ControllerStatus", controllerStatus, new string[] { "Ready", "Communications", "Type", "Version", "OperationMode", "Visible" }); AppendStatusLine(sb, "DetectorStatus", detectorStatus, new string[] { "Name", "Dimension2D", "Width", "Height", "Resolution" }); AppendStatusLine(sb, "DetectorParametersStatus", detectorParametersStatus, new string[] { "ExposureIndex", "GainIndex", "DigitalGainIndex", "BrightnessIndex", "BinningIndex", "AccumulationIndex" }); AppendStatusLine(sb, "IntensifierStatus", intensifierStatus, new string[] { "FieldCount", "Field" }); AppendStatusLine(sb, "GeometryStatus", geometryStatus, new string[] { "DistanceSourceToDetector", "DistanceSourceToMagnificationZero" }); AppendStatusLine(sb, "ImageStatus", imageStatus, new string[] { "LiveAvailable", "LiveActive" }); sb.AppendLine(); sb.AppendLine("Useful exposed methods on this wrapper:"); sb.AppendLine(" Controller: " + MethodSummary(imageChannel == null ? null : imageChannel.Controller)); sb.AppendLine(" Intensifier: " + MethodSummary(imageChannel == null ? null : imageChannel.Intensifier)); sb.AppendLine(" Image: " + MethodSummary(imageChannel == null ? null : imageChannel.Image)); sb.AppendLine(" DetectorParameters: " + MethodSummary(imageChannel == null ? null : imageChannel.DetectorParameters)); txtIntDiag.Text = sb.ToString(); } private void AppendStatusLine(StringBuilder sb, string name, object obj, string[] properties) { sb.Append(" "); sb.Append(name); sb.Append(": "); if (obj == null) { sb.AppendLine("n/a"); return; } for (int i = 0; i < properties.Length; i++) { if (i > 0) sb.Append("; "); object val = TryGetProperty(obj, properties[i]); sb.Append(properties[i]); sb.Append("="); sb.Append(FormatOptionalValue(ExtractIndexedValue(val))); } sb.AppendLine(); } private string MethodSummary(object target) { if (target == null) return "n/a"; try { List names = new List(); MethodInfo[] methods = target.GetType().GetMethods(); foreach (MethodInfo mi in methods) { if (mi.IsSpecialName) continue; if (mi.DeclaringType == typeof(object)) continue; names.Add(mi.Name + "(" + mi.GetParameters().Length.ToString() + ")"); } names.Sort(); return string.Join(", ", names.ToArray()); } catch (Exception ex) { return "err: " + ShortError(ex); } } private void LogImageProcessingInterfaces() { if (imageChannel == null) { Log("ImageProcessing channel not connected."); return; } Log("ImageProcessing wrapper: " + imageChannel.GetType().FullName); Log(" Channel methods: " + MethodSummary(imageChannel)); Log(" Controller methods: " + MethodSummary(imageChannel.Controller)); Log(" Detector methods: " + MethodSummary(imageChannel.Detector)); Log(" DetectorParameters methods: " + MethodSummary(imageChannel.DetectorParameters)); Log(" Intensifier methods: " + MethodSummary(imageChannel.Intensifier)); Log(" Geometry methods: " + MethodSummary(imageChannel.Geometry)); Log(" Image methods: " + MethodSummary(imageChannel.Image)); Log(" ImageProcessing methods: " + MethodSummary(imageChannel.ImageProcessing)); Log(" ToneCurve methods: " + MethodSummary(imageChannel.ToneCurve)); } protected override void OnFormClosing(FormClosingEventArgs e) { refreshTimer.Stop(); Disconnect(); base.OnFormClosing(e); } } public class NativeAxisSnapshot { public string Axis = ""; public string Position = ""; public string LinearEncoder = ""; public string Velocity = ""; public string Target = ""; public string MotorCurrent = ""; public string Idle = ""; public string Homed = ""; public string Locked = ""; public string Error = ""; public string MaxSpeed = ""; public string FollowError = ""; public string Returns = ""; } public class NativeMotionController { public string LoadedDll = ""; public string Kind = ""; public string LastError = ""; private IntPtr hModule = IntPtr.Zero; private string loadedPath = ""; private InitShort initialiseShort; private VoidNoArgs exitController; private GetShortRef getNumberAxes; private GetShortRef getNumberActiveAxes; private CommonGetFloat getPos; private CommonGetFloat getVel; private CommonGetFloat getMotorCurrent; private CommonGetFloat getLinearEncoderPos; private CommonGetFloat getMaximumSpeed; private CommonGetFloat getMaximumAcceleration; private CommonGetFloat getMaximumDeceleration; private CommonGetBool getIdle; private CommonGetBool getJogIdle; private CommonGetUShort getNodeInputs; private CommonGetByte getNodeOutputs; private CommonSetNodeOutput setNodeOutputs; private CommonGetByteAux getAuxInputs; private FollowError getXFollowError; private FollowError getYFollowError; private FollowError getZFollowError; private CommonSetComms commonSetComms; private CommonSetCommsWrite commonSetCommsWrite; private CommonSetAxisEnabledDelegate commonSetAxisEnabled; private CommonGetCommsF commonGetCommsF; private VoidNoArgs venloInitialize; private VoidNoArgs venloTerminate; private IntNoArgs venloIsInitialized; private IntNoArgs venloGetAxisCount; private IntNoArgs venloGetInterlock; private IntNoArgs venloGetGlobalSpeed; private SetInt venloSetGlobalSpeed; private GetFloatInt venloGetAxisPosition; private GetFloatInt venloGetAxisVelocity; private GetFloatInt venloGetAxisTarget; private GetFloatInt venloGetAxisMaxSpeed; private GetFloatInt venloGetAxisMaxAcceleration; private GetFloatInt venloGetAxisMaxDeceleration; private GetIntInt venloGetAxisHomed; private GetIntInt venloGetAxisStationary; private GetIntInt venloGetAxisError; private GetIntInt venloGetAxisLocked; private SetIntInt venloSetAxisLocked; private SetIntFloat venloSetAxisTarget; private SetIntFloat venloAxesGo; private SetIntFloat venloAxesGoRelative; private SetInt venloAxesHome; private SetIntFloat venloAxisVelocityGo; private VoidNoArgs venloStopAll; public bool IsLoaded { get { return hModule != IntPtr.Zero; } } public bool Load(string path) { Release(); LastError = ""; loadedPath = path; LoadedDll = System.IO.Path.GetFileName(path); Kind = LoadedDll.IndexOf("Venlo", StringComparison.OrdinalIgnoreCase) >= 0 ? "XTMVenlo" : "CommonCopleyRevolution"; hModule = NativeKernel.LoadLibrary(path); if (hModule == IntPtr.Zero) { LastError = "LoadLibrary failed; Win32=" + Marshal.GetLastWin32Error().ToString(); return false; } if (Kind == "XTMVenlo") BindVenlo(); else BindCommon(); return true; } public void Release() { try { if (Kind == "XTMVenlo" && venloTerminate != null) venloTerminate(); if (Kind != "XTMVenlo" && exitController != null) exitController(); } catch { } if (hModule != IntPtr.Zero) { NativeKernel.FreeLibrary(hModule); hModule = IntPtr.Zero; } loadedPath = ""; LoadedDll = ""; Kind = ""; } public string Initialise(short initArg) { if (Kind == "XTMVenlo") { if (venloInitialize == null) return "XTMVenlo Initialize unavailable"; venloInitialize(); string state = venloIsInitialized != null ? ("; IsInitialized=" + venloIsInitialized().ToString()) : ""; return "XTMVenlo Initialize called" + state; } if (initialiseShort == null) return "InitialiseCController unavailable"; initialiseShort(initArg); return LoadedDll + " InitialiseCController(" + initArg.ToString() + ") called"; } public string ExportSummary() { if (Kind == "XTMVenlo") { return "Init=" + Yes(venloInitialize) + ", Count=" + Yes(venloGetAxisCount) + ", Pos=" + Yes(venloGetAxisPosition) + ", Vel=" + Yes(venloGetAxisVelocity) + ", Target=" + Yes(venloGetAxisTarget) + ", AxesGo=" + Yes(venloAxesGo) + ", Rel=" + Yes(venloAxesGoRelative) + ", VelGo=" + Yes(venloAxisVelocityGo) + ", StopAll=" + Yes(venloStopAll); } return "Init=" + Yes(initialiseShort) + ", Count=" + Yes(getNumberAxes) + ", Pos=" + Yes(getPos) + ", LinearEnc=" + Yes(getLinearEncoderPos) + ", Vel=" + Yes(getVel) + ", MotorCurrent=" + Yes(getMotorCurrent) + ", AxisEnable=" + Yes(commonSetAxisEnabled) + ", Comms=" + Yes(commonSetComms) + "/" + Yes(commonSetCommsWrite) + "/" + Yes(commonGetCommsF) + ", NodeIO=" + Yes(getNodeInputs) + "/" + Yes(getNodeOutputs) + ", NodeWrite=" + Yes(setNodeOutputs); } private string Yes(object d) { return d == null ? "no" : "yes"; } public NativeAxisSnapshot[] ReadAxes(short controller, int axisBase, int maxRows) { if (Kind == "XTMVenlo") return ReadVenloAxes(axisBase, maxRows); return ReadCommonAxes(controller, axisBase, maxRows); } private NativeAxisSnapshot[] ReadVenloAxes(int axisBase, int maxRows) { int count = maxRows; if (venloGetAxisCount != null) { try { count = venloGetAxisCount(); } catch { count = maxRows; } } if (count < 1 || count > maxRows) count = maxRows; NativeAxisSnapshot[] rows = new NativeAxisSnapshot[count]; for (int i = 0; i < count; i++) { int axis = i + axisBase; NativeAxisSnapshot a = new NativeAxisSnapshot(); a.Axis = axis.ToString(); a.Position = ReadFloatInt(venloGetAxisPosition, axis); a.LinearEncoder = "n/a"; a.Velocity = ReadFloatInt(venloGetAxisVelocity, axis); a.Target = ReadFloatInt(venloGetAxisTarget, axis); a.MotorCurrent = "n/a"; a.Idle = ReadIntIntBool(venloGetAxisStationary, axis); a.Homed = ReadIntIntBool(venloGetAxisHomed, axis); a.Locked = ReadIntIntBool(venloGetAxisLocked, axis); a.Error = ReadIntInt(venloGetAxisError, axis); a.MaxSpeed = ReadFloatInt(venloGetAxisMaxSpeed, axis); a.FollowError = "n/a"; a.Returns = "interlock=" + (venloGetInterlock != null ? SafeInt(venloGetInterlock) : "n/a") + ", globalSpeed=" + (venloGetGlobalSpeed != null ? SafeInt(venloGetGlobalSpeed) : "n/a"); rows[i] = a; } return rows; } private NativeAxisSnapshot[] ReadCommonAxes(short controller, int axisBase, int maxRows) { int count = maxRows; short scount = 0; if (getNumberAxes != null) { try { short rc = getNumberAxes(ref scount); if (scount > 0 && scount <= maxRows) count = scount; } catch { } } NativeAxisSnapshot[] rows = new NativeAxisSnapshot[count]; for (int i = 0; i < count; i++) { short axis = (short)(i + axisBase); NativeAxisSnapshot a = new NativeAxisSnapshot(); a.Axis = axis.ToString(); a.Position = ReadCommonFloat(getPos, controller, axis); a.LinearEncoder = ReadCommonFloat(getLinearEncoderPos, controller, axis); a.Velocity = ReadCommonFloat(getVel, controller, axis); a.Target = ReadCommonRegister(controller, (short)(30 + axis)); a.MotorCurrent = ReadCommonFloat(getMotorCurrent, controller, axis); a.Idle = ReadCommonBool(getIdle, controller, axis); a.Homed = ReadCommonMaskBool(controller, 14, axis); a.Locked = ReadCommonMaskBool(controller, 21, axis); a.Error = "err=" + ReadCommonRegister(controller, 9) + ", axis=" + ReadCommonRegister(controller, 10); a.MaxSpeed = ReadCommonFloat(getMaximumSpeed, controller, axis); a.FollowError = ReadFollowError(controller, axis); a.Returns = "activeAxes=" + ReadShortRef(getNumberActiveAxes) + ", status11=" + ReadCommonRegister(controller, 11) + ", home14=" + ReadCommonRegister(controller, 14) + ", lock21=" + ReadCommonRegister(controller, 21); rows[i] = a; } return rows; } public string MoveAbsolute(int axis, float target, float speed) { if (Kind != "XTMVenlo") return CommonMoveAbsolute(axis, target, speed); if (venloSetAxisTarget == null || venloAxesGo == null) return "XTMVenlo absolute move unavailable: SetAxisTarget or AxesGo missing"; venloSetAxisTarget(axis, target); venloAxesGo(axis, speed); return "XTMVenlo SetAxisTarget(axis=" + axis.ToString() + ", target=" + target.ToString("F3") + ") then AxesGo(axis=" + axis.ToString() + ", speed=" + speed.ToString("F3") + ")"; } public string MoveRelative(int axis, float delta) { if (Kind != "XTMVenlo") return CommonMoveRelative(axis, delta); if (venloAxesGoRelative == null) return "XTMVenlo AxesGoRelative missing"; venloAxesGoRelative(axis, delta); return "XTMVenlo AxesGoRelative(axis=" + axis.ToString() + ", delta=" + delta.ToString("F3") + ")"; } public string VelocityGo(int axis, float velocity) { if (Kind != "XTMVenlo") return CommonVelocityGo(axis, velocity); if (venloAxisVelocityGo == null) return "XTMVenlo AxisVelocityGo missing"; venloAxisVelocityGo(axis, velocity); return "XTMVenlo AxisVelocityGo(axis=" + axis.ToString() + ", velocity=" + velocity.ToString("F3") + ")"; } public string Home(int axis) { if (Kind != "XTMVenlo") return CommonHome(axis); if (venloAxesHome == null) return "XTMVenlo AxesHome missing"; venloAxesHome(axis); return "XTMVenlo AxesHome(axis=" + axis.ToString() + ")"; } public string SetLocked(int axis, int locked) { if (Kind != "XTMVenlo") return CommonSetLocked(axis, locked); if (venloSetAxisLocked == null) return "XTMVenlo SetAxisLocked missing"; venloSetAxisLocked(axis, locked); return "XTMVenlo SetAxisLocked(axis=" + axis.ToString() + ", locked=" + locked.ToString() + ")"; } public string SetAxisEnabled(int axis, bool enabled) { if (Kind == "XTMVenlo") return "XTMVenlo axis-enable shortcut is not implemented; use lock/unlock/status APIs for Venlo."; return CommonSetAxisEnabled(axis, enabled); } public string EnableThenVelocity(int axis, float velocity) { if (Kind == "XTMVenlo") { string unlock = SetLocked(axis, 0); string vel = VelocityGo(axis, velocity); return "XTMVenlo enable+velocity: " + unlock + "; " + vel; } string enable = CommonSetAxisEnabled(axis, true); string unlock2 = CommonSetLocked(axis, 0); string vel2 = CommonVelocityGo(axis, velocity); return "CANOpen/Revolution Enable+Velocity: " + enable + "; " + unlock2 + "; " + vel2; } public string StopAll() { if (Kind == "XTMVenlo" && venloStopAll != null) { venloStopAll(); return "XTMVenlo StopAll() called"; } return CommonStopAll(); } private string CommonSetAxisEnabled(int axis, bool enabled) { if (commonSetAxisEnabled == null) return "CANOpen/Revolution _setAxisEnabled unavailable"; short rc = commonSetAxisEnabled((short)axis, enabled); return "CANOpen/Revolution _setAxisEnabled(axis=" + axis.ToString() + ", enabled=" + (enabled ? "true" : "false") + ") rc=" + rc.ToString(); } private string CommonMoveAbsolute(int axis, float target, float speed) { if (commonSetCommsWrite == null || commonSetComms == null) return "CANOpen/Revolution absolute move unavailable: setCommsWrite/setComms missing"; float writtenTarget = target; if (axis == 2) writtenTarget = target - 1.25f; // matches Manipulator.dll CANOpenRevolution.SetAxisTarget short rcTarget = commonSetCommsWrite((short)(30 + axis), writtenTarget); ushort rcSpeed = commonSetComms(0, (short)(210 + axis), speed); string cmd = SendCommonCommand(1 + axis, 1000); return "CANOpen/Revolution absolute/no-tracking: setCommsWrite(reg=" + (30 + axis).ToString() + ", target=" + writtenTarget.ToString("F4") + ") rc=" + rcTarget.ToString() + "; setComms(reg=" + (210 + axis).ToString() + ", speed=" + speed.ToString("F4") + ") rc=" + rcSpeed.ToString() + "; " + cmd; } private string CommonMoveRelative(int axis, float delta) { if (commonSetComms == null) return "CANOpen/Revolution relative move unavailable: setComms missing"; ushort rc = commonSetComms(0, (short)(210 + axis), delta); string cmd = SendCommonCommand(64 + axis, 1000); return "CANOpen/Revolution relative: setComms(reg=" + (210 + axis).ToString() + ", delta=" + delta.ToString("F4") + ") rc=" + rc.ToString() + "; " + cmd; } private string CommonVelocityGo(int axis, float velocity) { if (commonSetCommsWrite == null) return "CANOpen/Revolution velocity unavailable: setCommsWrite missing"; short rc = commonSetCommsWrite((short)(94 + axis), velocity); return "CANOpen/Revolution velocity: setCommsWrite(reg=" + (94 + axis).ToString() + ", velocity=" + velocity.ToString("F4") + ") rc=" + rc.ToString() + ". Use STOP ALL to write zero velocity."; } private string CommonHome(int axis) { if (commonSetComms == null || commonGetCommsF == null) return "CANOpen/Revolution home unavailable: setComms/getCommsF missing"; return "CANOpen/Revolution home command: " + SendCommonCommand(25 + axis, 1000); } private string CommonStopAll() { string result = ""; if (commonSetCommsWrite != null) { for (int i = 0; i < 8; i++) { try { short rc = commonSetCommsWrite((short)(94 + i), 0.0f); result += "v" + i.ToString() + "rc=" + rc.ToString() + " "; } catch (Exception ex) { result += "v" + i.ToString() + "err=" + ex.GetType().Name + " "; } } } if (commonSetComms != null && commonGetCommsF != null) result += SendCommonCommand(102, 1000); else result += "SendCommand unavailable"; return "CANOpen/Revolution STOP: " + result; } private string CommonSetLocked(int axis, int locked) { if (commonSetComms == null || commonGetCommsF == null) return "CANOpen/Revolution lock unavailable: setComms/getCommsF missing"; float maskF = 0; ushort rcRead = commonGetCommsF(0, 21, ref maskF); int mask = (int)maskF; if (locked != 0) mask |= (1 << (axis & 31)); else mask &= ~(1 << (axis & 31)); ushort rcWrite = commonSetComms(0, 21, (float)mask); return "CANOpen/Revolution lock mask reg21: read rc=" + rcRead.ToString() + " old=" + ((int)maskF).ToString() + ", write new=" + mask.ToString() + " rc=" + rcWrite.ToString(); } private string SendCommonCommand(int command, int timeoutMs) { if (commonSetComms == null || commonGetCommsF == null) return "SendCommand unavailable"; ushort rc0 = commonSetComms(0, 7, 0.0f); ushort rc1 = commonSetComms(0, 1, (float)command); float echo = -1.0f; DateTime start = DateTime.Now; while ((DateTime.Now - start).TotalMilliseconds < timeoutMs) { System.Threading.Thread.Sleep(10); ushort rcEcho = commonGetCommsF(0, 7, ref echo); if ((int)echo == command) { ushort rcClear = commonSetComms(0, 7, 0.0f); return "SendCommand(" + command.ToString() + ") rc0=" + rc0.ToString() + " rc1=" + rc1.ToString() + " echoRc=" + rcEcho.ToString() + " clearedRc=" + rcClear.ToString(); } } return "SendCommand(" + command.ToString() + ") timeout; rc0=" + rc0.ToString() + " rc1=" + rc1.ToString() + " lastEcho=" + echo.ToString("F3"); } public string ReadNodeIO(short controller, short node) { ushort inputs = 0; byte outputs = 0; string rin = "n/a"; string rout = "n/a"; if (getNodeInputs != null) { try { short rc = getNodeInputs(controller, node, ref inputs); rin = "rc=" + rc.ToString() + " inputs=0x" + inputs.ToString("X4") + " (" + inputs.ToString() + ")"; } catch (Exception ex) { rin = ex.Message; } } if (getNodeOutputs != null) { try { short rc = getNodeOutputs(controller, node, ref outputs); rout = "rc=" + rc.ToString() + " outputs=0x" + outputs.ToString("X2") + " (" + outputs.ToString() + ")"; } catch (Exception ex) { rout = ex.Message; } } return "node " + node.ToString() + ": " + rin + "; " + rout; } public string WriteNodeOutput(short controller, short node, byte value) { if (setNodeOutputs == null) return "setNodeOutputs unavailable in " + LoadedDll; short rc = setNodeOutputs(controller, node, value); return "setNodeOutputs(controller=" + controller.ToString() + ", node=" + node.ToString() + ", value=0x" + value.ToString("X2") + ") rc=" + rc.ToString(); } public string ReadAuxInputs(short controller) { if (getAuxInputs == null) return "getAuxInputs unavailable in " + LoadedDll; byte v = 0; short rc = getAuxInputs(controller, ref v); return "getAuxInputs(controller=" + controller.ToString() + ") rc=" + rc.ToString() + " value=0x" + v.ToString("X2") + " (" + v.ToString() + ")"; } private void BindCommon() { initialiseShort = Bind("InitialiseCController", 4); exitController = Bind("ExitCController", 0); getNumberAxes = Bind("getNumberAxes", 4); getNumberActiveAxes = Bind("getNumberActiveAxes", 4); getPos = Bind("getPos", 12); getVel = Bind("getVel", 12); getMotorCurrent = Bind("getMotorCurrent", 12); getLinearEncoderPos = Bind("getLinearEncoderPos", 12); getMaximumSpeed = Bind("getMaximumSpeed", 12); getMaximumAcceleration = Bind("getMaximumAcceleration", 12); getMaximumDeceleration = Bind("getMaximumDeceleration", 12); getIdle = Bind("getIdle", 12); getJogIdle = Bind("getJogIdle", 12); getNodeInputs = Bind("getNodeInputs", 12); getNodeOutputs = Bind("getNodeOutputs", 12); setNodeOutputs = Bind("setNodeOutputs", 12); getAuxInputs = Bind("getAuxInputs", 8); getXFollowError = Bind("getXFollowError", 8); getYFollowError = Bind("getYFollowError", 8); getZFollowError = Bind("getZFollowError", 8); commonSetAxisEnabled = Bind("setAxisEnabled", 8); commonSetComms = Bind("setComms", 12); commonSetCommsWrite = Bind("setCommsWrite", 8); commonGetCommsF = Bind("getCommsF", 12); } private void BindVenlo() { venloInitialize = Bind("Initialize", 0); venloTerminate = Bind("Terminate", 0); venloIsInitialized = Bind("IsInitialized", 0); venloGetAxisCount = Bind("GetAxisCount", 0); venloGetInterlock = Bind("GetInterlock", 0); venloGetGlobalSpeed = Bind("GetGlobalSpeed", 0); venloSetGlobalSpeed = Bind("SetGlobalSpeed", 4); venloGetAxisPosition = Bind("GetAxisPosition", 4); venloGetAxisVelocity = Bind("GetAxisVelocity", 4); venloGetAxisTarget = Bind("GetAxisTarget", 4); venloGetAxisMaxSpeed = Bind("GetAxisMaximumSpeed", 4); venloGetAxisMaxAcceleration = Bind("GetAxisMaximumAcceleration", 4); venloGetAxisMaxDeceleration = Bind("GetAxisMaximumDeceleration", 4); venloGetAxisHomed = Bind("GetAxisHomed", 4); venloGetAxisStationary = Bind("GetAxisStationary", 4); venloGetAxisError = Bind("GetAxisError", 4); venloGetAxisLocked = Bind("GetAxisLocked", 4); venloSetAxisLocked = Bind("SetAxisLocked", 8); venloSetAxisTarget = Bind("SetAxisTarget", 8); venloAxesGo = Bind("AxesGo", 8); venloAxesGoRelative = Bind("AxesGoRelative", 8); venloAxesHome = Bind("AxesHome", 4); venloAxisVelocityGo = Bind("AxisVelocityGo", 8); venloStopAll = Bind("StopAll", 0); } private T Bind(string name, int bytes) where T : class { IntPtr p = FindExport(name, bytes); if (p == IntPtr.Zero) return null; return Marshal.GetDelegateForFunctionPointer(p, typeof(T)) as T; } private IntPtr FindExport(string name, int bytes) { IntPtr p = NativeKernel.GetProcAddress(hModule, name); if (p != IntPtr.Zero) return p; p = NativeKernel.GetProcAddress(hModule, "_" + name + "@" + bytes.ToString()); if (p != IntPtr.Zero) return p; p = NativeKernel.GetProcAddress(hModule, name + "@" + bytes.ToString()); return p; } private string ReadCommonRegister(short controller, int address) { if (commonGetCommsF == null) return "n/a"; try { float v = 0; ushort rc = commonGetCommsF(controller, (short)address, ref v); return v.ToString("F4") + " rc=" + rc.ToString(); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadCommonMaskBool(short controller, int address, short axis) { if (commonGetCommsF == null) return "n/a"; try { float v = 0; ushort rc = commonGetCommsF(controller, (short)address, ref v); int mask = (int)v; bool bit = (mask & (1 << (axis & 31))) != 0; return (bit ? "YES" : "NO") + " mask=" + mask.ToString() + " rc=" + rc.ToString(); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadCommonFloat(CommonGetFloat f, short controller, short axis) { if (f == null) return "n/a"; try { float v = 0; short rc = f(controller, axis, ref v); return v.ToString("F4") + " rc=" + rc.ToString(); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadCommonBool(CommonGetBool f, short controller, short axis) { if (f == null) return "n/a"; try { bool v = false; short rc = f(controller, axis, ref v); return (v ? "YES" : "NO") + " rc=" + rc.ToString(); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadFollowError(short controller, short axis) { FollowError f = null; if (axis == 0) f = getXFollowError; if (axis == 1) f = getYFollowError; if (axis == 2) f = getZFollowError; if (f == null) return "n/a"; try { float v = 0; short rc = f(controller, ref v); return v.ToString("F4") + " rc=" + rc.ToString(); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadShortRef(GetShortRef f) { if (f == null) return "n/a"; try { short v = 0; short rc = f(ref v); return v.ToString() + " rc=" + rc.ToString(); } catch { return "err"; } } private string ReadFloatInt(GetFloatInt f, int axis) { if (f == null) return "n/a"; try { return f(axis).ToString("F4"); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadIntInt(GetIntInt f, int axis) { if (f == null) return "n/a"; try { return f(axis).ToString(); } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string ReadIntIntBool(GetIntInt f, int axis) { if (f == null) return "n/a"; try { int v = f(axis); return v != 0 ? "YES" : "NO"; } catch (Exception ex) { return "err " + ex.GetType().Name; } } private string SafeInt(IntNoArgs f) { try { return f().ToString(); } catch { return "err"; } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void InitShort(short arg); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void VoidNoArgs(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int IntNoArgs(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void SetInt(int value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void SetIntInt(int axis, int value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void SetIntFloat(int axis, float value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate float GetFloatInt(int axis); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetIntInt(int axis); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short GetShortRef(ref short value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonSetAxisEnabledDelegate(short axis, bool enabled); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate ushort CommonSetComms(short controller, short address, float value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonSetCommsWrite(short address, float value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate ushort CommonGetCommsF(short controller, short address, ref float value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonGetFloat(short controller, short axis, ref float value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonGetBool(short controller, short axis, ref bool value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonGetUShort(short controller, short node, ref ushort value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonGetByte(short controller, short node, ref byte value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonSetNodeOutput(short controller, short node, byte value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short CommonGetByteAux(short controller, ref byte value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate short FollowError(short controller, ref float value); } internal static class NativeKernel { [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool FreeLibrary(IntPtr hModule); } // ==================== Circular X/Y Shift Pad ==================== public class ShiftPad : Control { private bool dragging = false; private int xValue = 0; private int yValue = 0; public int Minimum = -99; public int Maximum = 99; public event EventHandler ValueChanged; public bool IsDragging { get { return dragging; } } public int XValue { get { return xValue; } } public int YValue { get { return yValue; } } public ShiftPad() { this.DoubleBuffered = true; this.BackColor = Color.White; this.MinimumSize = new Size(180, 180); this.Cursor = Cursors.Cross; } public void SetValues(int x, int y, bool raiseEvent) { xValue = Clamp(x); yValue = Clamp(y); Invalidate(); if (raiseEvent && ValueChanged != null) ValueChanged(this, EventArgs.Empty); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button != MouseButtons.Left) return; if (!IsInsidePad(e.Location)) return; dragging = true; Capture = true; UpdateFromPoint(e.Location); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (dragging && (e.Button & MouseButtons.Left) == MouseButtons.Left) { UpdateFromPoint(e.Location); } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); dragging = false; Capture = false; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int pad = 12; int side = Math.Min(ClientSize.Width, ClientSize.Height) - pad * 2; if (side < 20) return; Rectangle circle = new Rectangle((ClientSize.Width - side) / 2, (ClientSize.Height - side) / 2, side, side); Point center = new Point(circle.Left + circle.Width / 2, circle.Top + circle.Height / 2); int radius = circle.Width / 2; using (Pen gridPen = new Pen(Color.FromArgb(200, 200, 200))) using (Pen axisPen = new Pen(Color.FromArgb(120, 120, 120))) using (Brush fill = new SolidBrush(Color.FromArgb(248, 250, 252))) { g.FillEllipse(fill, circle); g.DrawEllipse(axisPen, circle); g.DrawLine(gridPen, center.X, circle.Top, center.X, circle.Bottom); g.DrawLine(gridPen, circle.Left, center.Y, circle.Right, center.Y); g.DrawEllipse(gridPen, center.X - radius / 2, center.Y - radius / 2, radius, radius); } Point knob = ValueToPoint(circle); using (Brush knobBrush = new SolidBrush(Color.FromArgb(33, 150, 243))) using (Pen knobPen = new Pen(Color.FromArgb(10, 80, 150), 2)) { Rectangle k = new Rectangle(knob.X - 8, knob.Y - 8, 16, 16); g.FillEllipse(knobBrush, k); g.DrawEllipse(knobPen, k); } string text = "X " + xValue + " / Y " + yValue; SizeF sz = g.MeasureString(text, Font); using (Brush textBrush = new SolidBrush(Color.DimGray)) { g.DrawString(text, Font, textBrush, center.X - sz.Width / 2, circle.Bottom + 4); } } private void UpdateFromPoint(Point p) { Rectangle circle = GetCircle(); Point center = new Point(circle.Left + circle.Width / 2, circle.Top + circle.Height / 2); double radius = circle.Width / 2.0; if (radius <= 0) return; double dx = p.X - center.X; double dy = p.Y - center.Y; double dist = Math.Sqrt(dx * dx + dy * dy); if (dist > radius) { return; } int range = Math.Max(Math.Abs(Minimum), Math.Abs(Maximum)); int newX = Clamp((int)Math.Round(dx / radius * range)); int newY = Clamp((int)Math.Round(-dy / radius * range)); if (newX == xValue && newY == yValue) return; xValue = newX; yValue = newY; Invalidate(); if (ValueChanged != null) ValueChanged(this, EventArgs.Empty); } private Rectangle GetCircle() { int pad = 12; int side = Math.Min(ClientSize.Width, ClientSize.Height) - pad * 2; if (side < 0) side = 0; return new Rectangle((ClientSize.Width - side) / 2, (ClientSize.Height - side) / 2, side, side); } private bool IsInsidePad(Point p) { Rectangle circle = GetCircle(); Point center = new Point(circle.Left + circle.Width / 2, circle.Top + circle.Height / 2); double radius = circle.Width / 2.0; if (radius <= 0) return false; double dx = p.X - center.X; double dy = p.Y - center.Y; return Math.Sqrt(dx * dx + dy * dy) <= radius; } private Point ValueToPoint(Rectangle circle) { Point center = new Point(circle.Left + circle.Width / 2, circle.Top + circle.Height / 2); double radius = circle.Width / 2.0; int range = Math.Max(Math.Abs(Minimum), Math.Abs(Maximum)); if (range <= 0) range = 1; int x = center.X + (int)Math.Round((double)xValue / range * radius); int y = center.Y - (int)Math.Round((double)yValue / range * radius); return new Point(x, y); } private int Clamp(int value) { if (value < Minimum) return Minimum; if (value > Maximum) return Maximum; return value; } } // ==================== Entry Point ==================== static class Program { [STAThread] static void Main() { System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); System.Windows.Forms.Application.Run(new DiagnosticForm()); } } }