Files
IOT/DeviceCommand/Base/EnovaDataReporter.cs
2026-06-09 15:54:50 +08:00

81 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Model.Model;
using Newtonsoft.Json;
namespace DeviceCommand.Base
{
public class EnovaDataReporter : IEnovaDataReporter
{
private readonly HttpClient _httpClient;
// 显式实现/自动属性,方便外部随时更新配置
public string TargetUrl { get; set; } = "http://127.0.0.1:8080/api/channel/state";
public int TimeoutMilliseconds { get; set; } = 5000;
/// <summary>
/// 构造函数注入 HttpClient符合 Prism 依赖注入规范)
/// </summary>
public EnovaDataReporter(HttpClient httpClient)
{
// 如果容器没有注入,则给个默认的单例/实例防空
_httpClient = httpClient ?? new HttpClient();
}
public async Task<EnovaReportResponse> ReportChannelStateAsync(List<EnovaChannelReportData> dataList, CancellationToken ct = default)
{
if (dataList == null || dataList.Count == 0)
{
return new EnovaReportResponse { Success = false, ErrorInfo = "上报数据集合为空" };
}
if (string.IsNullOrWhiteSpace(TargetUrl))
{
return new EnovaReportResponse { Success = false, ErrorInfo = "目标上报 URL 未配置" };
}
try
{
// 1. 序列化为标准 JSON 字符串
string jsonPayload = JsonConvert.SerializeObject(dataList);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 2. 绑定联动超时控制
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
if (TimeoutMilliseconds > 0)
{
cts.CancelAfter(TimeoutMilliseconds);
}
HttpResponseMessage response = await _httpClient.PostAsync(TargetUrl, content, cts.Token);
// 4. 解析返回值
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<EnovaReportResponse>(responseContent);
return result ?? new EnovaReportResponse { Success = true }; // 防止对方返回空Body [cite: 261]
}
else
{
return new EnovaReportResponse
{
Success = false,
ErrorInfo = $"服务器响应错误代码: {(int)response.StatusCode} {response.ReasonPhrase}"
};
}
}
catch (Exception ex)
{
// 完美承接你上位机原有的异常日志记录器逻辑
// Logger.LoggerHelper.ErrorWithNotify($"Enova3 数据上传失败: {ex.Message}");
return new EnovaReportResponse { Success = false, ErrorInfo = $"网络异常: {ex.Message}" };
}
}
}
}