IotService.cs 5.33 KB
using DataAcquisition.Common.Enums;
using DataAcquisition.Models;
using DataAcquisition.ViewModels.IOT;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

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="equipments"></param>
        /// <returns></returns>
        public IotResult<string> SendEquipmentData(IEnumerable<Equipment> equipments)
        {
            var data = new IotEquipmentDataDto
            {
                Equipments = equipments.Where(x => EquipmentCodes.Contains(x.Code)).Select(x => new EquipmentItem
                {
                    EquipmentSN = x.EquipmentSN,
                    Tags = x.EquipmentProperties.Select(p => new TagItem
                    {
                        Tag = p.DataAddress,
                        Value = p.Value ?? string.Empty,
                        SourceTimestamp = ConvertToTimestamp(p.UpdateTime),
                    }).ToList(),
                }).ToList(),
                Version = 1,
                Timestamp = ConvertToTimestamp(DateTime.Now)
            };
            return Post("api/Equipment/SendEquipmentData", data);
        }

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

        public IotResult<string> SyncEquipment(IEnumerable<Equipment> equipments)
        {
            var data = equipments.Where(x => EquipmentCodes.Contains(x.Code)).Select(x => new IotEquipmentDto
            {
                Code = x.Code,
                Name = x.Name,
                EquipmentSN = x.EquipmentSN,
                Type = x.EquipmentType.ToString(),
                Remark = x.Remark ?? string.Empty,
                EquipmentProperties = x.EquipmentProperties.Select(p => new EquipmentPropertyDto
                {
                    Code = p.Code,
                    Name = p.Name,
                    Tag = p.DataAddress,
                    Value = p.Value,
                    Remark = p.Remark,
                }).ToList(),
                WarehouseCode = x.WarehouseCode,
            }).OrderBy(x => x.Code).ToList();
            return Post("api/Equipment/SyncEquipment", data);
        }

        private IotResult<string> Post<T>(string requestUri, T data)
        {
            try
            {
                var client = _httpClientFactory.CreateClient(identity);
                var json = JsonSerializer.Serialize(data, JsonSerializerOptions);
                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,
                };
            }
        }

        private static long ConvertToTimestamp(DateTime? dateTime)
        {
            if (dateTime == null)
            {
                return 0;
            }
            return Convert.ToInt64(((DateTime)dateTime - new DateTime(1970, 1, 1)).TotalSeconds);
        }

        private static List<string> EquipmentCodes => new List<EquipmentConst>
        {
            EquipmentConst.Kuka_1,
            EquipmentConst.Kuka_2,
            EquipmentConst.Kuka_3,
            EquipmentConst.Kuka_4,
            EquipmentConst.Efort_1,
            EquipmentConst.Fanuc_1,
        }.Select(x => x.ToString()).ToList();

        private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions
        {
            ReferenceHandler = ReferenceHandler.IgnoreCycles,
        };
    }
}