using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using IStation.Model; namespace IStation.WinFrmUI.River { /// /// 潮汐接口 /// 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 /// /// 获取潮汐数据 /// static public List 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; } /// /// /// /// /// /// static public List GetByDay2(DateTime startday, out string error) { var waterLevels长江 = new List(); 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长江; } /// /// /// /// /// /// /// /// static public List GetByDayRange( DateTime startday, DateTime endday, out string error) { error = null; var waterLevels长江 = new List(); 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长江; } /// /// /// /// /// /// /// static private List 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(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 list = new List(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 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 ReadList(DateTime day,out string benchmark) { var list = new List(); 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; } } }