jy-plc/Services/PingService.cs

90 lines
2.3 KiB
C#

using LangGuan.Command.Model.EntityModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
namespace LangGuan.Services
{
/// <summary>
/// ping service
/// </summary>
public class PingService
{
private DeviceSerive _deviceSerive;
/// <summary>
///
/// </summary>
/// <param name="deviceSerive"></param>
public PingService(DeviceSerive deviceSerive)
{
_deviceSerive = deviceSerive;
}
/// <summary>
///
/// </summary>
public void CreatTask()
{
//5分钟执行一次
Timer myTimer = new Timer(new TimerCallback(Execute), null, 2000, 300000);
// Timer myTimer = new Timer(new TimerCallback(Execute), "ping service", 2000, 10000);
}
/// <summary>
///
/// </summary>
/// <param name="b"></param>
public async void Execute(object b)
{
var deviceList = await _deviceSerive.GetAsync();
if (deviceList.Any())
{
foreach (var item in deviceList)
{
if (!string.IsNullOrEmpty(item.deviceIp))
{
var ip = item.deviceIp.Split(":")[0];
var res = await PingIp(ip);
item.state = res == true ? 1 : 0;
await _deviceSerive.UpdateState(item);
}
}
}
Console.WriteLine("{0} ping running.", (string)b);
}
/// <summary>
/// ping
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public async Task<bool> PingIp(string ip)
{
try
{
//Ping 实例对象;
Ping pingSender = new Ping();
PingReply pingReply = await pingSender.SendPingAsync(ip);
if (pingReply.Status == IPStatus.Success)
{
return true;
}
}
catch (Exception)
{
return false;
}
return false;
}
}
}