设备基础命令
This commit is contained in:
81
DeviceCommand/Base/EnovaDataReporter.cs
Normal file
81
DeviceCommand/Base/EnovaDataReporter.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
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}" };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user