SafeDispatch/ServiceGatewaySDR/PingThread.cs

79 lines
2.7 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using SafeMobileLib;
using SDRGatewayService.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SDRGatewayService
{
class PingThread
{
string ip;
private int interval;
bool status;
private Thread t_Ping;
/// <summary>
/// ping class
/// </summary>
/// <param name="ip">dest IP</param>
/// <param name="interval">interval for pings in seconds</param>
public PingThread(string ip, int interval)
{
this.ip = ip;
this.interval = interval;
status = false;
t_Ping = new Thread(new ThreadStart(Worker));
t_Ping.IsBackground = true;
t_Ping.Start();
}
public void Worker()
{
Utils.WriteEventLog(Program.COMPANY, String.Format("PingThread started for " + ip + " interval:" + interval), EventLogEntryType.Information, (int)EventId.EVENT_PING);
int count = 0;
while (true)
{
try
{
Thread.Sleep(ConfigHelper.SdrPing * 1000);
DateTime time = DateTime.Now;
//SM.Debug(ip + " ping sent!");
Ping pingSender = new Ping();
PingReply pReply = pingSender.Send(ip);
if (pReply.Status == IPStatus.Success)
{
if (status == false) //going from OFF->ON
OnNewPingComplete(true, ip);
status = true;
}
else //if (pReply.Status == IPStatus.TimedOut)
{
if (status == true) //going from ON->OFF
OnNewPingComplete(false, ip);
status = false;
}
if (count++ % 10 == 0)
Utils.WriteEventLog(Program.COMPANY, String.Format("Gateway {0} is {1}", ip, (status ? "ONLINE" : "OFFLINE")), EventLogEntryType.Information, (int)EventId.EVENT_PING);
//SM.Debug(ip + " ping delta:" + (DateTime.Now -time) + " status:" + status);
}
catch
{
Utils.WriteEventLog(Program.COMPANY, String.Format("***Could not ping: " +ip+" ***"), EventLogEntryType.Information, (int)EventId.EVENT_PING);
}
Thread.Sleep(interval);
}
}
public delegate void NewPingCompleteDEl(bool status, string ip);
public event NewPingCompleteDEl OnNewPingComplete;
}
}