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/BaseDeviceService.cs

102 lines
3.5 KiB

using Infrastructure.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
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 BaseDeviceService : IDeviceService
{
internal readonly IServiceProvider _applicationServices;
internal readonly IConfiguration _configuration;
internal CancellationTokenSource _tokenSource;
public BaseDeviceService(IServiceProvider applicationServices, IConfiguration configuration)
{
this._applicationServices = applicationServices;
this._configuration = configuration;
this._tokenSource = new CancellationTokenSource();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<挂起>")]
public virtual void Start()
{
Task.Run(async () =>
{
while (!_tokenSource.IsCancellationRequested)
{
try
{
Execute();
}
catch (Exception ex)
{
ex.PrintStack();
}
await Task.Delay(_configuration.GetValue("timer.seconds", 60) * 1000).ConfigureAwait(true);
}
});
}
public virtual void Execute()
{
}
public virtual void Stop()
{
}
public virtual void Dispose()
{
this._tokenSource.Cancel();
this.Stop();
this._tokenSource.Dispose();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")]
public string GetApiJson(string prefix)
{
try
{
using var scope = _applicationServices.CreateScope();
var serviceProvider = scope.ServiceProvider;
var cfg = serviceProvider.GetService<IConfiguration>();
var port = cfg["server.urls"].Split(':')[2];
var url = $"http://localhost:{port}/swagger/v1/swagger.json";
var hc = serviceProvider.GetService<IHttpClientFactory>().CreateClient();
var result = hc.GetStringAsync(url).Result;
var json = JsonConvert.DeserializeObject(result) as JObject;
var paths = json.Properties().FirstOrDefault(o => o.Name == "paths").Value as JObject;
var names = paths.Properties().Select(o => o.Name).ToList();
foreach (var item in names)
{
if (!item.StartsWith(prefix))
{
paths.Remove(item);
}
}
var realResult = JsonConvert.SerializeObject(json);
return realResult;
}
catch (Exception ex)
{
ex.PrintStack();
return null;
}
}
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);
}
}
}