Files
New-version-HME-moisture-lo…/Services/MesHttpService.cs

111 lines
3.5 KiB
C#
Raw Normal View History

2026-06-17 15:04:35 +08:00
using HME_MoistureLossMeter.Models;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Serilog;
namespace HME_MoistureLossMeter.Services
{
public class MesHttpService : IMesService
{
private readonly HttpClient _httpClient;
private readonly MesConfiguration _config;
public MesHttpService(HttpClient httpClient, MesConfiguration config)
{
_httpClient = httpClient;
_config = config;
if (!string.IsNullOrEmpty(_config.ApiKey))
{
_httpClient.DefaultRequestHeaders.Add("X-API-Key", _config.ApiKey);
}
}
public async Task<bool> SendRealtimeDataAsync(RealtimeDataModel data)
{
try
{
var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/hme/realtime", content);
if (!response.IsSuccessStatusCode)
{
Log.Warning("发送实时数据失败: {StatusCode}, {Reason}",
response.StatusCode, response.ReasonPhrase);
return false;
}
return true;
}
catch (Exception ex)
{
Log.Error(ex, "发送实时数据异常");
return false;
}
}
public async Task<bool> SendTestResultAsync(TestResultModel result)
{
try
{
var json = JsonConvert.SerializeObject(result, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/hme/test-result", content);
if (!response.IsSuccessStatusCode)
{
Log.Warning("发送测试结果失败: {StatusCode}, {Reason}",
response.StatusCode, response.ReasonPhrase);
return false;
}
return true;
}
catch (Exception ex)
{
Log.Error(ex, "发送测试结果异常");
return false;
}
}
public async Task<bool> SendHistoryDataAsync(HistoryDataModel history)
{
try
{
var json = JsonConvert.SerializeObject(history, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/hme/history", content);
if (!response.IsSuccessStatusCode)
{
Log.Warning("发送历史数据失败: {StatusCode}, {Reason}",
response.StatusCode, response.ReasonPhrase);
return false;
}
return true;
}
catch (Exception ex)
{
Log.Error(ex, "发送历史数据异常");
return false;
}
}
}
}