tangxu
2024-03-19 26c7bd3e7060ffcb6456ea2098850ec5a4fee77c
WebApi/ÖÚÒãµ÷¶È/ZyConnectHelper.cs
@@ -1,9 +1,11 @@
 
using IStation.ZyDto;
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@@ -15,11 +17,14 @@
    /// </summary> 
    internal class ZyConnectHelper
    {
        public static bool isDebug = true;
        public static bool isDebug = false;
        /// <summary>
        /// 
        /// </summary>
        //static string _url_root = "ws://localhost:40001";
        //static string _url_prj = "ws://localhost:8001";
        static string _url_root = "ws://192.168.201.17:40001";
        static string _url_prj = "ws://192.168.201.17:8001";
        /// <summary>
        /// æäº¤è°ƒåº¦é¡¹ç›®
@@ -28,11 +33,11 @@
        /// <param name="cbSuccess"></param>
        /// <param name="cbFail"></param>
        /// <returns></returns>
        public static async Task<bool> SubmitPrj(IStation.CalcModel.AnaPrj currentViewPrj, Action cbSuccess, Action<string> cbFail)
        public static async Task<string> SubmitPrj(IStation.CalcModel.AnaPrj currentViewPrj)
        {
            if (currentViewPrj == null)
            {
                return false;
                return "currentViewPrj is null";
            }
            IStation.ZyDto.SubmitPrj dto_prj = new ZyDto.SubmitPrj();
            dto_prj.Day = currentViewPrj.StartTime.ToString("yyyy-MM-dd");
@@ -50,32 +55,68 @@
            }
            var ws = new ClientWebSocket();
            try
            {
                await ws.ConnectAsync(new Uri(_url_root), CancellationToken.None);
             await ws.ConnectAsync(new Uri(_url_prj), CancellationToken.None);
                if (ws.State != WebSocketState.Open)
                {
                    return default;
                return "WebSocketState is close";
                }
                var inputJson = JsonHelper.Object2Json(dto_prj);
                var inputBytes = Encoding.UTF8.GetBytes(inputJson);
                await ws.SendAsync(new ArraySegment<byte>(inputBytes), WebSocketMessageType.Text, true, CancellationToken.None);
            try
            {
                List<byte> outputBytes = new List<byte>();//全部消息容器
                var buffer = new byte[1024 * 4];//缓冲区
                var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); //监听Socket信息
                while (!result.CloseStatus.HasValue)  //是否关闭
                {
                    if (result.MessageType == WebSocketMessageType.Text)//文本消息
                    {
                        outputBytes.AddRange(buffer.Take(result.Count));
                        if (result.EndOfMessage)//消息是否已接收完全
                        {
                            //发送过来的消息
                            string outputJson = Encoding.UTF8.GetString(outputBytes.ToArray(), 0, outputBytes.Count);
                            var outPrj=JsonHelper.Json2Object<OutPrj>(outputJson);
                            if (outPrj == null)
                                return "return is null";
                            if( outPrj.result == 1)
                            {
                                //cbSuccess.Invoke(outPrj.schemeID);
                            }
                            else
                            {
                                return "outPrj result:"+ outPrj.result;
                            }
                        }
                    }
                   // result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);//继续监听Socket信息
                }
            }
            catch (Exception ex)
            {
                IStation.LogHelper.WriteError("Error:101", ex);
                return  "ex:" + ex.Message;
            }
            finally
            {
                try
                {
                //关闭WebSocket
                await ws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "AcknowledgeCloseframe", CancellationToken.None);
            }
            catch (Exception ex)
            {
                cbFail.Invoke(ex.Message);
                ws.Abort(); ws.Dispose();
                return false;
                    IStation.LogHelper.WriteError("Error:111", ex);
                   // return "ex:" + ex.Message;
            }
            ws.Abort();
            ws.Dispose();
            cbSuccess.Invoke();
            return true;
        }
            return null ;
        }
        /// <summary>
@@ -162,7 +203,6 @@
                    if (r.MonitorRecords == null || !r.MonitorRecords.Any())
                        continue;
                    var rrr = r.MonitorRecords.Where(x => x.Value != null).Select(x => x.Value.Value).ToList();
                    //var rrr = (from x in r.MonitorRecords where x.Value != null orderby x select x.Value.Value)?.ToList();
                    if (rrr == null || !rrr.Any())
                        continue;
@@ -229,7 +269,7 @@
        /// <param name="endTime">结束时间</param>
        /// <param name="resolution">时间步长,默认300秒</param>
        /// <returns></returns>
        public static async Task<double> GetTotalWaterByDay_Out(DateTime day, string resolution = "300")
        public static async Task<double> GetTotalWaterByDay_Out(DateTime dayD, string resolution = "300")
        {
            if (isDebug)
                return 135 + new Random().Next(10);
@@ -244,12 +284,15 @@
            var input = new ZyDto.ScadaDispatchInput
            {
                search = "history",
                starttime = new DateTime(day.Year, day.Month, day.Day, 0, 0, 0).ToString("G"),
                endtime = new DateTime(day.Year, day.Month, day.Day, 23, 59, 59).ToString("G"),
                starttime = new DateTime(dayD.Year, dayD.Month, dayD.Day, 0, 0, 0).ToString("G"),
                endtime = new DateTime(dayD.Year, dayD.Month, dayD.Day, 23, 59, 59).ToString("G"),
                Resolution = resolution,
                taglist = tagDict.Select(x => x.Key).ToArray()
            };
            if (dayD == DateTime.Today)
            {
                input.endtime = DateTime.Now.AddMinutes(-5).ToString("G");
            }
            double totalWaterSupply = 0;
            var realScadaDataList = await GetRealScadaResult(input);
            if (realScadaDataList != null && realScadaDataList.Any())
@@ -261,7 +304,10 @@
                    var rrr = r.MonitorRecords.Where(x => x.Value != null).Select(x => x.Value.Value).ToList();
                    if (rrr == null || !rrr.Any())
                        continue;
                    if (double.IsNaN(rrr.Last()) || double.IsNaN(rrr.First()))
                    {
                        throw new Exception( "获取监控数据失败" );
                    }
                    totalWaterSupply += (rrr.Last() - rrr.First());
                }
@@ -470,7 +516,6 @@
            {
                return default;
            }
            var realScadaDataList = new List<RealScadaData>();
            var inputJson = JsonHelper.Object2Json(input);
            var inputBytes = Encoding.UTF8.GetBytes(inputJson);
@@ -509,6 +554,7 @@
                                    }
                                    realScadaDataList.Add(data);
                                }
                            }
                            break;
                        }
@@ -735,6 +781,21 @@
        }
        /// <summary>
        /// Test1
        /// </summary>
        /// <returns></returns>
        public static async Task<double> async_debug()
        {
            //var ws = new ClientWebSocket();
            // await ws.ConnectAsync(new Uri(_url_root), CancellationToken.None);
              await Task.Run(() =>
            {
                Thread.Sleep(1000);
            });
            return   1;
        }
        /// <summary>
        ///