114 lines
5.1 KiB
C#
Raw Permalink Normal View History

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using YunDa.Server.ISMSTcp.Configuration;
using YunDa.SOMS.DataTransferObject;
namespace YunDa.Server.ISMSTcp.Services
{
/// <summary>
/// 孪生体ID API服务实现
/// </summary>
public class TwinIdApiService : ITwinIdApiService
{
private readonly HttpClient _httpClient;
private readonly ILogger<TwinIdApiService> _logger;
private readonly ApiEndpointsConfiguration _apiConfig;
public TwinIdApiService(
HttpClient httpClient,
ILogger<TwinIdApiService> logger,
IOptions<ApiEndpointsConfiguration> apiConfig)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_apiConfig = apiConfig?.Value ?? throw new ArgumentNullException(nameof(apiConfig));
}
/// <summary>
/// 通过孪生体代码获取设备信息ID
/// </summary>
/// <param name="code">孪生体代码</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>设备信息ID</returns>
public async Task<RequestResult<Guid>> GetTwIdAsync(string code, CancellationToken cancellationToken = default)
{
try
{
if (string.IsNullOrWhiteSpace(code))
{
_logger.LogWarning("GetTwIdAsync called with empty or null code");
return RequestResult<Guid>.CreateFailed("孪生体代码不能为空");
}
// 构建完整的API URL
var baseUrl = _apiConfig.BaseUrl.TrimEnd('/');
var getTwIdPath = _apiConfig.GetTwId ?? "/api/services/SOMS/RackEquipment/GetTwId";
var fullUrl = $"{baseUrl}{getTwIdPath}?code={Uri.EscapeDataString(code)}";
_logger.LogDebug("Making API call to GetTwId: {Url}", fullUrl);
// 发送HTTP GET请求
var response = await _httpClient.GetAsync(fullUrl, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_logger.LogDebug("GetTwId API response: {Response}", responseContent);
// 反序列化响应
var result = JsonConvert.DeserializeObject<RequestResult<Guid>>(responseContent);
if (result != null)
{
_logger.LogInformation("Successfully retrieved TwId for code: {Code}, EquipmentInfoId: {EquipmentInfoId}",
code, result.ResultData);
return result;
}
else
{
_logger.LogWarning("GetTwId API returned null result for code: {Code}", code);
return RequestResult<Guid>.CreateFailed("API返回空结果");
}
}
else
{
var errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_logger.LogError("GetTwId API call failed with status {StatusCode}: {ErrorContent}",
response.StatusCode, errorContent);
return RequestResult<Guid>.CreateFailed($"API调用失败: {response.StatusCode}");
}
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "HTTP request exception when calling GetTwId API for code: {Code}", code);
return RequestResult<Guid>.CreateFailed($"网络请求异常: {ex.Message}");
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
_logger.LogError(ex, "Timeout when calling GetTwId API for code: {Code}", code);
return RequestResult<Guid>.CreateFailed("API调用超时");
}
catch (TaskCanceledException ex) when (cancellationToken.IsCancellationRequested)
{
_logger.LogWarning("GetTwId API call was cancelled for code: {Code}", code);
return RequestResult<Guid>.CreateFailed("请求已取消");
}
catch (JsonException ex)
{
_logger.LogError(ex, "JSON deserialization error when calling GetTwId API for code: {Code}", code);
return RequestResult<Guid>.CreateFailed($"响应解析失败: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error when calling GetTwId API for code: {Code}", code);
return RequestResult<Guid>.CreateFailed($"未知错误: {ex.Message}");
}
}
}
}