You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/IoT/IoT.Shared/Infrastructure/DeviceService.cs

61 lines
1.9 KiB

using Infrastructure.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace IoT.Shared.Infrastructure
{
public abstract class DeviceService : IHostedService
{
internal readonly IServiceProvider _applicationServices;
internal readonly IConfiguration _configuration;
public DeviceService(IServiceProvider applicationServices, IConfiguration configuration)
{
this._applicationServices = applicationServices;
this._configuration = configuration;
}
public virtual Task StartAsync(CancellationToken cancellationToken)
{
Task.Run(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
Execute();
}
catch (Exception ex)
{
ex.PrintStack();
}
await Task.Delay(_configuration.GetValue("timer.seconds", 60) * 1000).ConfigureAwait(true);
}
});
return Task.CompletedTask;
}
public abstract void Execute();
public virtual Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public void SendToServer(string method, object data)
{
Console.WriteLine("send device to server");
using var scope = _applicationServices.CreateScope();
var clientService = scope.ServiceProvider.GetService<NodeService>();
clientService.SendToServer(method, data);
}
}
}