HttpService.cs 6.93 KB
using HHECS.BllModel;
using HHECS.DAQClient.Dto;
using HHECS.DAQClient.Model;
using System.IO.Compression;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Net.Http.Headers;

namespace HHECS.DAQClient.Services
{
    internal class HttpService
    {
        private readonly HttpClient _httpClient;

        private readonly JsonSerializerOptions jsonSerializeOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            PropertyNameCaseInsensitive = true
        };

        private readonly JsonSerializerOptions jsonDeserializeOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };

        public HttpService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        /// <summary>
        /// 推送设备实时数据
        /// </summary>
        /// <param name="equipmentDataQueues"></param>
        public BllResult SendEquipmentData(IEnumerable<EquipmentDataQueue> equipmentDataQueues)
        {
            try
            {
                var data = equipmentDataQueues.Select(x => new EquipmentDataDto
                {
                    Plmeid = x.Id == Guid.Empty ? Guid.NewGuid() : x.Id,
                    EquipmentSN = x.EquipmentCode,
                    Reported = JsonSerializer.Deserialize<List<TagItem>>(x.Reported),
                    Version = x.Version,
                    Timestamp = x.SourceTimestamp,
                }).ToList();

                var json = JsonSerializer.Serialize(data, jsonSerializeOptions);
                var compressedData = CompressString(json);
                var content = new ByteArrayContent(compressedData);
                // 设置请求头,指明内容是GZip压缩的
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                content.Headers.ContentEncoding.Add("gzip");
                var result = _httpClient.PostAsync("Equipment/SendEquipmentData", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    return JsonSerializer.Deserialize<BllResult>(resultContent, jsonDeserializeOptions);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }
                return BllResultFactory.Error($"推送失败:{resultContent}");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        /// <summary>
        /// 推送某一时间段的数据
        /// </summary>
        /// <param name="equipmentDataQueues"></param>
        /// <returns></returns>
        public BllResult SendEquipmentDataV2(IEnumerable<EquipmentDataQueue> equipmentDataQueues)
        {
            try
            {
                var data = equipmentDataQueues.Select(x => new EquipmentDataV2Dto
                {
                    Plmeid = x.Id,
                    EquipmentSN = x.EquipmentCode,
                    Reported = JsonSerializer.Deserialize<List<TagItem>>(x.Reported),
                    Version = x.Version,
                    TimestampStart = x.SourceTimestamp,
                    TimestampEnd = (long)(x.SourceTimestamp + (x.Updated.Value - x.Created.Value).TotalMilliseconds),
                });
                var json = JsonSerializer.Serialize(data, jsonSerializeOptions);
                var compressedData = CompressString(json);
                var content = new ByteArrayContent(compressedData);
                // 设置请求头,指明内容是GZip压缩的
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                content.Headers.ContentEncoding.Add("gzip");
                var result = _httpClient.PostAsync("Equipment/SendEquipmentDataV2", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    return JsonSerializer.Deserialize<BllResult>(resultContent, jsonDeserializeOptions);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }
                return BllResultFactory.Error($"推送失败:{resultContent}");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        public BllResult UpdateClientStatus(Guid clientId)
        {
            try
            {
                var data = new
                {
                    ClientId = clientId,
                };
                var json = JsonSerializer.Serialize(data, jsonSerializeOptions);
                var compressedData = CompressString(json);
                var temp = DecompressString(compressedData);
                var content = new ByteArrayContent(compressedData);
                // 设置请求头,指明内容是GZip压缩的
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                content.Headers.ContentEncoding.Add("gzip");
                var result = _httpClient.PostAsync("Equipment/UpdateClientStatus", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    return JsonSerializer.Deserialize<BllResult>(resultContent, jsonDeserializeOptions);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }
                return BllResultFactory.Error($"推送失败:{resultContent}");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        /// <summary>
        /// 数据压缩
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static byte[] CompressString(string text)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(text);
            using var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }
            return memoryStream.ToArray();
        }

        public static string DecompressString(byte[] gzip)
        {
            using var memoryStream = new MemoryStream(gzip);
            using var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress);
            using var streamReader = new StreamReader(gZipStream, Encoding.UTF8);
            return streamReader.ReadToEnd();
        }
    }
}