SafeDispatch/MotoTrbo_GW/PingClass.cs

85 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using SafeMobileLib;
namespace MotoTrbo_GW
{
class PingClass
{
string ip;
private Ping pingSender;
private bool isAlive;
System.Threading.Timer timer;
private int interval;
public bool IsAlive
{
get { return isAlive; }
//set { isAlive = value; }
}
/// <summary>
/// ping class
/// </summary>
/// <param name="ip">dest IP</param>
/// <param name="interval">interval for pings in seconds</param>
public PingClass(string ip, int interval)
{
this.ip = ip;
this.interval = interval;
pingSender = new Ping();
}
public void Start()
{
SafeMobileLib.Utils.WriteLine("Starting ping thread for :" +ip +" interval(secs) :"+interval);
timer = new System.Threading.Timer(timerDel, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, interval));
}
public void Stop()
{
timer = null;
}
private void timerDel(Object state)
{
try
{
PingReply pReply = pingSender.Send(ip);
//SafeMobileLib.Utils.WriteLine("Status: "+pReply.Status+" IP: "+ip);
if (pReply.Status == IPStatus.Success)
{
//SafeMobileLib.Utils.WriteLine("Ping for " + ip + " return successfuly!!! " +DateTime.Now.ToString());
isAlive = true;
}
else
{
//SafeMobileLib.Utils.WriteLine("Host " + ip + " could not be reached!!!" + DateTime.Now.ToString());
isAlive = false;
}
if (this.OnPingComplete != null)
{
this.OnPingComplete(isAlive);
}
if (this.OnNewPingComplete != null)
{
this.OnNewPingComplete(isAlive, ip);
}
}
catch (Exception e)
{
SafeMobileLib.Utils.WriteLine("Ping exception " + ip);
}
}
public delegate void PingCompleteDEl(bool status);
public event PingCompleteDEl OnPingComplete;
public delegate void NewPingCompleteDEl(bool status,string ip);
public event NewPingCompleteDEl OnNewPingComplete;
}
}