| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- using System;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Media;
- namespace AutoFocusTool
- {
- // 电机控制:Z对焦轴 / 水平轴 / 位置刷新
- public partial class MainWindow
- {
- /// <summary>串口操作统一包装:置忙、后台执行、完成后刷新位置。</summary>
- private void MotorAction(string name, Func<bool> action)
- {
- if (_motor == null) return;
- if (_busy) { Log("串口忙,请稍候。"); return; }
- int motorDelay = ParseInt2(TxtMotorDelay.Text, 1500); // UI线程先读
- Task.Run(() =>
- {
- _busy = true;
- try
- {
- if (_motor != null) _motor.MotorDelayMs = motorDelay;
- bool ok = action();
- Log($"{name} {(ok ? "完成" : "失败")}");
- }
- catch (Exception ex) { Log($"{name} 异常: {ex.Message}"); }
- finally { _busy = false; }
- RefreshPositions();
- });
- }
- // ── Z 对焦轴 ──
- private void BtnZUp_Click(object sender, RoutedEventArgs e)
- {
- int step = ParseInt2(TxtZStep.Text, 128);
- MotorAction($"Z正转 {step}步", () => _motor.VerticalForward(step));
- }
- private void BtnZDown_Click(object sender, RoutedEventArgs e)
- {
- int step = ParseInt2(TxtZStep.Text, 128);
- MotorAction($"Z反转 {step}步", () => _motor.VerticalBackward(step));
- }
- private void BtnZReset_Click(object sender, RoutedEventArgs e)
- => MotorAction("Z复位", () => _motor.VerticalReset());
- private void BtnZMoveTo_Click(object sender, RoutedEventArgs e)
- {
- int abs = ParseInt2(TxtZAbs.Text, 0);
- MotorAction($"Z绝对移动→{abs}", () => _motor.VerticalMoveTo(abs));
- }
- // ── 水平轴 ──
- private void BtnHFwd_Click(object sender, RoutedEventArgs e)
- {
- int step = ParseInt2(TxtHStep.Text, 100);
- MotorAction($"水平正转 {step}步", () => _motor.HorizontalForward(step));
- }
- private void BtnHBwd_Click(object sender, RoutedEventArgs e)
- {
- int step = ParseInt2(TxtHStep.Text, 100);
- MotorAction($"水平反转 {step}步", () => _motor.HorizontalBackward(step));
- }
- private void BtnHReset_Click(object sender, RoutedEventArgs e)
- => MotorAction("水平复位", () => _motor.HorizontalReset());
- // ── 读位置并显示 ──
- private void RefreshPositions()
- {
- if (_motor == null) return;
- Task.Run(() =>
- {
- if (_busy) return;
- _busy = true;
- int z = -1, hpos = -1;
- try
- {
- z = _motor.ReadVerticalPosition();
- hpos = _motor.ReadHorizontalPosition();
- }
- catch (Exception ex) { Log($"读位置异常: {ex.Message}"); }
- finally { _busy = false; }
- _lastZ = z; _lastH = hpos;
- Dispatcher.Invoke(() => { TxtZ.Text = $"Z: {z} 水平: {hpos}"; UpdateParamDisplay(); });
- });
- }
- private static int ParseInt2(string s, int def)
- => int.TryParse(s?.Trim(), out int v) ? v : def;
- }
- }
|