You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

726 lines
26 KiB
C#

using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Collections.ObjectModel;
using StartServerWPF.Modules.Main.Model;
using System.Windows.Media;
using System.Timers;
using System.Windows.Threading;
namespace StartServerWPF.Modules.Main.ViewModels
{
public class MainViewModel : BindableBase
{
public MainViewModel(IDialogService dialogService, WebsocketClient websocket)
{
Message = "View A from your Prism Module";
1 year ago
Console.WriteLine(System.Environment.CurrentDirectory + "\\" + JsonParser.systemConfigPath);
sc = JsonParser.ReadSystemJsonFile(JsonParser.systemConfigPath);
int moniTimeInd = sc.proMonitor.ProParams.IndexOf("-btime");
string moniTimeStr = sc.proMonitor.ProParams.Substring(moniTimeInd + 7);
int moniTimeIndEnd = moniTimeStr.IndexOf(">");
moniTimeStr = moniTimeStr.Substring(0, moniTimeIndEnd - 1);
MoniStartTime = DateTime.Parse(moniTimeStr);
InitializeParams();
JsonParser.UpdateApmsJson(sc.proApms.ProPath + "apms.json", sc.vpnInfo.DataSavePath);
JsonParser.UpdateRecvJson(sc.proRecv.ProPath + "gw.recvftp.json", sc.vpnInfo.DataSavePath);
sc.proMonitor.ProParams = JsonParser.CreateMonitorStartParam(sc.vpnInfo.DataSavePath, MoniStartTime);
StartTime = DateTime.Now;
// labelStartTime.Text = "启动时间:" + StartTime.ToString();
remDb = new MySqlHelper(sc.remoteDb);
Console.WriteLine(System.Environment.CurrentDirectory);
Console.WriteLine(sc.remoteDb.ServerAddress + "\t" + sc.remoteDb.ServerPort
+ "\t" + sc.remoteDb.UserName + "\t" + sc.remoteDb.Password);
this._dialogService = dialogService;
this._websocket = websocket;
_websocket.WebSocketInit();
}
#region 属性
private string _message;
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
private DateTime startTime;
private DateTime moniStartTime;
1 year ago
public DateTime StartTime { get => startTime; set => SetProperty(ref startTime, value); }
public DateTime MoniStartTime { get => moniStartTime; set => SetProperty(ref moniStartTime, value); }
private string runTime;
public string RunTime
{
get { return runTime; }
1 year ago
set { SetProperty(ref runTime, value); }
}
private string vPNStatus;
public string VPNStatus
{
get { return vPNStatus; }
1 year ago
set { SetProperty(ref vPNStatus, value);
}
}
private string vpnIP;
public string VpnIP
{
get { return vpnIP; }
1 year ago
set { SetProperty(ref vpnIP, value); }
}
private string vPNStatusForeColor;
public string VPNStatusForeColor
{
get { return vPNStatusForeColor; }
set { SetProperty(ref vPNStatusForeColor, value); }
}
1 year ago
private bool vPNIsConnect;
public bool VPNIsConnect
{
get { return vPNIsConnect; }
set { SetProperty(ref vPNIsConnect, value); }
}
private bool isIndeterminate=false;
1 year ago
public bool IsIndeterminate
{
get { return isIndeterminate; }
set { SetProperty(ref isIndeterminate, value); }
}
private ObservableCollection<string> reciveDataSource=new ObservableCollection<string>();
public ObservableCollection<string> ReciveDataSource
{
get { return reciveDataSource; }
set { reciveDataSource = value; }
}
private ObservableCollection<int> intervalTimesSource=new ObservableCollection<int>();
public ObservableCollection<int> IntervalTimesSource
{
get { return intervalTimesSource; }
set { intervalTimesSource = value; }
}
private int selectedIndex;
public int SelectedIndex
{
get { return selectedIndex; }
1 year ago
set { SetProperty(ref selectedIndex, value); }
}
private int proMonInterval = 10;
public int ProMonInterval { get => proMonInterval;
1 year ago
set => SetProperty(ref proMonInterval, value);
}
#endregion
#region 事件
public DelegateCommand LoadedCommand => new(Loaded);
public DelegateCommand UnloadedCommand => new(Unloaded);
public DelegateCommand ConnectVPNCommand => new(ConnectVPN);
public DelegateCommand DisConnectVPNCommand => new(DisConnectVPN);
public DelegateCommand GetVPNStatusCommand => new(GetVPNStatus);
public DelegateCommand SetVPNParaCommand => new(SetVPNPara);
public DelegateCommand DisplayLogCommand => new(DisplayLog);
public DelegateCommand OneKeyStartCommand => new(OneKeyStart);
public DelegateCommand OneKeyStopCommand => new(OneKeyStop);
public DelegateCommand DisplayRealWavesCommand => new(DisplayRealWaves);
public DelegateCommand QueryDataCommand => new(QueryData);
public DelegateCommand InsertDataCommand => new(InsertData);
private void Loaded()
{
IntilVPN();
SetControlstatus();
}
private void Unloaded()
{
KillProcess(sc.proServer);
KillProcess(sc.proRecv);
KillProcess(sc.proApms);
KillProcess(sc.proMonitor);
string logStr = DateTime.Now.ToString("s") + "\t程序关闭";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
//switch (kserindex)
//{
// case -1:
// Console.WriteLine(serProcInfo.ProName + "结束失败");
// break;
// case 0:
// Console.WriteLine(serProcInfo.ProName + "结束成功");
// break;
// case 1:
// Console.WriteLine(serProcInfo.ProName + "程序未启动");
// break;
//}
//int krecindex = KillProcess(recvProcInfo);
//switch (krecindex)
//{
// case -1:
// Console.WriteLine(recvProcInfo.ProName + "结束失败");
// break;
// case 0:
// Console.WriteLine(recvProcInfo.ProName + "结束成功");
// break;
// case 1:
// Console.WriteLine(recvProcInfo.ProName + "程序未启动");
// break;
//}
}
private void ConnectVPN()
{
vpn.CreateOrUpdateVPN(sc.vpnInfo.VpnName, sc.vpnInfo.VpnIP);
vpn.ConnectVPN(sc.vpnInfo.VpnName, sc.vpnInfo.VpnUserName, sc.vpnInfo.VpnPsw);
Thread.Sleep(1000);
string logStr = DateTime.Now.ToString("s") + "\tVPN手动连接";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
SetControlstatus();
}
private void DisConnectVPN()
{
if (MessageBox.Show("是否断开VPN连接", "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
{
vpn.DisConnectVPN(sc.vpnInfo.VpnName);
Thread.Sleep(500);
SetControlstatus();
Thread.Sleep(100);
string logStr = DateTime.Now.ToString("s") + "\tVPN手动断开";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
}
}
private void GetVPNStatus()
{
if (vpn.CheckVpnStatus(sc.vpnInfo.VpnName))
{
MessageBox.Show("VPN已经连接!");
}
else
{
MessageBox.Show("VPN断开连接!");
}
}
private void SetVPNPara()
{
//FormSetParam fvi = new FormSetParam();
//fvi.fm = this;
//fvi.ShowDialog();
DialogParameters param = new DialogParameters();
param.Add("type", 1);// 编辑
param.Add("model", sc);
param.Add("moniTime", MoniStartTime);
_dialogService.ShowDialog(
"SetParamDialog",
param,
new Action<IDialogResult>(result =>
{
if (result != null && result.Result == ButtonResult.OK)
{
MessageBox.Show("数据已保存", "提示");
}
}));
}
private void DisplayLog()
{
Process.Start("explorer.exe", sc.vpnInfo.SystemLogPath);
}
private void OneKeyStart()
{
StartTime = DateTime.Now;
sc.proServer.Pid = StartProcess(sc.proServer);
StartTime = DateTime.Now;
if (sc.proServer.Pid < 32)
{
ReciveDataSource.Add("服务器程序启动失败:" + StartTime.ToString());
}
Thread.Sleep(10);
sc.proRecv.Pid = StartProcess(sc.proRecv);
if (sc.proRecv.Pid < 32)
{
ReciveDataSource.Add("接收数据程序启动失败:" + StartTime.ToString());
}
Thread.Sleep(10);
sc.proApms.Pid = StartProcess(sc.proApms);
if (sc.proApms.Pid < 32)
{
ReciveDataSource.Add("自动识别程序启动失败:" + StartTime.ToString());
}
Thread.Sleep(10);
sc.proMonitor.Pid = StartProcess(sc.proMonitor);
Console.WriteLine(sc.proMonitor.Pid);
if (sc.proMonitor.Pid < 32)
{
ReciveDataSource.Add("网页服务程序启动失败:" + StartTime.ToString());
}
Thread.Sleep(10);
// labelStartTime.Text = "启动时间:" + StartTime.ToString();
RunTime = DateDiff(DateTime.Now, StartTime);
string logStr = StartTime.ToString("s") + "\t服务器程序启动";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
IsIndeterminate =true;
// btnSetParams.Enabled = false;
timer1.Interval = TimeSpan.FromSeconds(ProMonInterval);
timer1.Start();
timer1.Tick += timer1_Tick;
ReciveDataSource.Clear();
}
private void OneKeyStop()
{
int kserindex = KillProcess(sc.proServer);
if (kserindex > -1)
{
ReciveDataSource.Add(sc.proServer.ProName + "结束成功");
}
else
{
ReciveDataSource.Add(sc.proServer.ProName + "结束失败");
}
int krecindex = KillProcess(sc.proRecv);
if (kserindex > -1)
{
ReciveDataSource.Add(sc.proRecv.ProName + "结束成功");
}
else
{
ReciveDataSource.Add(sc.proRecv.ProName + "结束失败");
}
int kampsindex = KillProcess(sc.proApms);
if (kampsindex > -1)
{
ReciveDataSource.Add(sc.proApms.ProName + "结束成功");
}
else
{
ReciveDataSource.Add(sc.proApms.ProName + "结束失败");
}
int kmonitorindex = KillProcess(sc.proMonitor);
if (kmonitorindex > -1)
{
ReciveDataSource.Add(sc.proMonitor.ProName + "结束成功");
}
else
{
ReciveDataSource.Add(sc.proMonitor.ProName + "结束失败");
}
ReciveDataSource.Add("服务停止于:" + DateTime.Now.ToString());
timer1.Stop();
IsIndeterminate = false;
string logStr = DateTime.Now.ToString("s") + "\t服务器程序关闭";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
// labelStartTime.Text = "启动时间:";
StartTime = new DateTime();
// buttonOneKeyStart.Enabled = true;
// btnSetParams.Enabled = true;
}
private void DisplayRealWaves()
{
StartProcess(sc.proPlot);
}
private void QueryData()
{
string str = "2021-05-09T00:15:34.530406 -0.60000 -0.07969 0.6000 ML -3.05 14 13 0.048 ";
MsEvent me = new MsEvent(str);
// dataGridView1.DataSource = remDb.MySqlSelect("select ETime,X,Y,Z,ML,LocSta,MLSta,Rms from " + sc.remoteDb.TableName).Tables[sc.remoteDb.TableName];
}
private void InsertData()
{
string str = "2021-05-09T00:15:34.900406 -0.60000 -0.07969 0.6000 ML -3.05 14 13 0.048 ";
MsEvent me = new MsEvent(str);
bool insStat = remDb.InsertEvent(me);
if (insStat)
{
Console.WriteLine("新增成功");
}
else
{
Console.WriteLine("已有该记录");
}
// dataGridView1.DataSource = remDb.MySqlSelect("select ETime,X,Y,Z,ML,LocSta,MLSta,Rms from " + sc.remoteDb.TableName).Tables[sc.remoteDb.TableName];
}
//private void button1_Click(object sender, EventArgs e)
//{
// vpn.ConnectVPN(sc.vpnInfo.VpnName, sc.vpnInfo.VpnUserName, sc.vpnInfo.VpnPsw);
// Thread.Sleep(1000);
// string logStr = DateTime.Now.ToString("s") + "\tVPN手动连接";
// WriteSerLog(sc.SystemLogPath + systemLogFileName, logStr);
// SetControlstatus();
//}
//private void button1_Click_1(object sender, EventArgs e)
//{
// JsonParser.WriteSystemConfigFile("SystemConfig.json", sc);
//}
//private void button2_Click(object sender, EventArgs e)
//{
// ProcessStartInfo processStartInfo = new ProcessStartInfo(@"F:\Project\2021\河南理工\余吾预警项目\郑老师程序\v20210415\All\server.exe", "service.conf");
// processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
// Process proc = Process.Start(processStartInfo);
// ProcessStartInfo processStartInfoRec = new ProcessStartInfo(@"F:\Project\2021\河南理工\余吾预警项目\郑老师程序\v20210415\All\gw.recvftp.exe", "-cfg gw.recvftp.json >outRecv.txt");
// processStartInfoRec.WindowStyle = ProcessWindowStyle.Normal;
// Process procRec = Process.Start(processStartInfoRec);
//}
#endregion
private void ConnectVpn()
{
// 系统路径 C:\windows\system32\
string WinDir = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) + @"";
Console.WriteLine(WinDir);
// rasdial.exe
string RasDialFileName = "rasdial.exe";
// VPN路径 C:\windows\system32\rasdial.exe
string VPNPROCESS = WinDir + "\\" + RasDialFileName;
// VPN地址
//string IPToPing = "49.232.209.49";
// VPN名称
string VPNName = "余吾手动";
// VPN用户名
string UserName = "lzvpn";
// VPN密码
string PassWord = "Lz123456789";
string args = string.Format("{0} {1} {2}", VPNName, UserName, PassWord);
ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS, args);
myProcess.CreateNoWindow = true;
myProcess.UseShellExecute = false;
Process.Start(myProcess);
}
private void IntilVPN()
{
vpn = new VPNHelper(sc.vpnInfo.VpnName, sc.vpnInfo.VpnIP, sc.vpnInfo.VpnUserName, sc.vpnInfo.VpnPsw);
}
[DllImport("shell32.dll")]
public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
public VPNHelper vpn;
public bool vpnStatus = false;
public SystemConfig sc;
MySqlHelper remDb;
private DispatcherTimer timer1= new DispatcherTimer();
private readonly IDialogService _dialogService;
private readonly WebsocketClient _websocket;
public void InitializeParams()
{
timer1.Interval = TimeSpan.FromSeconds(ProMonInterval);
1 year ago
this.Message = "服务器版本:" + JsonParser.serverVision;
IntervalTimesSource.Add(5);
IntervalTimesSource.Add(10);
IntervalTimesSource.Add(15);
IntervalTimesSource.Add(20);
IntervalTimesSource.Add(30);
IntervalTimesSource.Add(60);
SelectedIndex = 1;
1 year ago
JsonParser.systemLogFileName = "SerLog_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
string logStr = DateTime.Now.ToString("s") + "\t程序启动";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
//CheckIp();
}
#region 方法
/// <summary>
/// 启动进程
/// </summary>
/// <param name="proInfo"></param>
/// <returns>进程启动返回值</returns>
private int StartProcess(ProcessInfo proInfo)
{
//using (Process compiler = new Process())
//{
// compiler.StartInfo.FileName = proInfo.ProName;
// compiler.StartInfo.Arguments = proInfo.ProPath + " -o " + proInfo.ProParams;
// compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// compiler.Start();
// compiler.WaitForExit();
//}
int seInd = ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder(proInfo.ProName + ".exe")
, new StringBuilder(proInfo.ProParams), new StringBuilder(proInfo.ProPath), proInfo.ShowState);
return seInd;
}
/// <summary>
/// 结束进程
/// </summary>
/// <param name="processInfo"></param>
/// <returns>0=成功;1=未找到进程;-1=失败</returns>
private int KillProcess(ProcessInfo processInfo)
{
int ri = 0;
if (processInfo != null)
{
if (processInfo.ProName != null)
{
try
{
Process[] localByName = Process.GetProcessesByName(processInfo.ProName);
if (localByName.Length == 0)
{
ri = 1;
return ri;
}
foreach (var item in localByName)
{
Console.WriteLine(item.Id);
item.Kill();
}
return ri;
}
catch (Exception)
{
return -1;
}
}
else
{
return 0;
}
}
else
{
return 0;
}
}
/// <summary>
/// 查找进程
/// </summary>
/// <param name="processInfo"></param>
/// <returns>0=正在运行;1=未运行;-1=系统错误</returns>
private int FindProcess(ProcessInfo processInfo)
{
int ri = 0;
try
{
Process[] localByName = Process.GetProcessesByName(processInfo.ProName);
if (localByName.Length == 0)
{
ri = 1;
return ri;
}
return ri;
}
catch (Exception)
{
return -1;
}
}
private string DateDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new
TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
if (ts.Days > 0)
{
dateDiff += ts.Days.ToString() + "天";
}
if (ts.Hours > 0)
{
dateDiff += ts.Hours.ToString() + "小时";
}
if (ts.Minutes > 0)
{
dateDiff += ts.Minutes.ToString() + "分钟";
}
dateDiff += ts.Seconds.ToString() + "秒";
return dateDiff;
}
private void timer1_Tick(object? sender, EventArgs e)
{
ReciveDataSource.Clear();
ReciveDataSource.Add(DateTime.Now.ToString());
int sfp = FindProcess(sc.proServer);
if (sfp == 0)
{
ReciveDataSource.Add("服务器程序运行正常");
}
else
{
ReciveDataSource.Add("服务器程序未运行");
Thread.Sleep(2);
StartProcess(sc.proServer);
Thread.Sleep(20);
ReciveDataSource.Add("服务器程序重启成功");
string logStr = DateTime.Now.ToString("s") + "\t服务器程序" + sc.proServer.ProName + "重启";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
}
sfp = FindProcess(sc.proRecv);
if (sfp == 0)
{
ReciveDataSource.Add("接收数据程序运行正常");
}
else
{
ReciveDataSource.Add("接收数据程序未运行");
Thread.Sleep(2);
StartProcess(sc.proRecv);
Thread.Sleep(20);
ReciveDataSource.Add("接收数据程序重启成功");
string logStr = DateTime.Now.ToString("s") + "\t接收数据程序" + sc.proRecv.ProName + "重启";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
}
sfp = FindProcess(sc.proApms);
if (sfp == 0)
{
ReciveDataSource.Add("自动识别程序运行正常");
}
else
{
ReciveDataSource.Add("自动识别程序未运行");
Thread.Sleep(2);
StartProcess(sc.proApms);
Thread.Sleep(20);
ReciveDataSource.Add("自动识别程序重启成功");
string logStr = DateTime.Now.ToString("s") + "\t自动识别程序" + sc.proApms.ProName + "重启";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
}
sfp = FindProcess(sc.proMonitor);
if (sfp == 0)
{
ReciveDataSource.Add("网页服务程序运行正常");
}
else
{
ReciveDataSource.Add("网页服务程序未运行");
Thread.Sleep(2);
StartProcess(sc.proMonitor);
Thread.Sleep(20);
ReciveDataSource.Add("网页服务程序重启成功");
string logStr = DateTime.Now.ToString("s") + "\t网页服务程序" + sc.proMonitor.ProName + "重启";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
}
RunTime = DateDiff(DateTime.Now, StartTime);
vpnStatus = vpn.CheckVpnStatus(sc.vpnInfo.VpnName);
if (!vpnStatus)
{
vpn.ConnectVPN(sc.vpnInfo.VpnName, sc.vpnInfo.VpnUserName, sc.vpnInfo.VpnPsw);
Thread.Sleep(1000);
string logStr = DateTime.Now.ToString("s") + "\tVPN断开重连";
1 year ago
WriteSerLog(sc.vpnInfo.SystemLogPath + JsonParser.systemLogFileName, logStr);
}
}
public void GetLocalIp()
{
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
if (AddressIP.Contains("172.16"))
{
sc.vpnInfo.VpnIP = AddressIP;
}
}
}
//return AddressIP;
}
public void SetControlstatus()
{
vpnStatus = vpn.CheckVpnStatus(sc.vpnInfo.VpnName);
if (vpnStatus)
{
//gbServerControl.Enabled = true;
1 year ago
// buttonConnectVPN.Enabled = false;
1 year ago
// buttonDisconnectVPN.Enabled = true;
// labelVPNstatus.ForeColor = Color.Blue;
VPNIsConnect = true;
VPNStatusForeColor = "#FF008000";
VPNStatus = "VPN已连接";
1 year ago
VpnIP = vpn.GetLocalIp();
}
else
{
1 year ago
// gbServerControl.Enabled = false;
// buttonConnectVPN.Enabled = true;
1 year ago
// buttonDisconnectVPN.Enabled = false;
// labelVPNstatus.ForeColor = Color.Red;
VPNIsConnect = false;
VPNStatusForeColor = "#FFFF0000";
VPNStatus = "VPN断开连接";
}
}
public void WriteSerLog(string fn, string logstr)
{
if(!File.Exists(fn))
{
Directory.CreateDirectory(Path.GetDirectoryName(fn));
}
StreamWriter sw = new StreamWriter(fn, true, Encoding.Default);
sw.WriteLine(logstr);
sw.Close();
}
#endregion
}
}