Files
MoviconHub/MoviconHub.App/Models/ClearAction.cs
2025-09-17 17:22:09 +08:00

142 lines
3.9 KiB
C#

using System;
namespace MoviconHub.App.Models
{
/// <summary>
/// 清洗动作
/// </summary>
public class ClearAction
{
/// <summary>
/// 清洗事件
/// </summary>
public event EventHandler<string> ClearActionEvent;
/// <summary>
/// 设备状态改变事件
/// </summary>
public event EventHandler<StateInfo> DeviceStateChangeEvent;
// 状态变更并发锁:确保在多线程环境下,状态切换与事件发布的原子性,避免竞态条件
private readonly object _stateLock = new object();
// 是否已存在当前状态:用于首次赋值时不发布“上一状态”事件的标记
private bool _hasCurrentState = false;
private bool _ClearEnd;
/// <summary>
/// 清洗完成信号
/// </summary>
public bool ClearEnd
{
get { return _ClearEnd; }
set
{
if (_ClearEnd != value)
{
_ClearEnd = value;
//清洗完成
if (_ClearEnd)
{
ClearActionEvent.BeginInvoke(this, "清洗完成", null, null);
}
}
}
}
private bool _DeviceClose;
/// <summary>
/// 设备关机信号
/// </summary>
public bool DeviceClose
{
get { return _DeviceClose; }
set
{
if (_DeviceClose != value)
{
_DeviceClose = value;
//清洗完成
if (_DeviceClose)
{
ClearActionEvent.BeginInvoke(this, "设备关机", null, null);
}
}
}
}
/// <summary>
/// 当前状态信息
/// </summary>
public StateInfo CurStateInfo { get; set; } = new StateInfo();
private int _DeviceState;
/// <summary>
/// 设备状态
/// </summary>
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;
}
}
}
}
}
/// <summary>
/// 状态信息
/// </summary>
public class StateInfo
{
/// <summary>
/// 开始时间
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime EndTime { get; set; }
/// <summary>
/// 值
/// </summary>
public int State { get; set; }
}
}