using System;
namespace MoviconHub.App.Models
{
///
/// 清洗动作
///
public class ClearAction
{
///
/// 清洗事件
///
public event EventHandler ClearActionEvent;
///
/// 设备状态改变事件
///
public event EventHandler DeviceStateChangeEvent;
// 状态变更并发锁:确保在多线程环境下,状态切换与事件发布的原子性,避免竞态条件
private readonly object _stateLock = new object();
// 是否已存在当前状态:用于首次赋值时不发布“上一状态”事件的标记
private bool _hasCurrentState = false;
private bool _ClearEnd;
///
/// 清洗完成信号
///
public bool ClearEnd
{
get { return _ClearEnd; }
set
{
if (_ClearEnd != value)
{
_ClearEnd = value;
//清洗完成
if (_ClearEnd)
{
ClearActionEvent.BeginInvoke(this, "清洗完成", null, null);
}
}
}
}
private bool _DeviceClose;
///
/// 设备关机信号
///
public bool DeviceClose
{
get { return _DeviceClose; }
set
{
if (_DeviceClose != value)
{
_DeviceClose = value;
//清洗完成
if (_DeviceClose)
{
ClearActionEvent.BeginInvoke(this, "设备关机", null, null);
}
}
}
}
///
/// 当前状态信息
///
public StateInfo CurStateInfo { get; set; } = new StateInfo();
private int _DeviceState;
///
/// 设备状态
///
public int DeviceState
{
get { return _DeviceState; }
set
{
if (_DeviceState != value)
{
lock (_stateLock)
{
var now = DateTime.Now;
// 若已有当前状态,先发布上一个状态的维持区间
if (_hasCurrentState)
{
var prevStateInfo = new StateInfo
{
StartTime = CurStateInfo.StartTime,
EndTime = now,
State = CurStateInfo.State
};
var handler = DeviceStateChangeEvent;
handler?.BeginInvoke(this, prevStateInfo, null, null);
}
// 更新为新的当前状态
_DeviceState = value;
CurStateInfo = new StateInfo
{
StartTime = now,
EndTime = default, // 结束时间在下次状态变化时确定
State = value
};
_hasCurrentState = true;
}
}
}
}
}
///
/// 状态信息
///
public class StateInfo
{
///
/// 开始时间
///
public DateTime StartTime { get; set; }
///
/// 结束时间
///
public DateTime EndTime { get; set; }
///
/// 值
///
public int State { get; set; }
}
}