using HMI.AlarmInfoManage.Entity;
using HMI.AlarmInfoManage.Model;
using HMI.Base;
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.UI.Util;
using Microsoft.Win32;
using NPOI.XSSF.UserModel;
using Sharp7;
using SimensDriver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
namespace HMI.AlarmInfoManage
{
///
/// UserControl1.xaml 的交互逻辑
///
public partial class AlarmInfoManage : PluginControl
{
private string blockPath;
private string markPath;
private string textSettingPath;
private Simens plc = new Simens();
private XmlUIModel Model;
private bool isHaveAlarm;
private bool isNewAlarm;
private SqliteHelper sqliteHelper;
private Timer MonitorTimer;
private Timer PcTimer;
///
/// pc警告数字信号
///
private int isPcAlarmnumber = 0;
///
/// 当前报警信息
///
private string currentInfo = null;
///
/// 接收报警的队列
///
private MSMQHelper alarmQueue = new MSMQHelper("LTHMI_Alarm");
///
/// 日志生成器
///
private MSMQHelper loggeralarm = new MSMQHelper("LTHMI_Logger");
///
/// 刷新报警的队列
///
private MSMQHelper alarmRefershToMain = new MSMQHelper("LTHMI_Alarm_Rrfresh");
///
/// 报警
///
private byte[] alarmCodeBytes;
///
/// 报警信息缓存
///
private List currentAlarmCachePlc = new List();
///
/// PLC报警信息缓存
///
private List preAlarmCachePlc = new List();
///
/// 报警信息缓存
///
private List currentAlarmCachePc = new List();
///
/// 代码管理
///
private List alarmSettings = new List();
//
/// 标志位报警管理
///
private List signAlarmSetting = new List();
///
/// 报警文本列表
///
private List alarmTexts = new List();
///
/// 传至主窗体的报警信息
///
private List currentAlarmCachePlcToMain = new List();
private AlarmText alarm;
private SystemSetting systemSetting;
public AlarmInfoManage()
{
systemSetting = SystemSetting.Instance;
InitializeComponent();
}
public override void InitFinish()
{
Model = new XmlUIModel(BaseFolder);
DataContext = Model;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
switch (btn.Name)
{
case "settingBtn":
OpenSettingWindow();
break;
case "refreshBtn":
//Model.
break;
case "importBtn":
ImportText();
break;
default:
break;
}
}
private void OpenSettingWindow()
{
AlarmSettingList listModal = new AlarmSettingList(blockPath, markPath, log)
{
Owner = Window.GetWindow(this)
};
listModal.ShowDialog();
}
private void ImportText()
{
try
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Filter = "Files (*.xlsm)|*.xlsm";
if (openDialog.ShowDialog() == true)
{
this.ImportExcelAlarmText(openDialog.FileName);
}
}
catch (Exception ex)
{
log.Error("AlarmText Import Failed.", ex);
ToastHelper.Error(Window.GetWindow(this), $"{this.lang("App.ImportFailed")}: {ex.Message}");
}
}
///
/// 导入报警代码文本
///
/// 电子设计表格文件
private void ImportExcelAlarmText(string excelFile)
{
int index = 0;
try
{
if (excelFile.IndexOf(".xlsm") < 0)
{
this.Warning(this.lang("Alm.OnlySupportXlsm"));
return;
}
this.alarmTexts.Clear();
XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheet("sheet1");
XSSFRow row = null;
for (int i = 2; i < (sheet.LastRowNum + 1); i++)
{
index = i;
row = (XSSFRow)sheet.GetRow(i);
if (row != null)
{
AlarmText alarm = new AlarmText();
alarm.AlarmCode = row.Cells[0].StringCellValue;
alarm.OpNo = row.Cells[1].StringCellValue;
alarm.ModuleNo = row.Cells[2].StringCellValue;
alarm.ModuleName_CN = row.Cells[3].StringCellValue;
alarm.ModuleName_EN = row.Cells[4].StringCellValue;
alarm.MAlarmCode = row.Cells[5].StringCellValue;
alarm.MAlarmText_CN = row.Cells[6].StringCellValue;
alarm.MAlarmText_EN = row.Cells[7].StringCellValue;
this.alarmTexts.Add(alarm);
}
}
if (sheet.LastRowNum > 0)
{
XmlHelper.SerializeToXml(textSettingPath, this.alarmTexts);
}
this.Success(this.lang("App.ImportSuccess"));
}
catch (Exception ex)
{
log.Error($"Row {index} AlarmText Import Failed.", ex);
this.Error($"{this.lang("Alm.RowImportFailed", index)}: {ex.Message}");
}
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(systemSetting.PlcIp))
{
if (this.plc.isConnection)
{
this.plc.Simens_S7_ConnectPLC(systemSetting.PlcIp, 102, 0, 1, string.Empty);
}
}
MonitorTimer = new Timer
{
Interval = 100,
};
MonitorTimer.Elapsed += MonitorTimer_Elapsed;
PcTimer = new Timer
{
Interval = 100,
};
PcTimer.Elapsed += PcTimer_Elapsed; ;
Loaded -= UserControl_Loaded;
}
private void PcTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
PcTimer.Enabled = false;
this.alarmQueue.Receive(100, out string MessageID, out string MsgStr);
if (MessageID != string.Empty)
{
log.Info(MsgStr);
switch (MessageID)
{
case "Clear":
////this.currentAlarmCachePc.RemoveAll(alarm => alarm.Source == "PC");
this.currentAlarmCachePc.Clear();
this.RefershAlarm();
break;
default:
AlarmText aalarm = this.alarmTexts.Find(alarm => alarm.AlarmCode == MsgStr);
aalarm.Source = "PC";
aalarm.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if ((aalarm != null) && (this.currentAlarmCachePc.Find(alarm => alarm.AlarmCode == aalarm.AlarmCode) == null))
{
this.currentAlarmCachePc.Add(aalarm);
this.RefershAlarm();
this.isPcAlarmnumber = this.currentAlarmCachePc.Count;
}
break;
}
}
}
catch (Exception ex)
{
log.Error("PcTimer Execute Failed", ex);
}
finally
{
PcTimer.Enabled = true;
}
}
private void MonitorTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
this.MonitorTimer.Enabled = false;
isHaveAlarm = false;
foreach (var item in signAlarmSetting)
{
isHaveAlarm = isHaveAlarm ||
this.plc.Simens_S7_ReadBool_DB(item.DBAddress, item.StartAddress, item.Length);
}
////有报警
if (isHaveAlarm)
{
this.isNewAlarm = false;
this.currentAlarmCachePlc.Clear();
RefreshDBSetting();
for (int i = 0; i < ((int)alarmCodeBytes.Length / 4); i++)
{
int code = S7.GetDIntAt(alarmCodeBytes, 4 * i);
////有报警
if (code != 0)
{
string acode = string.Format("{0:d10}", code);
alarm = this.alarmTexts.Find(item => item.AlarmCode == acode);
if (alarm != null)
{
alarm.Source = "PLC";
alarm.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
this.currentAlarmCachePlc.Add(alarm);
////有新报警
if (this.preAlarmCachePlc.Find(alarm => alarm.AlarmCode == acode) == null)
{
this.isNewAlarm = true;
this.SendLogMsg(alarm.ModuleName_CN + alarm.MAlarmText_CN);
}
}
}
}
////有新报警和报警减少时刷新报警表
if (this.isNewAlarm || (this.currentAlarmCachePlc.Count != this.preAlarmCachePlc.Count))
{
this.currentAlarmCachePlcToMain = XmlHelper.DeepClone(this.currentAlarmCachePlc);
this.RefershAlarm();
}
this.preAlarmCachePlc.Clear();
this.preAlarmCachePlc = XmlHelper.DeepClone(this.currentAlarmCachePlc);
}
else
{
if (this.preAlarmCachePlc.Count != 0 || this.currentAlarmCachePlcToMain.Count != 0 || this.currentAlarmCachePlc.Count != 0)
{
this.preAlarmCachePlc.Clear();
this.currentAlarmCachePlcToMain.Clear();
this.currentAlarmCachePlc.Clear();
this.RefershAlarm();
}
}
}
catch (Exception ex)
{
log.Error("sdadsa", ex);
}
finally
{
this.MonitorTimer.Enabled = true;
}
}
///
/// 刷新报警块信息
///
private void RefreshDBSetting()
{
List bytes = new List();
foreach (var item in alarmSettings)
{
byte[] itemalarmCodeBytes = this.plc.Simens_S7_ReadBytes_DB("DB", item.DBAddress, item.StartAddress, item.Length);
bytes.AddRange(itemalarmCodeBytes.ToList());
}
alarmCodeBytes = bytes.ToArray();
}
///
/// 刷新报警信息
///
private void RefershAlarm()
{
this.alarmRefershToMain.Send("AlarmRefersh", string.Empty);
foreach (AlarmText alarm in this.currentAlarmCachePlc)
{
this.currentInfo = alarm.ModuleName_CN + alarm.MAlarmText_CN;
Model.Datasource.Add(alarm);
string sqladd = string.Format("INSERT INTO Alarm (source, alarmcode, alarminfo, time) VALUES( '{0}','{1}','{2}','{3}');",
alarm.Source, alarm.AlarmCode, this.currentInfo, alarm.Time);
sqliteHelper.ExecuteSql(sqladd);
}
foreach (AlarmText alarm in this.currentAlarmCachePc)
{
Model.Datasource.Add(alarm);
string sqladd2 = string.Format("INSERT INTO Alarm (source, alarmcode, alarminfo, time) VALUES( '{0}','{1}','{2}','{3}');", alarm.Source, alarm.AlarmCode, this.currentInfo, alarm.Time);
this.sqliteHelper.ExecuteSql(sqladd2);
}
}
///
/// 发送日志消息
///
/// 日志消息
private void SendLogMsg(string Msg)
{
string LogMsg = "{\"Type\":\"Alarm\",\"Source\":\"" + alarm.Source + "\",\"Msg\":\"" + Msg + "\",\"Time\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\"}";
this.loggeralarm.Send("Log", LogMsg);
}
public override void SetBaseFolder(string folder)
{
base.SetBaseFolder(folder);
blockPath = Path.Combine(BaseFolder, "BlockSetting.xml");
markPath = Path.Combine(BaseFolder, "MarkSetting.xml");
textSettingPath = Path.Combine(BaseFolder, "textSetting.xml");
}
}
}