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 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 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 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; } } } }