SafeNet/SafeNetLib/PingThread.cs
2021-02-24 13:50:23 +02:00

92 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.NetworkInformation;
namespace SafeNetLib
{
public class PingThread
{
string ip;
private int interval;
bool status;
private bool running = true;
/// <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;
}
public void Worker()
{
Utils.ConsWrite(DebugMSG_Type.ALL, "PingThread started for " + ip + " interval:" + interval);
while (running)
{
try
{
//DateTime time = DateTime.Now;
//SM.Debug(ip+" start ping");
Ping pingSender = new Ping();
PingReply pReply = pingSender.Send(ip, 5000);
if (pReply.Status == IPStatus.Success)
{
//if (status == false) //going from OFF->ON
{
OnNewPingComplete(true, ip);
//Utils.ConsWrite(DebugMSG_Type.DB, "****** OnNewPingComplete ** " + true + " *** " + ip);
}
status = true;
}
else //if (pReply.Status == IPStatus.TimedOut)
{
//if (status == true) //going from ON->OFF
{
OnNewPingComplete(false, ip);
//Utils.ConsWrite(DebugMSG_Type.DB, "****** OnNewPingComplete ** " + false + " *** " + ip);
}
status = false;
}
}
catch
{
Utils.ConsWrite(DebugMSG_Type.DB, "*** Could not ping: " + ip + " *****");
}
Thread.Sleep(interval * 1000);
}
}
/**
* Interrupt the ping worker
*/
public void StopPingWorker()
{
running = false;
}
/**
* Modify the interval at which Ping is tested
* @param seconds : number of seconds between ping requests
*/
public void SetPingWorkerFrequency(int seconds)
{
this.interval = seconds;
}
public delegate void NewPingCompleteDEl(bool status, string ip);
public event NewPingCompleteDEl OnNewPingComplete;
public delegate void RadioPingDEl(bool status, string ip);
public event RadioPingDEl OnRadioPing;
}
}