using JiangsuEarthquake.Common; using JiangsuEarthquake.DataAccess; using JiangsuEarthquake.Models; using JiangsuEarthquake.Views; using JiangsuEarthquake.Views.UserControls; using LiveCharts; using LiveCharts.Defaults; using LiveCharts.Wpf; using MySql.Data.MySqlClient; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Media; using System.Windows.Threading; using Application = System.Windows.Application; using Brush = System.Windows.Media.Brush; using Color = System.Windows.Media.Color; namespace JiangsuEarthquake.ViewModels { public class BoosterStationStateDataViewModel : NotifyBase { public BoosterStationStateDataModel boosterStationStateDataModel { get; set; } = new BoosterStationStateDataModel(); public BoosterStationStateDataView boosterStationStateDataView { get; set; } = new BoosterStationStateDataView(); #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 int boosterStationStateTotalPage; public int BoosterStationStateTotalPage { get { return boosterStationStateTotalPage; } set { boosterStationStateTotalPage = value; this.DoNotify(); } } private int boosterStationStateNowPage; public int BoosterStationStateNowPage { get { return boosterStationStateNowPage; } set { boosterStationStateNowPage = value; this.DoNotify(); } } #endregion private ObservableCollection boosterStationStateDataList = new ObservableCollection(); public ObservableCollection BoosterStationStateDataList { get { return boosterStationStateDataList; } set { boosterStationStateDataList = value; this.DoNotify(); } } private ObservableCollection totalBoosterStationStateDataList = new ObservableCollection(); public ObservableCollection TotalBoosterStationStateDataList { get { return totalBoosterStationStateDataList; } set { totalBoosterStationStateDataList = value; this.DoNotify(); } } #region CommandBase public CommandBase ForwordBoosterStationStateCommand { get; set; } //读取日志信息 public CommandBase NextBoosterStationStateCommand { get; set; } //读取日志信息 public CommandBase AskDataCommand { get; set; } //获取数据 public CommandBase RefreshDataCommand { get; set; } public CommandBase DownloadDataCommand { get; set; } public CommandBase SearchBoosterStationStateCommand { get; set; } public CommandBase ResetSearchCommand { get; set; } #endregion int station_id = 1; #region Timer Define public DispatcherTimer timerAskData = new DispatcherTimer(); public DispatcherTimer timerAskDataMsgCollapse = new DispatcherTimer(); public DispatcherTimer timerCycleAskData1 = new DispatcherTimer(); public DispatcherTimer timerCycleAskData2 = new DispatcherTimer(); #endregion #region VolCurCollectorModel 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 checkByte { get; set; } = new List(); //校验码Byte private byte[] writeData { get; set; } //数据 private List sendBytes { get; set; } = new List(); //发送数据 #endregion public static DialogViewModel vm; public BoosterStationStateDataViewModel(int id) { // 默认查询1天内的日志 this.EndDateTime = DateTime.Now; this.StartDateTime = DateTime.Now.AddDays(-1); PageIndex = 1; station_id = id; vm = new DialogViewModel { Content = "" }; #region Command Set this.ForwordBoosterStationStateCommand = new CommandBase(); this.ForwordBoosterStationStateCommand.DoExcute = new Action(ForwordBoosterStationState); this.ForwordBoosterStationStateCommand.DoCanExcute = new Func((o) => true); this.NextBoosterStationStateCommand = new CommandBase(); this.NextBoosterStationStateCommand.DoExcute = new Action(NextBoosterStationState); this.NextBoosterStationStateCommand.DoCanExcute = new Func((o) => true); this.AskDataCommand = new CommandBase(); this.AskDataCommand.DoExcute = new Action(AskData); this.AskDataCommand.DoCanExcute = new Func((o) => true); this.RefreshDataCommand = new CommandBase(); this.RefreshDataCommand.DoExcute = new Action(RefreshData); this.RefreshDataCommand.DoCanExcute = new Func((o) => true); this.DownloadDataCommand = new CommandBase(); this.DownloadDataCommand.DoExcute = new Action(DownloadData); this.DownloadDataCommand.DoCanExcute = new Func((o) => true); this.SearchBoosterStationStateCommand = new CommandBase(); this.SearchBoosterStationStateCommand.DoExcute = new Action(SearchBoosterStationState); this.SearchBoosterStationStateCommand.DoCanExcute = new Func((o) => true); this.ResetSearchCommand = new CommandBase(); this.ResetSearchCommand.DoExcute = new Action(ResetSearch); this.ResetSearchCommand.DoCanExcute = new Func((o) => true); #endregion #region Timer Set timerAskData.Interval = TimeSpan.FromSeconds(20); timerAskData.Tick += TimerAskData_Tick; timerAskDataMsgCollapse.Interval = TimeSpan.FromSeconds(2); timerAskDataMsgCollapse.Tick += TimerAskDataMsgCollapse_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; //可改为自动设定周期 } //周期获取数据 if (station_id == 1) { timerCycleAskData1.Interval = TimeSpan.FromSeconds(int.Parse(CycleRequestCycle)); timerCycleAskData1.Tick += TimerCycleAskData1_Tick; timerCycleAskData1.Start(); } else { timerCycleAskData2.Interval = TimeSpan.FromSeconds(int.Parse(CycleRequestCycle)); timerCycleAskData2.Tick += TimerCycleAskData2_Tick; timerCycleAskData2.Start(); } string record = "周期请求升压站状态数据已开启,请求周期为:" + CycleRequestCycle; string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{station_id}','{DateTime.Now}','升压站电控通信系统','数据请求','{record}');"; DBHelper.ExecuteNonQuery(sql, 1); } else { //停止定时器 if (station_id == 1) { timerCycleAskData1.Stop(); } else { timerCycleAskData2.Stop(); } string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{station_id}','{DateTime.Now}','升压站电控通信系统','数据请求','周期请求升压站状态数据已关闭');"; DBHelper.ExecuteNonQuery(sql, 1); } } } private void TimerCycleAskData1_Tick(object sender, EventArgs e) { AskBoosterStationData(1); } private void TimerCycleAskData2_Tick(object sender, EventArgs e) { AskBoosterStationData(2); } 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) { AskBoosterStationData(station_id); } private void AskBoosterStationData(int id) { AskDataBtnIsEnabled = false; AskDataBtnIsReceived = false; //查询从设备寄存器内容 fromDeviceAddress = 0x01; //if (id == 1) //{ // deviceAddress = Convert.ToByte(Tools.GetAppSetting("DeviceAddress1")); // fromDeviceAddress = deviceAddress; //从设备地址 //} //else //{ // 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 (id == 1) { //if (comModel1.IsConnected) // result = comModel1.SendMessage(sendBytes.ToArray()); 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; } } else { //if (comModel2.IsConnected) // result = comModel2.SendMessage(sendBytes.ToArray()); if (MainWindow.mainViewModel.clientModel2.IsConnected) result = MainWindow.mainViewModel.clientModel2.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('{station_id}','{DateTime.Now}','升压站电控通信系统','数据请求','{AskDataMsg}');"; DBHelper.ExecuteNonQuery(sql, 1); } #endregion #region Refresh Data public void RefreshData(object o) { this.EndDateTime = DateTime.Now; this.StartDateTime = DateTime.Now.AddDays(-1); //设置当前页为1 PageIndex = 1; TotalBoosterStationStateDataList.Clear(); BoosterStationStateDataList.Clear(); var chartValuesTeam1 = new ChartValues(); var chartValuesTeam2 = new ChartValues(); string sql = String.Format("select RecordTime,In_Vol,In_Cur,Power,RelayStatus from boosterstation_state where StationID = {0} ORDER by id desc limit 100", station_id); MySqlDataReader dataReader = DBHelper.ExecuteReader(sql, 1); int index = 1; while (dataReader.Read()) { BoosterStationStateDataModel boosterStationStateDataModel = new BoosterStationStateDataModel(); boosterStationStateDataModel.Index = index++; boosterStationStateDataModel.RecordTime = Convert.ToDateTime(dataReader["RecordTime"]); boosterStationStateDataModel.In_Vol = Convert.ToSingle(string.IsNullOrEmpty(dataReader["In_Vol"].ToString()) ? "0.00" : dataReader["In_Vol"]); boosterStationStateDataModel.In_Cur = Convert.ToSingle(string.IsNullOrEmpty(dataReader["In_Cur"].ToString()) ? "0.00" : dataReader["In_Cur"]); boosterStationStateDataModel.Power = Convert.ToSingle(string.IsNullOrEmpty(dataReader["Power"].ToString()) ? "0.00" : dataReader["Power"]); if (dataReader["RelayStatus"].ToString() == "0") boosterStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("BoosterStationDeviceOn"); else boosterStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("BoosterStationDeviceOff"); TotalBoosterStationStateDataList.Add(boosterStationStateDataModel); if (!Convert.IsDBNull(boosterStationStateDataModel.In_Vol) && !Convert.IsDBNull(boosterStationStateDataModel.In_Cur)) { chartValuesTeam1.Add(new DateTimePoint { Value = Convert.ToSingle(dataReader["In_Vol"]), DateTime = Convert.ToDateTime(dataReader["RecordTime"]), }); chartValuesTeam2.Add(new DateTimePoint { Value = Convert.ToSingle(dataReader["In_Cur"]), DateTime = Convert.ToDateTime(dataReader["RecordTime"]), }); } } dataReader.Dispose(); RecordCount = index - 1; if (RecordCount <= 10) { TotalPage = 1; BoosterStationStateDataList = new ObservableCollection(); BoosterStationStateDataList = TotalBoosterStationStateDataList; } else { TotalPage = (int)Math.Ceiling((double)RecordCount / 10); BoosterStationStateDataList = new ObservableCollection(); for (int i = 0; i < 10; i++) { BoosterStationStateDataList.Add(TotalBoosterStationStateDataList[i]); } } BoosterStationStateTotalPage = TotalPage; BoosterStationStateNowPage = PageIndex; //sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{station_id}','{DateTime.Now}','升压站电控通信系统','数据刷新','刷新升压站状态数据');"; //DBHelper.ExecuteNonQuery(sql, 1); } #endregion #region DownloadData public void DownloadData(object o) { string boosterStationFolder = Tools.GetAppSetting("BoosterStationFolder"); string savePath = CSVDownload.CreateFile(boosterStationFolder, "BoosterStationStateData_" + DateTime.Now.ToString("yyyyMMddhhMMss"), "csv"); string DownloadDataMsg; bool result = CSVDownload.SaveBoosterStationDataToCSVFile(TotalBoosterStationStateDataList, savePath); if (result) { DownloadDataMsg = "下载数据成功!"; } else { DownloadDataMsg = "下载数据失败!"; } string record = "下载升压站状态数据," + DownloadDataMsg; string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{station_id}','{DateTime.Now}','升压站电控通信系统','数据下载','{record}');"; DBHelper.ExecuteNonQuery(sql, 1); } #endregion #region Page Switching public void ForwordBoosterStationState(object o) { if (PageIndex == 1) return; try { PageIndex -= 1; BoosterStationStateDataList.Clear(); for (int i = 0; i < 10; i++) { BoosterStationStateDataList.Add(TotalBoosterStationStateDataList[i + (PageIndex - 1) * 10]); } BoosterStationStateTotalPage = TotalPage; BoosterStationStateNowPage = PageIndex; } catch { TotalBoosterStationStateDataList.Clear(); BoosterStationStateDataList.Clear(); } } public void NextBoosterStationState(object o) { if (PageIndex == TotalPage) return; try { PageIndex += 1; BoosterStationStateDataList.Clear(); for (int i = 0; i < (PageIndex == TotalPage ? (RecordCount - (PageIndex - 1) * 10) : 10); i++) { BoosterStationStateDataList.Add(TotalBoosterStationStateDataList[i + (PageIndex - 1) * 10]); } BoosterStationStateTotalPage = TotalPage; BoosterStationStateNowPage = PageIndex; } catch { TotalBoosterStationStateDataList.Clear(); BoosterStationStateDataList.Clear(); } } #endregion #region SerachData public void SearchBoosterStationState(object o) { if (string.IsNullOrEmpty(EndDateTime.ToString()) || string.IsNullOrEmpty(StartDateTime.ToString())) { HandyControl.Controls.Dialog.Show(new TextDialog("请选择起始时间和结束时间!")); return; } if (EndDateTime < StartDateTime) { HandyControl.Controls.Dialog.Show(new TextDialog("起始时间大于结束时间,\n请重新输入!")); return; } string timeSearch = " and RecordTime BETWEEN '" + StartDateTime + "' and '" + EndDateTime + "' "; //设置当前页为1 PageIndex = 1; TotalBoosterStationStateDataList.Clear(); BoosterStationStateDataList.Clear(); var chartValuesTeam1 = new ChartValues(); var chartValuesTeam2 = new ChartValues(); string sql = String.Format("select RecordTime,In_Vol,In_Cur,Power,RelayStatus from boosterstation_state where StationID = {0} {1} ORDER by id desc limit 100", station_id, timeSearch); MySqlDataReader dataReader = DBHelper.ExecuteReader(sql, 1); int index = 1; while (dataReader.Read()) { BoosterStationStateDataModel boosterStationStateDataModel = new BoosterStationStateDataModel(); boosterStationStateDataModel.Index = index++; boosterStationStateDataModel.RecordTime = Convert.ToDateTime(dataReader["RecordTime"]); boosterStationStateDataModel.In_Vol = Convert.ToSingle(string.IsNullOrEmpty(dataReader["In_Vol"].ToString()) ? "0" : dataReader["In_Vol"]); boosterStationStateDataModel.In_Cur = Convert.ToSingle(string.IsNullOrEmpty(dataReader["In_Cur"].ToString()) ? "0" : dataReader["In_Cur"]); boosterStationStateDataModel.Power = Convert.ToSingle(string.IsNullOrEmpty(dataReader["Power"].ToString()) ? "0" : dataReader["Power"]); if (dataReader["RelayStatus"].ToString() == "0") boosterStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("BoosterStationDeviceOn"); else boosterStationStateDataModel.RelayStatus = (ImageSource)Application.Current.FindResource("BoosterStationDeviceOff"); TotalBoosterStationStateDataList.Add(boosterStationStateDataModel); if (!Convert.IsDBNull(dataReader["In_Vol"]) && !Convert.IsDBNull(dataReader["In_Cur"])) { chartValuesTeam1.Add(new DateTimePoint { Value = Convert.ToSingle(dataReader["In_Vol"]), DateTime = Convert.ToDateTime(dataReader["RecordTime"]), }); chartValuesTeam2.Add(new DateTimePoint { Value = Convert.ToSingle(dataReader["In_Cur"]), DateTime = Convert.ToDateTime(dataReader["RecordTime"]), }); } } dataReader.Dispose(); RecordCount = index - 1; if (RecordCount <= 10) { TotalPage = 1; BoosterStationStateDataList = new ObservableCollection(); BoosterStationStateDataList = TotalBoosterStationStateDataList; } else { TotalPage = (int)Math.Ceiling((double)RecordCount / 10); BoosterStationStateDataList = new ObservableCollection(); for (int i = 0; i < 10; i++) { BoosterStationStateDataList.Add(TotalBoosterStationStateDataList[i]); } } BoosterStationStateTotalPage = TotalPage; BoosterStationStateNowPage = PageIndex; string record = "查询升压站状态数据历史数据,查询时间范围为:" + StartDateTime + "至" + EndDateTime + ",共查询到" + RecordCount + "条历史数据"; sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{station_id}','{DateTime.Now}','升压站电控通信系统','数据查询','{record}');"; DBHelper.ExecuteNonQuery(sql, 1); } public void ResetSearch(object o) { RefreshData(null); } #endregion } }