20240301_JSEQ_upperpc/JiangsuEarthquakeNowUI/JiangsuEarthquake/Models/ClientModel.cs
2024-11-01 15:54:08 +08:00

312 lines
13 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 JiangsuEarthquake.Common;
using JiangsuEarthquake.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JiangsuEarthquake.Models
{
public class ClientModel : NotifyBase
{
SocketInfo SI = new SocketInfo();
//升压站数据解析
private VolCurCollectorModel volCurCollectorModel { get; set; } = new VolCurCollectorModel();
private ZSWLModel zSWLModel { get; set; } = new ZSWLModel();
////地震仪数据解析
//private SeismographModel seismographModel { get; set; } = new SeismographModel();
public SocketHelper.TcpClients client { set; get; } = new SocketHelper.TcpClients();
private bool isConnected;
/// <summary>
/// Socket通信是否连接
/// </summary>
public bool IsConnected
{
get { return isConnected; }
set { isConnected = value; this.DoNotify(); }
}
/// <summary>
/// 打开客户端连接
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <returns></returns>
public bool DoConnect(SocketInfo socketInfo)
{
//if (!tools.TelnetPort(socketInfo.IP, socketInfo.Port))
// return false;
SI.IP = socketInfo.IP;
SI.Port = socketInfo.Port;
int id;
if (SI.Port == int.Parse(Tools.GetAppSetting("SYZ_Client_Port1")) || SI.Port == int.Parse(Tools.GetAppSetting("ZSWL_Client_Port1")))
id = 1;
else
id = 2;
client.InitSocket(socketInfo.IP, socketInfo.Port); //初始化设备的IP和端口号
IsConnected = client.Start();
if (IsConnected)
{
client.pushSockets = ReceiveMess;
//SocketHelper.pushSockets = new SocketHelper.PushSockets(ReceiveMess);
//tools.Logging("连接客户端成功,IP:" + socketInfo.IP + "端口号:" + socketInfo.Port);
Console.WriteLine("Client连接客户端成功IP" + socketInfo.IP + "端口号:" + socketInfo.Port);
//string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','{"连接客户端成功了IP" + socketInfo.IP + ";端口号:" + socketInfo.Port}');";
//DBHelper.ExecuteNonQuery(sql, 1);
//开始进行心跳包检查
//将是否接收到心跳包判断位 置于false
IsReturnMsg = System.DateTime.Now;
//检测当前连接状态
CheckConnect();
}
else
{
//tools.Logging("连接客户端失败,IP:" + socketInfo.IP + "端口号:" + socketInfo.Port);
Console.WriteLine("Client连接客户端失败IP" + socketInfo.IP + "端口号:" + socketInfo.Port);
//string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','{"连接客户端失败IP" + socketInfo.IP + ";端口号:" + socketInfo.Port}');";
//DBHelper.ExecuteNonQuery(sql, 1);
}
return IsConnected;
}
public bool DisConnect()
{
client.Stop();
IsConnected = false;
return IsConnected;
}
private void ReceiveMess(SocketHelper.Sockets sks)
{
int id;
if (SI.Port == int.Parse(Tools.GetAppSetting("SYZ_Client_Port1")) || SI.Port == int.Parse(Tools.GetAppSetting("ZSWL_Client_Port1")))
id = 1;
else
id = 2;
if (sks.ex != null)
{
if (sks.ClientDispose == true)
{
//由于未知原因引发异常.导致客户端下线. 比如网络故障.或服务器断开连接.
//SetClientState(string.Format("客户端下线.!异常消息:{0}\r\n", sks.ex));
Console.WriteLine("Client ReceiveMess Error" + string.Format("客户端下线.!异常消息:{0}\r\n", sks.ex));
//string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','{string.Format("客户端下线!异常消息:{0}\r\n", sks.ex)}');";
//DBHelper.ExecuteNonQuery(sql, 1);
IsConnected = false;
client.Stop();
}
}
else if (sks.Offset == 0)
{
//客户端主动下线
// SetClientState("客户端下线.!");
Console.WriteLine("Client ReceiveMess Error客户端主动下线");
//string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','客户端下线!');";
//DBHelper.ExecuteNonQuery(sql, 1);
IsConnected = false;
client.Stop();
}
else
{
byte[] buffer = new byte[sks.Offset];
Array.Copy(sks.RecBuffer, buffer, sks.Offset);
try
{
int stationName = 0;
if (SI.IP == Tools.GetAppSetting("SYZ_Client_IP1") && SI.Port == int.Parse(Tools.GetAppSetting("SYZ_Client_Port1")))
{
stationName = 1;
volCurCollectorModel.ParsingData(new List<byte>(buffer), stationName);
}
else if (SI.IP == Tools.GetAppSetting("SYZ_Client_IP2") && SI.Port == int.Parse(Tools.GetAppSetting("SYZ_Client_Port2")))
{
stationName = 2;
volCurCollectorModel.ParsingData(new List<byte>(buffer), stationName);
}
else if (SI.IP == Tools.GetAppSetting("ZSWL_Client_IP1") && SI.Port == int.Parse(Tools.GetAppSetting("ZSWL_Client_Port1")))
{
stationName = 1;
zSWLModel.ParsingData(new List<byte>(buffer), stationName);
}
else if (SI.IP == Tools.GetAppSetting("ZSWL_Client_IP2") && SI.Port == int.Parse(Tools.GetAppSetting("ZSWL_Client_Port2")))
{
stationName = 2;
zSWLModel.ParsingData(new List<byte>(buffer), stationName);
}
//else if (SI.IP == Tools.GetAppSetting("MainSeis_Client_IP1") && SI.Port == int.Parse(Tools.GetAppSetting("MainSeis_Client_Port1")))
//{
// stationName = 1;
// seismographModel.ParsingData(new List<byte>(buffer), stationName, true);
//}
//else if (SI.IP == Tools.GetAppSetting("MainSeis_Client_IP2") && SI.Port == int.Parse(Tools.GetAppSetting("MainSeis_Client_Port2")))
//{
// stationName = 2;
// seismographModel.ParsingData(new List<byte>(buffer), stationName, true);
//}
//else if (SI.IP == Tools.GetAppSetting("BackupSeis_Client_IP1") && SI.Port == int.Parse(Tools.GetAppSetting("BackupSeis_Client_Port1")))
//{
// stationName = 1;
// seismographModel.ParsingData(new List<byte>(buffer), stationName, false);
//}
//else if (SI.IP == Tools.GetAppSetting("BackupSeis_Client_IP2") && SI.Port == int.Parse(Tools.GetAppSetting("BackupSeis_Client_Port2")))
//{
// stationName = 2;
// seismographModel.ParsingData(new List<byte>(buffer), stationName, false);
//}
}
catch (Exception ex)
{
Console.WriteLine("Client ReceiveMess Error" + ex.ToString());
return;
}
}
}
/// <summary>
/// 发送消息
/// </summary>
public bool SendMessage(byte[] SendData)
{
try
{
client.SendData(SendData);
return true;
}
catch(Exception ex)
{
Console.WriteLine("Client SendMessage Error" + ex.ToString());
return false;
}
}
//用于记录心跳包的返回时间
public DateTime IsReturnMsg = System.DateTime.Now;
//用于记录当前是否在检查连接状态 初始值为false
bool IsCheckConnect = false;
/// <summary>
/// 用于检查当前连接状态
/// </summary>
private async void CheckConnect()
{
int id;
if (SI.Port == int.Parse(Tools.GetAppSetting("SYZ_Client_Port1")) || SI.Port == int.Parse(Tools.GetAppSetting("ZSWL_Client_Port1")))
id = 1;
else
id = 2;
await Task.Run(() =>
{
//将检查连接状态置为开
IsCheckConnect = true;
//连接成功等待10秒后 发送心跳包
Thread.Sleep(10000);
//tools.Logging("开始发送心跳包");
Console.WriteLine("Client开始发送心跳包");
//string sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','客户端下线!');";
//DBHelper.ExecuteNonQuery(sql, 1);
while ((System.DateTime.Now - IsReturnMsg).TotalSeconds < 150)
{
//发送一次Get
SendMessage(new byte[] { (byte)'G', (byte)'E', (byte)'T' });
//tools.Logging("发送一次心跳包GET,上一次收到心跳包的时间差为" + (System.DateTime.Now - IsReturnMsg).TotalSeconds + "秒");
Console.WriteLine("Client发送一次心跳包GET,上一次收到心跳包的时间差为" + (System.DateTime.Now - IsReturnMsg).TotalSeconds + "秒");
//等待30秒钟
Thread.Sleep(30000);
}
//tools.Logging("心跳包超时主动断开链接停止发送心跳包GET");
Console.WriteLine("Client心跳包超时主动断开链接停止发送心跳包GET");
//sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','心跳包超时主动断开链接停止发送心跳包GET');";
//DBHelper.ExecuteNonQuery(sql, 1);
//先断开链接
DisConnect();
IsConnected = false;
//等待2秒钟
Thread.Sleep(2000);
//tools.Logging("心跳包超时,开始初始化并重新链接!");
Console.WriteLine("Client心跳包超时开始初始化并重新链接");
//重新链接
while (!DoConnect(SI))
{
//tools.Logging("心跳包超时,重新链接失败!");
Console.WriteLine("Client心跳包超时重新链接失败");
//sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','心跳包超时,重新链接失败!');";
//DBHelper.ExecuteNonQuery(sql, 1);
Thread.Sleep(30000);
IsConnected = false;
}
//tools.Logging("心跳包超时,重新链接成功!");
Console.WriteLine("Client心跳包超时重新链接成功");
//sql = $"insert into log_record(StationID,RecordTime,Device_Name,Operation_Type,Record) values('{id}','{DateTime.Now}','升压站电控通信系统','通信连接','心跳包超时,重新链接成功!');";
//DBHelper.ExecuteNonQuery(sql, 1);
IsConnected = true;
});
}
}
public class SocketInfo : NotifyBase
{
private string ip;
/// <summary>
/// IP
/// </summary>
public string IP
{
get { return ip; }
set { ip = value; this.DoNotify(); }
}
private int port;
/// <summary>
/// 端口号
/// </summary>
public int Port
{
get { return port; }
set { port = value; this.DoNotify(); }
}
}
}