IotService.cs 2.82 KB
using DataAcquisition.ViewModels.IOT;
using System.Text;
using System.Text.Json;

namespace DataAcquisition.Services
{
    public class IotService
    {
        private readonly IHttpClientFactory _httpClientFactory;

        private readonly string identity = "iot";

        public IotService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 设备数据
        /// </summary>
        /// <param name="equipment"></param>
        /// <returns></returns>
        public IotResult<string> SendEquipment(IEnumerable<IotEquipment> equipment)
        {
            return Post("", equipment);
        }

        /// <summary>
        /// 设备报警
        /// </summary>
        /// <param name="equipmentAlarm"></param>
        /// <returns></returns>
        public IotResult<string> SendEquipmentAlarm(IotEquipmentAlarm equipmentAlarm)
        {
            return Post("", equipmentAlarm);
        }

        /// <summary>
        /// 设备运行参数
        /// </summary>
        /// <param name="equipmmentRunParameter"></param>
        /// <returns></returns>
        public IotResult<string> SendEquipmentRunParameter(IotEquipmmentRunParameter equipmmentRunParameter)
        {
            return Post("", equipmmentRunParameter);
        }

        /// <summary>
        /// 设备状态
        /// </summary>
        /// <param name="equipmentStatus"></param>
        /// <returns></returns>
        public IotResult<string> SendEquipmentStatus(IotEquipmentStatus equipmentStatus)
        {
            return Post("", equipmentStatus);
        }

        private IotResult<string> Post<T>(string requestUri, T data)
        {
            try
            {
                var client = _httpClientFactory.CreateClient(identity);
                var json = JsonSerializer.Serialize(data);
                var responseMessage = client.PostAsync(requestUri, new StringContent(json, Encoding.UTF8)).GetAwaiter().GetResult();
                if (!responseMessage.IsSuccessStatusCode)
                {
                    return new IotResult<string>
                    {
                        Code = (int)responseMessage.StatusCode,
                        Status = false,
                        Message = responseMessage.ReasonPhrase ?? string.Empty,
                    };
                }
                var responseContent = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                return JsonSerializer.Deserialize<IotResult<string>>(responseContent)!;
            }
            catch (Exception ex)
            {
                return new IotResult<string>
                {
                    Code = 500,
                    Message = ex.Message,
                    Status = false,
                };
            }
        }
    }
}