20240801_FJEQ_upperpc/FujianEarthquake_seabed_now/FujianEarthquake/ViewModels/ShoreBaseStationStatusDataViewModel.cs

706 lines
26 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using FujianEarthquake.Common;
using FujianEarthquake.DataAccess;
using FujianEarthquake.Models;
using FujianEarthquake.Views.UserControls;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using LiveCharts;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows;
namespace FujianEarthquake.ViewModels
{
public class ShoreBaseStationStatusDataViewModel : NotifyBase
{
#region Search Data
private DateTime _startDateTime;
public DateTime StartDateTime
{
get { return _startDateTime; }
set { Set(ref _startDateTime, value); }
}
private DateTime _endDateTime;
public DateTime EndDateTime
{
get { return _endDateTime; }
set { Set(ref _endDateTime, value); }
}
int PageIndex = 0;
private int recordCount;
public int RecordCount
{
get { return recordCount; }
set { recordCount = value; this.DoNotify(); }
}
private int totalPage;
public int TotalPage
{
get { return totalPage; }
set { totalPage = value; this.DoNotify(); }
}
private string shoreBaseStationStateMsg;
public string ShoreBaseStationStateMsg
{
get { return shoreBaseStationStateMsg; }
set { shoreBaseStationStateMsg = value; this.DoNotify(); }
}
#endregion
private ObservableCollection<ShoreBaseStationStateDataModel> shoreBaseStationStateDataList = new ObservableCollection<ShoreBaseStationStateDataModel>();
public ObservableCollection<ShoreBaseStationStateDataModel> ShoreBaseStationStateDataList
{
get { return shoreBaseStationStateDataList; }
set { shoreBaseStationStateDataList = value; this.DoNotify(); }
}
private ObservableCollection<ShoreBaseStationStateDataModel> totalShoreBaseStationStateDataList = new ObservableCollection<ShoreBaseStationStateDataModel>();
public ObservableCollection<ShoreBaseStationStateDataModel> TotalShoreBaseStationStateDataList
{
get { return totalShoreBaseStationStateDataList; }
set { totalShoreBaseStationStateDataList = value; this.DoNotify(); }
}
#region CommandBase
public CommandBase ForwordShoreBaseStationStateCommand { get; set; } //读取日志信息
public CommandBase NextShoreBaseStationStateCommand { get; set; } //读取日志信息
public CommandBase AskDataCommand { get; set; } //获取数据
public CommandBase ProSettingCommand { get; set; }
public CommandBase ParaSettingCommand { get; set; }
public CommandBase RefreshDataCommand { get; set; }
public CommandBase DownloadDataCommand { get; set; }
#endregion
#region Timer Define
public DispatcherTimer timerAskData = new DispatcherTimer();
public DispatcherTimer timerAskDataMsgCollapse = new DispatcherTimer();
public DispatcherTimer timerDownloadDataMsgHidden = new DispatcherTimer();
public DispatcherTimer timerCycleAskData = new DispatcherTimer();
#endregion
#region ShoreBaseStationModel
private byte fromDeviceAddress { get; set; } //从设备地址
private byte functionCode { get; set; } //功能码
private byte[] startingRegisterAddress { get; set; } //起始寄存器地址
private byte[] registerNumber { get; set; } //寄存器个数
private byte[] registerAddress { get; set; } //寄存器地址
private byte[] checkCodeCRC { get; set; } //校验码
private List<byte> checkByte { get; set; } = new List<byte>(); //校验码Byte
private byte[] writeData { get; set; } //数据
private List<byte> sendBytes { get; set; } = new List<byte>(); //发送数据
#endregion
#region Data Filtering
public static DialogViewModel vm;
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
this.DoNotify();
string timeSearch = "";
if (IsChecked)
{
if (string.IsNullOrEmpty(EndDateTime.ToString()) || string.IsNullOrEmpty(StartDateTime.ToString()))
{
IsChecked = false;
return;
}
if (EndDateTime < StartDateTime)
{
HandyControl.Controls.Dialog.Show(new TextDialog("起始时间大于结束时间,\n请重新输入"));
IsChecked = false;
return;
}
timeSearch = " and DataTime BETWEEN '" + StartDateTime + "' and '" + EndDateTime + "' ";
}
else
{
timeSearch = "";
}
//设置当前页为1
PageIndex = 1;
TotalShoreBaseStationStateDataList.Clear();
ShoreBaseStationStateDataList.Clear();
string sql = String.Format("select Out_Vol,Out_Cur from shorebasestation_output_state ORDER by id desc limit 100");
MySqlDataReader dataReader = DBHelper.ExecuteReader(sql, 1);
string sqlSub = String.Format("select * from shorebasestation_coil_state ORDER by id desc limit 100");
MySqlDataReader dataReaderSub = DBHelper.ExecuteReader(sqlSub, 1);
int index = 1;
while (dataReader.Read())
{
ShoreBaseStationStateDataModel shoreBaseStationStateDataModel = new ShoreBaseStationStateDataModel();
shoreBaseStationStateDataModel.Index = index++;
shoreBaseStationStateDataModel.RecordTime = Convert.ToDateTime(dataReader["RecordTime"]);
shoreBaseStationStateDataModel.Out_Vol = Convert.ToSingle(string.IsNullOrEmpty(dataReader["Out_Vol"].ToString()) ? "0" : dataReader["In_Vol"]);
shoreBaseStationStateDataModel.Out_Cur = Convert.ToSingle(string.IsNullOrEmpty(dataReader["Out_Cur"].ToString()) ? "0" : dataReader["In_Cur"]);
if (dataReaderSub.Read())
{
if (dataReaderSub["OutOverVol_Pro"].ToString() == "1")
shoreBaseStationStateDataModel.VolProStatus = (ImageSource)Application.Current.FindResource("DeviceOn");
else
shoreBaseStationStateDataModel.VolProStatus = (ImageSource)Application.Current.FindResource("DeviceOff");
if (dataReaderSub["OutOverCur_Pro"].ToString() == "1")
shoreBaseStationStateDataModel.CurProStatus = (ImageSource)Application.Current.FindResource("DeviceOn");
else
shoreBaseStationStateDataModel.CurProStatus = (ImageSource)Application.Current.FindResource("DeviceOff");
if (dataReaderSub["Out_Switch"].ToString() == "1")
shoreBaseStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("DeviceOn");
else
shoreBaseStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("DeviceOff");
}
TotalShoreBaseStationStateDataList.Add(shoreBaseStationStateDataModel);
}
dataReader.Dispose();
dataReaderSub.Dispose();
RecordCount = index - 1;
if (RecordCount <= 10)
{
TotalPage = 1;
ShoreBaseStationStateDataList = TotalShoreBaseStationStateDataList;
}
else
{
TotalPage = (int)Math.Ceiling((double)RecordCount / 10);
for (int i = 0; i < 10; i++)
{
ShoreBaseStationStateDataList.Add(TotalShoreBaseStationStateDataList[i]);
}
}
ShoreBaseStationStateMsg = string.Format("共计{0}页,当前第{1}页", TotalPage, PageIndex);
string record = "查询岸基站状态数据历史数据,查询时间范围为:" + StartDateTime + "至" + EndDateTime + ",共查询到" + RecordCount + "条历史数据";
sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('1','{DateTime.Now}','岸基站电控通信系统','数据查询','{record}');";
DBHelper.ExecuteNonQuery(sql, 1);
}
}
#endregion
public ShoreBaseStationStatusDataViewModel()
{
// 默认查询1天内的日志
this.EndDateTime = DateTime.Now;
this.StartDateTime = DateTime.Now.AddDays(-1);
PageIndex = 1;
vm = new DialogViewModel
{
Content = ""
};
#region Command Set
this.ForwordShoreBaseStationStateCommand = new CommandBase();
this.ForwordShoreBaseStationStateCommand.DoExcute = new Action<object>(ForwordShoreBaseStationState);
this.ForwordShoreBaseStationStateCommand.DoCanExcute = new Func<object, bool>((o) => true);
this.NextShoreBaseStationStateCommand = new CommandBase();
this.NextShoreBaseStationStateCommand.DoExcute = new Action<object>(NextShoreBaseStationState);
this.NextShoreBaseStationStateCommand.DoCanExcute = new Func<object, bool>((o) => true);
this.AskDataCommand = new CommandBase();
this.AskDataCommand.DoExcute = new Action<object>(AskData);
this.AskDataCommand.DoCanExcute = new Func<object, bool>((o) => true);
this.ProSettingCommand = new CommandBase();
this.ProSettingCommand.DoExcute = new Action<object>(ProSetting);
this.ProSettingCommand.DoCanExcute = new Func<object, bool>((o) => true);
this.ParaSettingCommand = new CommandBase();
this.ParaSettingCommand.DoExcute = new Action<object>(ParaSetting);
this.ParaSettingCommand.DoCanExcute = new Func<object, bool>((o) => true);
this.RefreshDataCommand = new CommandBase();
this.RefreshDataCommand.DoExcute = new Action<object>(RefreshData);
this.RefreshDataCommand.DoCanExcute = new Func<object, bool>((o) => true);
this.DownloadDataCommand = new CommandBase();
this.DownloadDataCommand.DoExcute = new Action<object>(DownloadData);
this.DownloadDataCommand.DoCanExcute = new Func<object, bool>((o) => true);
#endregion
#region Timer Set
timerAskData.Interval = TimeSpan.FromSeconds(20);
timerAskData.Tick += TimerAskData_Tick;
timerAskDataMsgCollapse.Interval = TimeSpan.FromSeconds(2);
timerAskDataMsgCollapse.Tick += TimerAskDataMsgCollapse_Tick;
timerDownloadDataMsgHidden.Interval = TimeSpan.FromSeconds(2);
timerDownloadDataMsgHidden.Tick += TimerDownloadDataMsgHidden_Tick;
#endregion
}
#region Ask Data
private void TimerAskData_Tick(object sender, EventArgs e)
{
if (!AskDataBtnIsReceived)
{
AskDataMsgVisibility = Visibility.Visible;
AskDataMsg = "请求数据发送成功,但未接收到数据!";
timerAskDataMsgCollapse.Start();
AskDataMsgForeground = new SolidColorBrush(Colors.Red);
AskDataBtnIsEnabled = true;
}
// 停止定时器
(sender as DispatcherTimer).Stop();
}
private void TimerAskDataMsgCollapse_Tick(object sender, EventArgs e)
{
AskDataMsgVisibility = Visibility.Hidden;
// 停止定时器
(sender as DispatcherTimer).Stop();
}
private bool cycleRequestIsChecked;
public bool CycleRequestIsChecked
{
get { return cycleRequestIsChecked; }
set
{
cycleRequestIsChecked = value;
this.DoNotify();
if (CycleRequestIsChecked)
{
if (string.IsNullOrEmpty(CycleRequestCycle))
{
CycleRequestIsChecked = false;
return;
//可改为自动设定周期
}
//周期获取数据
timerCycleAskData.Interval = TimeSpan.FromSeconds(int.Parse(CycleRequestCycle));
timerCycleAskData.Tick += TimerCycleAskData_Tick;
timerCycleAskData.Start();
string record = "周期请求岸基站状态数据已开启,请求周期为:" + CycleRequestCycle;
string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('1','{DateTime.Now}','岸基站电控通信系统','数据请求','{record}');";
DBHelper.ExecuteNonQuery(sql, 1);
}
else
{
//停止定时器
timerCycleAskData.Stop();
string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('1','{DateTime.Now}','岸基站电控通信系统','数据请求','周期请求岸基站状态数据已关闭');";
DBHelper.ExecuteNonQuery(sql, 1);
}
}
}
private void TimerCycleAskData_Tick(object sender, EventArgs e)
{
AskShoreBaseStationData();
}
private string cycleRequestCycle;
public string CycleRequestCycle
{
get { return cycleRequestCycle; }
set { cycleRequestCycle = value; this.DoNotify(); }
}
private string askDataMsg;
public string AskDataMsg
{
get { return askDataMsg; }
set { askDataMsg = value; this.DoNotify(); }
}
private Brush askDataMsgForeground;
public Brush AskDataMsgForeground
{
get { return askDataMsgForeground; }
set { askDataMsgForeground = value; this.DoNotify(); }
}
private bool askDataBtnIsEnabled = true;
public bool AskDataBtnIsEnabled
{
get { return askDataBtnIsEnabled; }
set { askDataBtnIsEnabled = value; this.DoNotify(); }
}
private bool askDataBtnIsReceived = false;
public bool AskDataBtnIsReceived
{
get { return askDataBtnIsReceived; }
set { askDataBtnIsReceived = value; this.DoNotify(); }
}
private Visibility askDataMsgVisibility = Visibility.Visible;
public Visibility AskDataMsgVisibility
{
get { return askDataMsgVisibility; }
set { askDataMsgVisibility = value; this.DoNotify(); }
}
public void AskData(object o)
{
AskShoreBaseStationData();
}
private void AskShoreBaseStationData()
{
AskDataBtnIsEnabled = false;
AskDataBtnIsReceived = false;
//查询从设备寄存器内容
byte deviceAddress;
deviceAddress = Convert.ToByte(Tools.GetAppSetting("DeviceAddress2"));
fromDeviceAddress = deviceAddress; //从设备地址
functionCode = 0x03; //功能码
startingRegisterAddress = new byte[2] { 0x00, 0x00 }; //起始寄存器地址
registerNumber = new byte[2] { 0x00, 0x0A }; //寄存器个数
//校验码计算
checkByte.Clear();
checkByte.Add(fromDeviceAddress);
checkByte.Add(functionCode);
checkByte.AddRange(startingRegisterAddress);
checkByte.AddRange(registerNumber);
checkCodeCRC = Tools.CRCCalcRev(checkByte.ToArray());
//发送指令
sendBytes.Clear();
sendBytes.Add(fromDeviceAddress);
sendBytes.Add(functionCode);
sendBytes.AddRange(startingRegisterAddress);
sendBytes.AddRange(registerNumber);
sendBytes.AddRange(checkCodeCRC);
bool result = false;
if (MainWindow.mainViewModel.clientModel1.IsConnected)
result = MainWindow.mainViewModel.clientModel1.SendMessage(sendBytes.ToArray());
else
{
AskDataMsgVisibility = Visibility.Visible;
AskDataMsg = "通信未连接!";
timerAskDataMsgCollapse.Start();
AskDataMsgForeground = new SolidColorBrush(Colors.Red);
AskDataBtnIsEnabled = true;
return;
}
if (result)
{
AskDataMsgVisibility = Visibility.Visible;
AskDataMsg = "请求岸基站状态数据发送成功!";
timerAskDataMsgCollapse.Start();
AskDataMsgForeground = new SolidColorBrush(Colors.Green);
timerAskData.Start();
}
else
{
AskDataMsgVisibility = Visibility.Visible;
AskDataMsg = "请求岸基站状态数据发送失败!";
timerAskDataMsgCollapse.Start();
AskDataMsgForeground = new SolidColorBrush(Colors.Red);
AskDataBtnIsEnabled = true;
}
string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('1','{DateTime.Now}','岸基站电控通信系统','数据请求','{AskDataMsg}');";
DBHelper.ExecuteNonQuery(sql, 1);
}
#endregion
#region Refresh Data
public void RefreshData(object o)
{
string timeSearch = "";
if (IsChecked)
{
timeSearch = " and DataTime BETWEEN '" + StartDateTime + "' and '" + EndDateTime + "' ";
}
else
{
timeSearch = "";
}
//设置当前页为1
PageIndex = 1;
TotalShoreBaseStationStateDataList.Clear();
ShoreBaseStationStateDataList.Clear();
string sql = String.Format("select * from shorebasestation_state {0} ORDER by id desc limit 100", timeSearch);
MySqlDataReader dataReader = DBHelper.ExecuteReader(sql, 1);
int index = 1;
while (dataReader.Read())
{
ShoreBaseStationStateDataModel shoreBaseStationStateDataModel = new ShoreBaseStationStateDataModel();
shoreBaseStationStateDataModel.Index = index++;
shoreBaseStationStateDataModel.RecordTime = Convert.ToDateTime(dataReader["RecordTime"]);
shoreBaseStationStateDataModel.Out_Vol = Convert.ToSingle(string.IsNullOrEmpty(dataReader["In_Vol"].ToString()) ? "0" : dataReader["In_Vol"]);
shoreBaseStationStateDataModel.Out_Cur = Convert.ToSingle(string.IsNullOrEmpty(dataReader["In_Cur"].ToString()) ? "0" : dataReader["In_Cur"]);
if (dataReader["VolProStatus"].ToString() == "1")
shoreBaseStationStateDataModel.VolProStatus = (ImageSource)Application.Current.FindResource("DeviceOn");
else
shoreBaseStationStateDataModel.VolProStatus = (ImageSource)Application.Current.FindResource("DeviceOff");
if (dataReader["CurProStatus"].ToString() == "1")
shoreBaseStationStateDataModel.CurProStatus = (ImageSource)Application.Current.FindResource("DeviceOn");
else
shoreBaseStationStateDataModel.CurProStatus = (ImageSource)Application.Current.FindResource("DeviceOff");
if (dataReader["RelayStatus"].ToString() == "1")
shoreBaseStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("DeviceOn");
else
shoreBaseStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("DeviceOff");
TotalShoreBaseStationStateDataList.Add(shoreBaseStationStateDataModel);
}
dataReader.Dispose();
RecordCount = index - 1;
if (RecordCount <= 10)
{
TotalPage = 1;
ShoreBaseStationStateDataList = TotalShoreBaseStationStateDataList;
}
else
{
TotalPage = (int)Math.Ceiling((double)RecordCount / 10);
for (int i = 0; i < 10; i++)
{
ShoreBaseStationStateDataList.Add(TotalShoreBaseStationStateDataList[i]);
}
}
ShoreBaseStationStateMsg = string.Format("共计{0}页,当前第{1}页", TotalPage, PageIndex);
sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('1','{DateTime.Now}','岸基站电控通信系统','数据刷新','刷新岸基站状态数据');";
DBHelper.ExecuteNonQuery(sql, 1);
}
#endregion
#region DownloadData
private void TimerDownloadDataMsgHidden_Tick(object sender, EventArgs e)
{
DownloadDataMsgVisibility = Visibility.Hidden;
// 停止定时器
(sender as DispatcherTimer).Stop();
}
private string downloadDataMsg;
public string DownloadDataMsg
{
get { return downloadDataMsg; }
set { downloadDataMsg = value; this.DoNotify(); }
}
private Brush downloadDataMsgForeground;
public Brush DownloadDataMsgForeground
{
get { return downloadDataMsgForeground; }
set { downloadDataMsgForeground = value; this.DoNotify(); }
}
private bool downloadDataBtnIsEnabled = true;
public bool DownloadDataBtnIsEnabled
{
get { return downloadDataBtnIsEnabled; }
set { downloadDataBtnIsEnabled = value; this.DoNotify(); }
}
private Visibility downloadDataMsgVisibility = Visibility.Visible;
public Visibility DownloadDataMsgVisibility
{
get { return downloadDataMsgVisibility; }
set { downloadDataMsgVisibility = value; this.DoNotify(); }
}
public void DownloadData(object o)
{
DownloadDataBtnIsEnabled = false;
string shoreBaseStationFolder = Tools.GetAppSetting("ShoreBaseStationFolder");
string savePath = CSVDownload.CreateFile(shoreBaseStationFolder, "ShoreBaseStationStateData_" + DateTime.Now.ToString("yyyyMMddhhMMss"), "csv");
bool result = CSVDownload.SaveShoreBaseStationDataToCSVFile(TotalShoreBaseStationStateDataList, savePath);
if (result)
{
DownloadDataMsg = "下载数据成功!";
DownloadDataMsgVisibility = Visibility.Visible;
DownloadDataMsgForeground = new SolidColorBrush(Colors.Green);
}
else
{
DownloadDataMsg = "下载数据失败!";
DownloadDataMsgVisibility = Visibility.Visible;
DownloadDataMsgForeground = new SolidColorBrush(Colors.Red);
}
timerDownloadDataMsgHidden.Start();
DownloadDataBtnIsEnabled = true;
string record = "下载岸基站状态数据," + DownloadDataMsg;
string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('1','{DateTime.Now}','岸基站电控通信系统','数据下载','{record}');";
DBHelper.ExecuteNonQuery(sql, 1);
}
#endregion
#region Page Switching
public void ForwordShoreBaseStationState(object o)
{
if (PageIndex == 1)
return;
try
{
PageIndex -= 1;
ShoreBaseStationStateDataList.Clear();
for (int i = 0; i < 10; i++)
{
ShoreBaseStationStateDataList.Add(TotalShoreBaseStationStateDataList[i + (PageIndex - 1) * 10]);
}
ShoreBaseStationStateMsg = string.Format("共计{0}页,当前第{1}页", TotalPage, PageIndex);
}
catch
{
TotalShoreBaseStationStateDataList.Clear();
ShoreBaseStationStateDataList.Clear();
}
}
public void NextShoreBaseStationState(object o)
{
if (PageIndex == TotalPage)
return;
try
{
PageIndex += 1;
ShoreBaseStationStateDataList.Clear();
for (int i = 0; i < (PageIndex == TotalPage ? (RecordCount - (PageIndex - 1) * 10) : 10); i++)
{
ShoreBaseStationStateDataList.Add(TotalShoreBaseStationStateDataList[i + (PageIndex - 1) * 10]);
}
ShoreBaseStationStateMsg = string.Format("共计{0}页,当前第{1}页", TotalPage, PageIndex);
}
catch
{
TotalShoreBaseStationStateDataList.Clear();
ShoreBaseStationStateDataList.Clear();
}
}
#endregion
#region Para Set
public void ParaSetting(object o)
{
//HandyControl.Controls.Dialog.Show();
}
#endregion
#region Pro Set
public void ProSetting(object o)
{
//HandyControl.Controls.Dialog.Show();
}
#endregion
}
}