1.概述
做非标视觉项目多了,就想着有没有通用的视觉工具,某视觉软件就做的很好,熟悉使用之后,看了其实现过程,不得不佩服。然而其代码过于庞杂,有些理解不便,尤其是逻辑和界面严重耦合,不能兼容最新设计界面,因此在其基础上,做了一些改进,主要在数据绑定部分,后面详细说明,现在大致介绍接口。
public interface ITool:INotifyPropertyChanged
{
string Name { get; set; }
void Run();
IPropertyBinderImplementation Bindings { get; }
IToolRecord CreateCurrentRecord();
IToolRecord CreateLastRunRecord();
event EventHandler Ran;
event EventHandler Running;
IToolRunStatus RunStatus { get; }
}
(1)Name 名字
(2)Run 运行,使用命令模式,解耦参数
(3)IPropertyBinderImplementation Bindings { get; }参数绑定接口,用于多个工具之间传递参数和结果
(4)IToolRecord CreateCurrentRecord();
IToolRecord CreateLastRunRecord();这两个运行结果接口
(5) event EventHandler Ran;
event EventHandler Running;
(6)IToolRunStatus RunStatus { get; } 运行状态
里面关键是参数绑定,首要在代码逻辑上实现,然后还要为ui界面考虑,既要保证功能,还要实现视图和数据分离
2.数据绑定
首先,一个问题,数据如何在工具中传递呢,借助一个设计模式,观察者模式,一个推送数据,一个接受,.NET 有现成的接口
/// <summary>
/// 获取属性绑定信息的接口
/// </summary>
public interface IPropertyBinderImplementation
{
/// <summary>
/// 数据输出端
/// </summary>
PropertySubjectCollection Senders
{
get;
}
/// <summary>
/// 数据输入端
/// </summary>
PropertySubjectCollection Receivers
{
get;
}
/// <summary>
/// 当前工具绑定到源对象
/// </summary>
/// <param name="destinationPath">当前对象路径</param>
/// <param name="source">源对象</param>
/// <param name="sourcePath">源对象路径</param>
void BindTo(string destinationPath, object source, string sourcePath);
// 获取匹配的属性源
IList<string> GetCompatibleOutputs(Type destinationType);
}
(1)变量观察者 INotifyPropertyChanged
设置属性时,触发该事件,这样就能够感知数据变化,推送数据
(2)IObserver
[Serializable]
public class PropertyObserver : PropertySubjectBase, IObserver<object>
{
private IDisposable unsubscriber;
// 数据源异常信息
[NonSerialized]
private Exception updateException;
private IObservable<object> Observable_;
private bool needCastConvert = false;
public PropertyObserver(object subject, string path)
: base(subject, path)
{
}
protected PropertyObserver(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public IObservable<object> Observable
{
get
{
return Observable_;
}
}
public Exception UpdateException
{
get { return updateException; }
}
public virtual void BindTo(IObservable<object> provider)
{
if (provider != null && provider != Observable_)
{
// 类型判断
var providerSubject = (PropertySubjectBase)provider;
if (providerSubject.ValueType != this.ValueType)
{
if (TypeConvertUtils.CanConvertType(providerSubject.PropertyExpression.Value.GetType(), this.ValueType))
{
needCastConvert = true;
}
else
{
throw new ArgumentException("类型之间无法进行转换!");
}
}
if (unsubscriber != null)
{// 已绑定则取消,保证绑定的唯一性
unsubscriber.Dispose();
}
unsubscriber = provider.Subscribe(this);
Observable_ = provider;
((PropertySubject)Observable_).Notify();
NotifyPropertyChanged("BindTo");
}
}
public virtual void Unsubscribe()
{
if (unsubscriber != null)
{
unsubscriber.Dispose();
unsubscriber = null;
Observable_ = null;
needCastConvert = false;
NotifyPropertyChanged("Unsubscribe");
}
}
void IObserver<object>.OnNext(object value)
{
if (needCastConvert)
{
PropertyExpression.Value = TypeConvertUtils.ConvertValue(value, value.GetType(), this.ValueType);
}
else
{
PropertyExpression.Value = value;
}
updateException = null;
}
void IObserver<object>.OnError(Exception error)
{
updateException = error;
}
// 退订
void IObserver<object>.OnCompleted()
{
Unsubscribe();
}
protected override void PrivateDispose()
{
Unsubscribe();
}
}
(3)IObservable
[Serializable]
public class PropertySubject : PropertySubjectBase, IObservable<object>
{
private List<IObserver<object>> _targetObservers;
public PropertySubject(object tool, string path) : base(tool, path)
{
ConnectExpressionEvent();
}
protected PropertySubject(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public void Notify()
{
object value = null;
Exception sourceException = null;
try
{
value = PropertyExpression.Value;
}
catch (Exception ex)
{
sourceException = ex;
}
if (sourceException != null)
{
foreach (var observer in _targetObservers)
{
observer.OnError(sourceException);
}
return;
}
try
{
// 同步操作,将来可能改为异步方案,或使用reactive
foreach (var observer in TargetObservers)
{
observer.OnNext(value);
}
}
catch (Exception)
{
}
}
// 取消所有接受者
public void EndTransmission()
{
var observers = new IObserver<object>[TargetObservers.Count];
TargetObservers.CopyTo(observers);
foreach (var item in observers)
{
item.OnCompleted();
}
NotifyPropertyChanged("ClearObservers");
}
// 添加接受者
public IDisposable Subscribe(IObserver<object> observer)
{
if (!TargetObservers.Contains(observer))
{
this.TargetObservers.Add(observer);
}
return new Unsubscriber(TargetObservers, observer);
}
public List<IObserver<object>> TargetObservers
{
get
{
if (_targetObservers == null)
{
_targetObservers = new List<IObserver<object>>();
}
return _targetObservers;
}
}
protected void ConnectExpressionEvent()
{
PropertyExpression.PropertyChanged += PropertyValueChanged;
}
protected void DisConnectExpressionEvent()
{
if (PropertyExpression != null)
{
PropertyExpression.PropertyChanged -= PropertyValueChanged;
}
}
protected override void PrivateDeserialize()
{
ConnectExpressionEvent();
}
protected override void PrivateDispose()
{
DisConnectExpressionEvent();
EndTransmission();
}
private void PropertyValueChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Value")
{
Notify();
}
}
// 退订
[Serializable]
private class Unsubscriber : IDisposable
{
private List<IObserver<object>> _observers;
private IObserver<object> _observer;
public Unsubscriber(List<IObserver<object>> observers, IObserver<object> observer)
{
this._observers = observers;
this._observer = observer;
}
public void Dispose()
{
if (_observer != null && _observers.Contains(_observer))
{
_observers.Remove(_observer);
}
}
}
}
(4)ISerializable
对象关系如何保存呢,重写这个接口
[Serializable]
public abstract class SerializableObjectBase : MarshalByRefObject, ISerializable
{
protected SerializableObjectBase()
{
}
protected SerializableObjectBase(SerializationInfo info, StreamingContext context)
{
SerializationSurrogate.SetObjectData(this, info, context);
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
IHasChanged HasChanged = this as IHasChanged;
if ( HasChanged != null && (context.State & StreamingContextStates.Persistence) != 0)
{
HasChanged.HasChanged = false;
}
GetObjectData(info, context);
}
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializationSurrogate.GetObjectData(this, info, context);
}
protected static Version GetArchivedAssemblyVersion(SerializationInfo info)
{
Match match = Regex.Match(info.AssemblyName, "Version=([^,]*),");
if (match.Success && match.Groups.Count == 2)
{
return new Version(match.Groups[1].Value);
}
return new Version();
}
}
[Serializable]
public abstract class SerializableComponentBase : Component, ISerializable
{
protected SerializableComponentBase()
{
}
protected SerializableComponentBase(SerializationInfo info, StreamingContext context)
{
SerializationSurrogate.SetObjectData(this, info, context);
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
IHasChanged HasChanged = this as IHasChanged;
if ( HasChanged != null && (context.State & StreamingContextStates.Persistence) != 0)
{
HasChanged.HasChanged = false;
}
GetObjectData(info, context);
}
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializationSurrogate.GetObjectData(this, info, context);
}
protected static Version GetArchivedAssemblyVersion(SerializationInfo info)
{
Match match = Regex.Match(info.AssemblyName, "Version=([^,]*),");
if (match.Success && match.Groups.Count == 2)
{
return new Version(match.Groups[1].Value);
}
return new Version();
}
}
3.界面
(1)因为上面数据属性使用了INotifyPropertyChanged接口,就可以使用通用的绑定控件了,winform就用MvvmFx.Bindings,Wpf直接就可以
(2)工具树如何实现呢,使用第三方树状控件就可以,很多不推荐了
4. 总结
单个工具实现了,再搞个工具组,基本可以实现常用的串行检测逻辑,图形界面可编辑,兼容多家图像算法库。
这种工具设计市面上已经有好多产品,这里介绍其设计原理,无论使用c++还是c#,基本这个设计思路。实现的过程中,加深了对面向对象和面向接口编程思想的理解和应用,熟悉了常用设计模式,为以后程序开发提供了极大的便利。
现在不做工业视觉,然后接触到机器人领域,有个ros系统,尤其最新ros2,了解其设计理念,比如行为树,也是可以用到工业视觉软件设计上的,这些思想都是通用的。