EquipmentController.cs 3.89 KB
using HHECS.BllModel;
using HHECS.DAQServer.DataAccess;
using HHECS.DAQServer.Dto.Equipment;
using HHECS.DAQServer.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System.Text;
using System.Text.Json;

namespace HHECS.DAQServer.Controllers
{
    /// <summary>
    /// 设备数据
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class EquipmentController : ControllerBase
    {
        private readonly DataContext _context;
        private readonly IDistributedCache _cache;

        public EquipmentController(DataContext dataContext, IDistributedCache cache)
        {
            _context = dataContext;
            _cache = cache;
        }

        /// <summary>
        /// 推送设备实时数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<BllResult> SendEquipmentData(IEnumerable<EquipmentDataDto> data)
        {
            try
            {
                if (!data.Any())
                {
                    return BllResultFactory.Error($"数据不能为空!");
                }

                var records = data.Select(x => new EquipmentDataRecord
                {
                    Plmeid = x.Plmeid,
                    EquipmentCode = x.EquipmentSN,
                    Tags = JsonSerializer.Serialize(x.Reported),
                    IsHandle = false,
                    Version = x.Version,
                    CreateTime = DateTime.Now,
                    Timestamp = x.Timestamp,
                }).ToList();
                await _context.EquipmentDataRecord.AddRangeAsync(records);
                await _context.SaveChangesAsync();

                //缓存配置
                var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(10));
                foreach (var record in data.GroupBy(x => x.EquipmentSN))
                {
                    //获取最新时间戳的数据
                    var lastItem = record.OrderByDescending(x => x.Timestamp).First();

                    //获取当前缓存数据
                    var cacheDataBytes = await _cache.GetAsync(record.Key);
                    if (cacheDataBytes != null)
                    {
                        var cacheData = JsonSerializer.Deserialize<EquipmentDataDto>(Encoding.Default.GetString(cacheDataBytes));
                        if (cacheData.Timestamp >= lastItem.Timestamp)
                        {
                            continue;
                        }
                    }

                    var encodedCurrentData = JsonSerializer.SerializeToUtf8Bytes(lastItem);
                    await _cache.SetAsync(record.Key, encodedCurrentData, options);
                }
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        /// <summary>
        /// 更新设备在线状态
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<BllResult> UpdateClientStatus(ClientStatusDto data)
        {
            try
            {
                var client = await _context.ClientStatus.Where(x => x.ClientKeys == data.ClientId).FirstAsync();
                if (client == null)
                {
                    return BllResultFactory.Error($"客户端标识:{data.ClientId}不存在,请查验后再试!");
                }
                _context.ClientStatus.Attach(client);
                client.LastSeenDate = DateTime.Now;
                await _context.ClientStatus.UpdateAsync(client);
                await _context.SaveChangesAsync();
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }
    }
}