using ProjectBase.Data.Redis;
using SIMDP.Model;
using ProjectBase.Util;
using System.Collections.Generic;
using System.Timers;
namespace SIMDP.Device
{
public abstract class AbstractBaseDevice
{
public AbstractBaseDevice()
{
timer.Elapsed += timer_Elapsed;
}
#region 数据定义
///
/// Redis
///
protected RedisHelper redis = new RedisHelper(0);
///
/// 轮询定时器
///
protected Timer timer = new Timer() { Enabled = false, AutoReset = false };
///
/// 定时器停止标志
///
protected bool timerStopped = false;
///
///PLC配置信息
///
protected MoPlcInfo plcInfo;
#endregion
#region 接口函数
///
/// 设备启动
///
public abstract void Start(MoPlcInfo _plcInfo, List _dataPoints);
///
/// 设备停止
///
public virtual void Stop()
{
actionStop();
SetRedisPlcDisConnect();
timerStopped = true;
}
///
/// 设备连接状态
///
public abstract bool isConnected();
///
/// 设备连接
///
///
protected abstract bool Connect();
///
/// 设备断开
///
protected abstract void Disconnect();
///
/// 定时器逻辑
///
///
///
public virtual void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!isConnected()) // 判断连接状态
{
try
{
Connect();
}
catch
{ }
}
else // PLC已连接,执行自定义函数
{
actionTimer();
}
if (!timerStopped)
{
timer.Start();
}
else
{
Disconnect();
}
}
#endregion
#region 自定义函数
///
/// 启动时执行的自定义函数,可重写
///
public virtual void actionStart() { }
///
/// 停止时执行的自定义函数,可重写
///
public virtual void actionStop() { }
///
/// 连接成功时执行的自定义函数,可重写
///
public virtual void actionConnected() { }
///
/// 连接成功后每次定时器执行的函数,可重写
///
public virtual void actionTimer() { }
#endregion
#region Redis
protected void SetRedisPlcConnected()
{
redis.SetString(SysEnvironment.PlcStatusPrefix + ":" + plcInfo.PlcId.ToString() + plcInfo.PlcName, "2");
redis.Publish(SysEnvironment.PlcStatusChannel, "2");
}
protected void SetRedisPlcDisConnect()
{
if (timerStopped)
return; //设备断开时,已在Stop()中更新连接状态,避免重连后状态覆盖
redis.SetString(SysEnvironment.PlcStatusPrefix + ":" + plcInfo.PlcId.ToString() + plcInfo.PlcName, "3");
redis.Publish(SysEnvironment.PlcStatusChannel, "3");
}
protected void UpdataRedisDataPoint(MoDataPoint mo, string value, bool refresh = false)
{
string key = SysEnvironment.PlcPointsPrefix + ":" + plcInfo.PlcName + ":" + mo.DataPointId.ToString() + mo.DataPointName;
redis.SetString(key, value);
if (refresh)
redis.Publish(SysEnvironment.OpcDataChannel, value);
}
#endregion
}
}