duheng
2025-02-11 af0cfb03cda2679b4e89bf42ebea3d06e22ec4c0
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text; 
using IStation.Model;
 
namespace IStation.WinFrmUI.River
{
    /// <summary>
    ///  潮汐接口
    /// </summary>
    public class TideFromWebHelper
    { 
        private static readonly string _urlPrefix = "https://global-tide.nmdis.org.cn/Api/Service.ashx";
            //"http://global-tide.nmdis.org.cn/Api/Service.ashx";//主体Url
 
 
        /// <summary>
        /// 获取潮汐数据
        /// </summary>
        static public List<Model.TileLevel> GetByDay1(
            DateTime startday,  
            out string error)
        {
            string benchmark;
            var list = ReadList(startday, out benchmark);
            if(list == null)
            {
                list = GetByDayApi(startday, out benchmark, out error);
                if (list == null)
                {
                    return null;
                }
 
                SaveList(startday, benchmark, list);
            }
            else
            {
                 error = null;
            } 
            return list;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="startday"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        static public List<Model.TimeWaterLevel> GetByDay2(DateTime startday, out string error)
        {
            var waterLevels长江 = new List<TimeWaterLevel>();
         
            var list = GetByDay1(startday,   out error);
            if (list != null)
            {
                foreach (var h in list)
                {
                    waterLevels长江.Add(
                       new TimeWaterLevel(
                       new DateTime(startday.Year, startday.Month, startday.Day, h.Hour, 0, 0), h.Level));
                }
            }
            else
            {
                error = null;
            }
            return waterLevels长江;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="startday"></param>
        /// <param name="endday"></param>
        /// <param name="benchmark"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        static public List<Model.TimeWaterLevel> GetByDayRange(
            DateTime startday, DateTime endday, 
            out string error)
        {
   
            error = null;
 
            var waterLevels长江 = new List<TimeWaterLevel>(); 
            for (DateTime currentDate = startday; currentDate <= endday; currentDate = currentDate.AddDays(1))
            {
                if (endday.Date > DateTime.Now.Date.AddDays(2))
                {
                    break ;
                }
 
                var list1 = GetByDay1(startday.Date,  out error);
                if (list1 != null && list1.Count > 0)
                {
                    for (int h = startday.Hour; h < 24; h++)
                    {
                        waterLevels长江.Add(
                           new TimeWaterLevel(
                           new DateTime(startday.Year, startday.Month, startday.Day, h, 0, 0),
                           list1[h].Level));
                    }
                }
            }
 
   
            return waterLevels长江;
        }
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="day"></param>
        /// <param name="benchmark"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        static private List<Model.TileLevel> GetByDayApi(
            DateTime day,
            out string benchmark,
            out string error)
        {
            if (day > DateTime.Today.AddDays(1))
            {
                error = "不能查询后天的数据";
                benchmark = "";
                return null;
            }
            IStation.LogHelper.Info("read tide from web  day: " + day + " start");
 
            benchmark = "";
            error = "";
            IStation.CalcModel.Tide.PostParas paras = new CalcModel.Tide.PostParas();
            paras.Data = new CalcModel.Tide.DateParas();
            paras.Data.code = "NT1170";//static string 石洞口 = "NT1170";
            paras.Data.date = day.ToString();
            var url = $"{_urlPrefix}?ApiRequest={paras.ToJson()}";
            try
            {
                var responseText = HttpRequest(url, "GET");
                var result = JsonHelper.Json2Object<IStation.CalcModel.Tide.Result>(responseText);
                if (result == null)
                {
                    IStation.LogHelper.Error("read tide from web 1 长江水位请求失败 "   );
                    error = "长江水位请求失败";
                    return null;
                }
 
                if (Convert.ToBoolean(result.State) && !string.IsNullOrEmpty(result.Message))
                {
                    IStation.LogHelper.Error("read tide from web 2 长江水位请求失败 "+ result.Message);
                    error = result.Message;
                    return null;
                }
                if (result.Data == null)
                {
                    IStation.LogHelper.Error("read tide from web 3 长江水位请求失败 "  );
                    error = "长江水位请求失败";
                    return null;
                }
 
                benchmark = result.Data.Data.Benchmark;//= "在平均海面下213cm"
                List<Model.TileLevel> list = new List<Model.TileLevel>(24);
                list.Add(new Model.TileLevel()
                { Hour =   0 , Level = result.Data.SubData.a0 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 1, Level = result.Data.SubData.a1 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 2, Level = result.Data.SubData.a2 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 3, Level = result.Data.SubData.a3 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 4, Level = result.Data.SubData.a4 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 5, Level = result.Data.SubData.a5 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 6, Level = result.Data.SubData.a6 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 7, Level = result.Data.SubData.a7 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 8, Level = result.Data.SubData.a8 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 9, Level = result.Data.SubData.a9 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 10, Level = result.Data.SubData.a10 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 11, Level = result.Data.SubData.a11 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 12, Level = result.Data.SubData.a12 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 13, Level = result.Data.SubData.a13 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 14, Level = result.Data.SubData.a14 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 15, Level = result.Data.SubData.a15 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 16, Level = result.Data.SubData.a16 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 17, Level = result.Data.SubData.a17 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 18, Level = result.Data.SubData.a18 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 19, Level = result.Data.SubData.a19 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 20, Level = result.Data.SubData.a20 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 21, Level = result.Data.SubData.a21 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 22, Level = result.Data.SubData.a22 / 100 });
                list.Add(new Model.TileLevel()
                { Hour = 23, Level = result.Data.SubData.a23 / 100 });
                IStation.LogHelper.Info("read tide from web  day: " + day +" success");
                return list;
            }
            catch (Exception ex)
            {
                IStation.LogHelper.Error("read tide from web error:"+ ex);
                error = ex.Message;
                //IStation.Log
            }
            return null;
        }
 
        static private void SaveList(DateTime day, string benchmark, List<Model.TileLevel> list)
        {
            if (list == null)
                return;
            try
            {
                var folder = System.IO.Path.Combine(IStation.DataFolderHelper.GetRootPath(),
                "Tide", "FromWeb",
                day.Year.ToString(),
                day.ToString("yyyy-MM"));
                if (!System.IO.Directory.Exists(folder))
                {
                    System.IO.Directory.CreateDirectory(folder);
 
                }
                var fileName = System.IO.Path.Combine(folder,
                    string.Format("{0}.csv", day.ToString("yyyy-MM-dd")));
 
 
                StreamWriter streamWriter = new StreamWriter(fileName, false, System.Text.Encoding.GetEncoding("gb2312"));
 
                StringBuilder StringBuilder = new StringBuilder();
                // 写出表头
                StringBuilder.Append("总流量,长江水位差值");
                //
                StringBuilder.AppendLine(); StringBuilder.Append("benchmark,"); StringBuilder.Append(benchmark);
 
                // 写出数据
                foreach (var m in list)
                {
                    StringBuilder.AppendLine(); StringBuilder.AppendFormat("{0},{1}", m.Hour, m.Level);
                }
                streamWriter.Write(StringBuilder.ToString());
 
                streamWriter.Flush();
                streamWriter.Close();
            }
            catch(Exception ex)
            {
               IStation.LogHelper.WriteError("write tide file error:"+ex.Message, ex);
                return;
            }
        }
 
        static private List<Model.TileLevel> ReadList(DateTime day,out string benchmark)
        {
            var list = new List<Model.TileLevel>();
            benchmark = null;
            var folder = System.IO.Path.Combine(IStation.DataFolderHelper.GetRootPath(),
                "Tide", "FromWeb",
                day.Year.ToString(),
                day.ToString("yyyy-MM"));
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
                return null;
            }
            var fileName = System.IO.Path.Combine(folder,
                string.Format("{0}.csv", day.ToString("yyyy-MM-dd")));
            if (!System.IO.File.Exists(fileName))
            {
                return null;
            }
            //文件流读取
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
            System.IO.StreamReader sr = new System.IO.StreamReader(fs, Encoding.GetEncoding("gb2312"));
 
            string tempText  ;
            int line = 0;
            while ((tempText = sr.ReadLine()) != null)
            {
                line++;
                string[] arr = tempText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
 
                //一般第一行为标题,所以取出来作为标头
                if (line == 1)
                {
 
                }
                else if (line == 2)
                {
                    benchmark = arr[1];
                }
                else
                {
                     list.Add(new Model.TileLevel(Convert.ToInt32(arr[0]), Convert.ToDouble(arr[1])));
                }
            }
 
            //关闭流
            sr.Close(); fs.Close();
 
            return list;
        }
 
        //请求
        private static string HttpRequest(string url, string type, string data = null )
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
 
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = type;
            request.ContentType = "application/json";
            request.KeepAlive = false;
             
            //if (version != null)
            //{
            //    //默认是HttpVersion.Version11
            //    request.ProtocolVersion = version;
            //}
 
            #region 注释
            /*request.Timeout = 10 * 1000;//请求超时时间
            if (!string.IsNullOrEmpty(data))
            {
                request.ContentLength = Encoding.UTF8.GetBytes(data).Length;
            }*/
            #endregion
 
            if (!string.IsNullOrEmpty(data))
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(data);
                    streamWriter.Flush();
                }
            }
 
            string responseText;
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                responseText = reader.ReadToEnd();
            }
            return responseText;
        }
 
 
    }
}