tangxu
2024-06-12 16ad5cbeb4ef90fcce13458e13acc324d592106c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
using IStation.Common;
using IStation.Dto;
using IStation.Untity; 
using IStation.ZyModel; 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http; 
 
namespace IStation.WebApi.Controllers
{
    /// <summary>
    /// 取水总量
    /// </summary>
    [RoutePrefix("TotalWaterIn")]
    public class TotalWaterInController : ApiController
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [Route("Test1")]
        [HttpGet]
        public async Task<IStation.Dto.ApiResult> Test1()
        {
            var sum = await ZyConnectHelper.async_debug();
            return new IStation.Dto.ApiResult<double>(sum);
        }
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [Route("Test2")]
        [HttpGet]
        public IStation.Dto.ApiResult Test2()
        {
            var sum = ZyConnectHelper.async_debug().GetAwaiter().GetResult();
            return new IStation.Dto.ApiResult<double>(sum);
        }
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [Route("GetByDayDebug")]
        [HttpGet]
        public IStation.Dto.ApiResult GetByDayDebug(string day)
        {
            if (ZyConnectHelper.isDebug)
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "Debug is Unacess " };
            if (day == null)
            {
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "day null" };
            }
            if (!DateTime.TryParse(day, out DateTime dayD))
            {
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "day 格式不正确" };
            }
            if (dayD > DateTime.Today)
            {
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "不能查询今日的数据" };
            }
 
            var sum = ZyConnectHelper.GetTotalWaterByDay_In(dayD).Result;
            return new IStation.Dto.ApiResult<double>(sum);
        }
 
        /// <summary>
        /// 获取某日的取水总量
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [Route("GetByDay")]
        [HttpGet]
        public async Task<IStation.Dto.ApiResult> GetByDay(string day)
        {
            if (ZyConnectHelper.isDebug)
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "Debug is Unacess " };
            if (day == null)
            {
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "day null" };
            }
            if (!DateTime.TryParse(day, out DateTime dayD))
            {
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "day 格式不正确" };
            }
            if (dayD > DateTime.Today)
            {
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "不能查询今日的数据" };
            }
            double sum = -1;
            if (dayD < DateTime.Today)
            {
                sum = TotalWaterInHelper.Read(dayD);
            }
 
            if (sum < 0)
            {
                var tagDict = new Dictionary<string, string>
                {
                  { "1#", "二取水1号主水泵.累计流量" },
                  { "2#", "二取水2号主水泵.累计流量" },
                  { "3#", "二取水3号主水泵.累计流量" },
                  { "4#", "二取水4号主水泵.累计流量" },
                  { "5#", "二取水5号主水泵.累计流量" },
                };
                var starttime = new DateTime(dayD.Year, dayD.Month, dayD.Day, 0, 0, 0).ToString("G");
                var endtime = new DateTime(dayD.Year, dayD.Month, dayD.Day, 23, 59, 59).ToString("G");
                if (dayD == DateTime.Today)
                {
                    endtime = DateTime.Now.AddMinutes(-5).ToString("G");
                }
                sum = 0;
                string joinedValues = string.Join(",", tagDict.Values);
                var result = HttpClientHelper.Get<List<DataPoint>>(ZyConnectHelper.ZyApiUrl, starttime, endtime, "first", "300s", joinedValues);
                var realScadaDataList = ZyConnectHelper.GetScadaData(result);
                if (realScadaDataList != null && realScadaDataList.Any())
                {
                    foreach (var r in realScadaDataList)
                    {
                        if (r.MonitorRecords == null || !r.MonitorRecords.Any())
                            continue;
                        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()))
                        {
                            return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "获取监控数据失败" };
                        }
                        sum += (rrr.Last() - rrr.First());
                    }
                }
            }
            if (dayD < DateTime.Today)
            {
                TotalWaterInHelper.Save(dayD, sum);
            }
            return new IStation.Dto.ApiResult<double>(sum / 10000);
        }
 
        /// <summary>
        /// 获取最近三天的取水总量
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [Route("GetLastDay3")]
        [HttpGet]
        public async Task<IStation.Dto.ApiResult> GetLastDay3()
        {
            if (ZyConnectHelper.isDebug)
                return new IStation.Dto.ApiResult() { Code = ApiResultCode.Error, Message = "Debug is Unacess " };
            DateTime yest1 = DateTime.Today.AddDays(-1);
            var sum1 = TotalWaterInHelper.Read(yest1);
            if (sum1 < 0)
            {
                sum1 = await ZyConnectHelper.GetTotalWaterByDay_In(yest1);//.GetAwaiter().GetResult();
                TotalWaterInHelper.Save(yest1, sum1);
            }
 
            DateTime yest2 = DateTime.Today.AddDays(-2);
            var sum2 = TotalWaterInHelper.Read(yest2);
            if (sum2 < 0)
            {
                sum2 = await ZyConnectHelper.GetTotalWaterByDay_In(yest2);//.GetAwaiter().GetResult();
                TotalWaterInHelper.Save(yest2, sum2);
            }
 
            DateTime yest3 = DateTime.Today.AddDays(-3);
            var sum3 = TotalWaterInHelper.Read(yest3);
            if (sum3 < 0)
            {
                sum3 = await ZyConnectHelper.GetTotalWaterByDay_In(yest3);//.GetAwaiter().GetResult();
 
                TotalWaterInHelper.Save(yest3, sum3);
            }
 
            return new IStation.Dto.ApiResult<List<double>>(new List<double> { sum1 / 10000, sum2 / 10000, sum3 / 10000 });
        }
 
        /// <summary>
        /// 获取web客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetWebClientIp()
        {
            string userIP = "";
 
            try
            {
                if (System.Web.HttpContext.Current == null
                 || System.Web.HttpContext.Current.Request == null
                 || System.Web.HttpContext.Current.Request.ServerVariables == null)
                {
                    return "";
                }
 
                string CustomerIP = "";
 
                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }
 
                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 
                if (!String.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }
 
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 
                    if (CustomerIP == null)
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
 
                if (string.Compare(CustomerIP, "unknown", true) == 0 || String.IsNullOrEmpty(CustomerIP))
                {
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                }
                return CustomerIP;
            }
            catch { }
 
            return userIP;
        }
 
        private string _url = "ws://192.168.201.17:40001";
 
        private async Task<List<ZyModel.RealScadaData>> Get(string inputJson)
        {
            if (string.IsNullOrEmpty(inputJson))
                return default;
            var ws = new ClientWebSocket();
            IStation.LogHelper.Info(" var ws = new ClientWebSocket();");
            await ws.ConnectAsync(new Uri(_url), CancellationToken.None);
            IStation.LogHelper.Info(" ws.ConnectAsync(new Uri(_url_root), CancellationToken.None);");
            if (ws.State != WebSocketState.Open)
            {
                return default;
            }
            IStation.LogHelper.Info("ws.ConnectAsync");
            var realScadaDataList = new List<ZyModel.RealScadaData>();
            var inputBytes = Encoding.UTF8.GetBytes(inputJson);
            await ws.SendAsync(new ArraySegment<byte>(inputBytes), WebSocketMessageType.Text, true, CancellationToken.None);
            try
            {
                IStation.LogHelper.Info("ws.SendAsync");
                List<byte> outputBytes = new List<byte>();//全部消息容器
                var buffer = new byte[1024 * 4];//缓冲区
                var result = ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result; //监听Socket信息
                while (!result.CloseStatus.HasValue)  //是否关闭
                {
                    if (result.MessageType == WebSocketMessageType.Text)//文本消息
                    {
                        outputBytes.AddRange(buffer.Take(result.Count));
                        if (result.EndOfMessage)//消息是否已接收完全
                        {
                            IStation.LogHelper.Info("result.EndOfMessage");
                            //发送过来的消息
                            string outputJson = Encoding.UTF8.GetString(outputBytes.ToArray(), 0, outputBytes.Count);
                            var scadaDict = JsonHelper.Json2Object<Dictionary<string, Dictionary<DateTime, string>>>(outputJson);
                            if (scadaDict != null && scadaDict.Any())
                            {
                                foreach (var dict in scadaDict)
                                {
                                    var data = new ZyModel.RealScadaData();
                                    data.TagName = dict.Key;
                                    data.MonitorRecords = new List<IStation.ZyModel.MonitorRecord>();
                                    foreach (var item in dict.Value)
                                    {
                                        var record = new IStation.ZyModel.MonitorRecord();
                                        record.Time = item.Key;
                                        if (double.TryParse(item.Value, out double value))
                                        {
                                            record.Value = value;
                                        }
                                        data.MonitorRecords.Add(record);
                                    }
                                    realScadaDataList.Add(data);
                                }
                                IStation.LogHelper.Info("scadaDict != null && scadaDict.Any()");
                            }
                            break;
                        }
                    }
 
                    result = ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;//继续监听Socket信息
                                                                                                            // IStation.LogHelper.Info("ws.ReceiveAsync");
                }
            }
            catch (Exception ex)
            {
                IStation.LogHelper.Info(ex.Message);
                throw ex;
            }
            finally
            {
                try
                {   //关闭WebSocket
                    await ws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "AcknowledgeCloseframe", CancellationToken.None);
                    IStation.LogHelper.Info("ws.CloseOutputAsync");
                }
                catch (Exception ex)
                {
                    IStation.LogHelper.Info(ex.Message);
                    throw ex;
                }
                ws.Abort();
                ws.Dispose();
            }
            return realScadaDataList;
        }
    }
}