using MyFrontCodeTest.Models;
using MyFrontCodeTest.Models.PLC;
using MyFrontCodeTest.Service;
using System.Net.Http;
using System.Text.Json;
namespace MyFrontCodeTest.Utils
{
public class StartupInitializationService : IHostedService
{
private readonly MyS7Entry myS7Entry;
private readonly IS7ConnService s7ConnService;
private readonly ILogger<StartupInitializationService> logger;
private readonly HttpClient httpClient;
public StartupInitializationService(MyS7Entry myS7Entry
, IS7ConnService s7ConnService
, IHttpClientFactory httpClientFactory
, ILogger<StartupInitializationService> logger
)
{
this.myS7Entry = myS7Entry;
this.s7ConnService = s7ConnService;
this.logger = logger;
this.httpClient = httpClientFactory.CreateClient();
}
public Task StartAsync(CancellationToken cancellationToken)
{
logger.LogWarning("初始化函数成功");
myS7Entry.PropertyChanged += async (s, e) =>
{
if (e.PropertyName == "MyBool1")
{
string? url = "http://127.0.0.1:8881/endpoint/mes/kx/reportA";
Student stu = new()
{
Id = 1,
Name = "MyBool1",
Age = 999
};
var json = JsonSerializer.Serialize(stu);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
logger.LogInformation("Data sent successfullyS1.");
}
else
{
logger.LogInformation("Failed to send dataS1.");
}
}
if (e.PropertyName == "MyShort2")
{
}
};
return Task.CompletedTask;
}
private void MyS7Entry_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "MyBool1")
{
}
if (e.PropertyName == "MyBool2")
{
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
builder.Services.AddHttpClient("testClient", (client) =>
{
client.BaseAddress = new Uri("http://127.0.0.1:8889");
});