using OpenCvSharp; using OpenCvSharp.WpfExtensions; using PLCSharp.Core.Common; using PLCSharp.Core.Prism; using Prism.Commands; using Prism.Dialogs; using Prism.Events; using Prism.Ioc; using System.Threading; using System.Windows.Media.Imaging; namespace PLCSharp.VVMs.Vision.Camera { /// /// 相机配置视图模型 /// public class CameraConfigViewModel : DialogAwareBase { /// /// 相机配置视图模型 /// public CameraConfigViewModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService) { } private CameraBase _Camera; /// /// 配置项 /// public CameraBase Camera { get { return _Camera; } set { SetProperty(ref _Camera, value); } } private Mat _ShowMat; /// /// 显示矩阵 /// public Mat ShowMat { get { return _ShowMat; } set { SetProperty(ref _ShowMat, value); if (value == null) return; _ = System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => { if (_ImgSrc != null && _ShowMat.Width == _ImgSrc.PixelWidth && _ShowMat.Height == _ImgSrc.PixelHeight) { WriteableBitmapConverter.ToWriteableBitmap(_ShowMat, _ImgSrc); } else { ImgSrc = _ShowMat.ToWriteableBitmap(); } })); } } private WriteableBitmap _ImgSrc; /// /// 显示的图像源 /// public WriteableBitmap ImgSrc { get { return _ImgSrc; } set { SetProperty(ref _ImgSrc, value); } } /// /// 打开对话框后要执行的 /// /// parameters public override void OnDialogOpened(IDialogParameters parameters) { var camera = parameters.GetValue("Camera"); if (camera == null) { } else { Title = camera.Name; Camera = camera; } } /// /// 关闭对话框后要执行的 /// public override void OnDialogClosed() { Camera.StopContinuous(); } private DelegateCommand _StopContinuous; /// /// 停止Continuous /// public DelegateCommand StopContinuous => _StopContinuous ??= new DelegateCommand(ExecuteStopContinuous); void ExecuteStopContinuous() { Camera.StopContinuous(); continuous = false; } bool continuous; private AsyncDelegateCommand _CameraCommand; /// /// 相机Command /// public AsyncDelegateCommand CameraCommand => _CameraCommand ??= new AsyncDelegateCommand(ExecuteCameraCommandAsync); private async Task ExecuteCameraCommandAsync(object param) { if (Camera is null) return; var cmd = param as string; if (cameraWorking) return; cameraWorking = true; await Task.Run(() => { FlowModel flow = new(); switch (cmd) { case "Trig": { while (flow.Done == false) { Thread.Sleep(1); switch (flow.Step) { case 0: Camera.Trig(); flow.Step++; break; case 1: if (Camera.WaitOne(3000)) { ShowMat = Camera.Mat; flow.Step++; } break; case 2: Camera.SetTriggerSource(); flow.Done = true; break; } if (flow.CheckFlowTime(10)) { break; } } } break; case "Continuous": { while (flow.Done == false) { Thread.Sleep(1); switch (flow.Step) { case 0: Camera.Continuous(); continuous = true; flow.Step++; break; case 1: if (Camera.WaitOne(3000)) { ShowMat = Camera.Mat; } if (continuous == false) { flow.Step++; } break; case 2: Camera.SetTriggerSource(); flow.Done = true; break; } } } break; } }); cameraWorking = false; } bool cameraWorking; } }