diff --git a/solarApp/Service/archiveLowData.cs b/solarApp/Service/archiveLowData.cs new file mode 100644 index 0000000..6645212 --- /dev/null +++ b/solarApp/Service/archiveLowData.cs @@ -0,0 +1,343 @@ +using System; +using System.Collections.Generic; +using System.Text; +using MySql.Data.MySqlClient; +using solarApp.Model; +using System.Configuration; +using Dapper; +using Microsoft.Extensions.Logging; + +namespace solarApp.Service +{ + class archiveLowData + { + string Connection1 = string.Empty; + + public archiveLowData(string Connection_parame = null) + { + if (!string.IsNullOrEmpty(Connection_parame)) + { + Connection1 = Connection_parame; + } + else + { + Connection1 = ConfigurationManager.ConnectionStrings["mySql"].ConnectionString; + } + } + + public string _siteID { get; set; } + public string _siteDB { get; set; } + public string _siteID01 { get; set; } + public string _powerStationID { get; set; } + + public bool archiveData(string siteID) + { + bool result = false; + try + { + _siteID = siteID; + //_date1 = date1; + get_siteInfo(); + checkTable(); + moveData(); + result = true; + } + catch (Exception ex) + { + throw ex; + } + return result; + } + + public bool get_siteInfo() + { + bool result = false; + try + { + using (MySqlConnection conn = new MySqlConnection(Connection1)) + { + conn.Open(); + #region 取得 PowerStationID + string sql = @" select id , `code` siteID, siteDB, `name` siteName + from solar_master.power_station where `code` = @siteID"; + var ds = conn.Query(sql, new { siteID = _siteID }).AsList(); + foreach (var item in ds) + { + _powerStationID = item.id; + _siteDB = item.SiteDB; + _siteID01 = item.SiteID + "01"; + } + #endregion + conn.Close(); + } + result = true; + } + catch (Exception ex) + { + throw ex; + } + return result; + } + + bool checkTable() + { + bool result = false; + using (MySqlConnection conn = new MySqlConnection(Connection1)) + { + conn.Open(); + try + { + //先判斷是否存在 DB + //string ss = $@"SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME='" + _siteDB + "'; "; + //List ds_db = conn.Query(ss, new { siteDB = _siteDB }).AsList(); + + ////如果該 DB不存在 則create + //if (ds_db.Count == 0) + //{ + // string createDb = $@"CREATE SCHEMA '" + _siteDB + "' DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"; + //} + + //判斷table是否存在 + string checkStationExists = $@"SELECT * FROM information_schema.tables WHERE table_schema = '{_siteDB}_history' AND table_name = 's{_siteID01}_station';"; + List ds_stationExists = conn.Query(checkStationExists).AsList(); + + //如果該 table不存在 則create + if (ds_stationExists.Count == 0) + { + string ss_station = $@"CREATE TABLE {_siteDB}_history. `s{_siteID01}_station` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `TIMESTAMP` bigint(20) NULL DEFAULT NULL, + `SITEID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `SITETYPE` int(11) NULL DEFAULT NULL, + `CONTROLLERID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `KWH` double NULL DEFAULT NULL, + `TODAYKWH` double NULL DEFAULT NULL, + `TOTALKWH` double NULL DEFAULT NULL, + `KWHKWP` double NULL DEFAULT NULL, + `PR` double NULL DEFAULT NULL, + `MP` double NULL DEFAULT NULL, + `SOLARHOUR` double NULL DEFAULT NULL, + `CreatedTime` datetime(0) NULL DEFAULT NULL, + `insertTime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + PRIMARY KEY (`ID`) USING BTREE + ) ENGINE = InnoDB AUTO_INCREMENT = 8920 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;"; + int ds_station = conn.Execute(ss_station); + } + + //判斷table是否存在 + string checkInvExists = $@"SELECT * FROM information_schema.tables WHERE table_schema = '{_siteDB}_history' AND table_name = 's{_siteID01}_inv';"; + List ds_InvExists = conn.Query(checkInvExists).AsList(); + + //如果該 table不存在 則create + if (ds_InvExists.Count == 0) + { + string ss_inv = $@"CREATE TABLE {_siteDB}_history.`s{_siteID01}_inv` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `TIMESTAMP` bigint(20) NULL DEFAULT NULL, + `SITEID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `SITETYPE` int(11) NULL DEFAULT NULL, + `CONTROLLERID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `INVERTERID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `SN` double NULL DEFAULT NULL, + `AC1V` double NULL DEFAULT NULL, + `AC1A` double NULL DEFAULT NULL, + `AC1W` double NULL DEFAULT NULL, + `AC1F` double NULL DEFAULT NULL, + `AC1WH` double NULL DEFAULT NULL, + `AC2V` double NULL DEFAULT NULL, + `AC2A` double NULL DEFAULT NULL, + `AC2W` double NULL DEFAULT NULL, + `AC2F` double NULL DEFAULT NULL, + `AC2WH` double NULL DEFAULT NULL, + `AC3V` double NULL DEFAULT NULL, + `AC3A` double NULL DEFAULT NULL, + `AC3W` double NULL DEFAULT NULL, + `AC3F` double NULL DEFAULT NULL, + `AC3WH` double NULL DEFAULT NULL, + `ACRUNTIME` double NULL DEFAULT NULL, + `DC1V` double NULL DEFAULT NULL, + `DC1A` double NULL DEFAULT NULL, + `DC1W` double NULL DEFAULT NULL, + `DC1WH` double NULL DEFAULT NULL, + `DC2V` double NULL DEFAULT NULL, + `DC2A` double NULL DEFAULT NULL, + `DC2W` double NULL DEFAULT NULL, + `DC2WH` double NULL DEFAULT NULL, + `DC3V` double NULL DEFAULT NULL, + `DC3A` double NULL DEFAULT NULL, + `DC3W` double NULL DEFAULT NULL, + `DC3WH` double NULL DEFAULT NULL, + `DC4V` double NULL DEFAULT NULL, + `DC4A` double NULL DEFAULT NULL, + `DC4W` double NULL DEFAULT NULL, + `DC4WH` double NULL DEFAULT NULL, + `DC5V` double NULL DEFAULT NULL, + `DC5A` double NULL DEFAULT NULL, + `DC5W` double NULL DEFAULT NULL, + `DC5WH` double NULL DEFAULT NULL, + `DCRUNTIME` double NULL DEFAULT NULL, + `WH` double NULL DEFAULT NULL, + `TODAYKWH` double NULL DEFAULT NULL, + `TOTALKWH` double NULL DEFAULT NULL, + `PR` double NULL DEFAULT NULL, + `RA1` double NULL DEFAULT NULL, + `RA2` double NULL DEFAULT NULL, + `RA3` double NULL DEFAULT NULL, + `RA4` double NULL DEFAULT NULL, + `RA5` double NULL DEFAULT NULL, + `CreatedTime` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), + `CrdTime` datetime(0) NULL DEFAULT NULL, + PRIMARY KEY (`ID`) USING BTREE, + INDEX `IDX01`(`TIMESTAMP`, `INVERTERID`) USING BTREE, + INDEX `IDX02`(`INVERTERID`, `CrdTime`) USING BTREE, + INDEX `IDX03`(`CrdTime`) USING BTREE + ) ENGINE = InnoDB AUTO_INCREMENT = 1197423 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;"; + int ds_inv = conn.Execute(ss_inv); + } + + //判斷table是否存在 + string checkSensorAvgExists = $@"SELECT * FROM information_schema.tables WHERE table_schema = '{_siteDB}_history' AND table_name = 's{_siteID01}_sensoravg';"; + List ds_sensorAvgExists = conn.Query(checkSensorAvgExists).AsList(); + + //如果該 table不存在 則create + if (ds_sensorAvgExists.Count == 0) + { + string ss_sensorAvg = $@"CREATE TABLE {_siteDB}_history.`s{_siteID01}_sensoravg` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `TIMESTAMP` bigint(20) NULL DEFAULT NULL, + `SITEID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `SITETYPE` int(11) NULL DEFAULT NULL, + `CONTROLLERID` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, + `SENSORAVG01` double NULL DEFAULT NULL, + `SENSORAVG02` double NULL DEFAULT NULL, + `SENSORAVG03` double NULL DEFAULT NULL, + `SENSORAVG04` double NULL DEFAULT NULL, + `SENSORAVG05` double NULL DEFAULT NULL, + `SENSORAVG06` double NULL DEFAULT NULL, + `SENSORAVG07` double NULL DEFAULT NULL, + `SENSORAVG08` double NULL DEFAULT NULL, + `SENSORAVG09` double NULL DEFAULT NULL, + `SENSORAVG10` double NULL DEFAULT NULL, + `SENSORAVG11` double NULL DEFAULT NULL, + `SENSORAVG12` double NULL DEFAULT NULL, + `SENSORAVG13` double NULL DEFAULT NULL, + `SENSORAVG14` double NULL DEFAULT NULL, + `SENSORAVG15` double NULL DEFAULT NULL, + `SENSORAVG16` double NULL DEFAULT NULL, + `SENSORAVG17` double NULL DEFAULT NULL, + `SENSORAVG18` double NULL DEFAULT NULL, + `SENSORAVG19` double NULL DEFAULT NULL, + `SENSORAVG20` double NULL DEFAULT NULL, + `SENSORAVG21` double NULL DEFAULT NULL, + `SENSORAVG22` double NULL DEFAULT NULL, + `SENSORAVG23` double NULL DEFAULT NULL, + `SENSORAVG24` double NULL DEFAULT NULL, + `SENSORAVG25` double NULL DEFAULT NULL, + `SENSORAVG26` double NULL DEFAULT NULL, + `SENSORAVG27` double NULL DEFAULT NULL, + `SENSORAVG28` double NULL DEFAULT NULL, + `SENSORAVG29` double NULL DEFAULT NULL, + `SENSORAVG30` double NULL DEFAULT NULL, + `SENSORAVG31` double NULL DEFAULT NULL, + `SENSORAVG32` double NULL DEFAULT NULL, + `SENSORAVG33` double NULL DEFAULT NULL, + `SENSORAVG34` double NULL DEFAULT NULL, + `SENSORAVG35` double NULL DEFAULT NULL, + `SENSORAVG36` double NULL DEFAULT NULL, + `SENSORAVG37` double NULL DEFAULT NULL, + `SENSORAVG38` double NULL DEFAULT NULL, + `SENSORAVG39` double NULL DEFAULT NULL, + `SENSORAVG40` double NULL DEFAULT NULL, + `SENSORAVG41` double NULL DEFAULT NULL, + `SENSORAVG42` double NULL DEFAULT NULL, + `SENSORAVG43` double NULL DEFAULT NULL, + `SENSORAVG44` double NULL DEFAULT NULL, + `SENSORAVG45` double NULL DEFAULT NULL, + `SENSORAVG46` double NULL DEFAULT NULL, + `SENSORAVG47` double NULL DEFAULT NULL, + `SENSORAVG48` double NULL DEFAULT NULL, + `SENSORAVG49` double NULL DEFAULT NULL, + `SENSORAVG50` double NULL DEFAULT NULL, + `CreatedTime` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), + `CrdTime` datetime(0) NULL DEFAULT NULL, + PRIMARY KEY (`ID`) USING BTREE, + INDEX `IDX_01`(`TIMESTAMP`) USING BTREE, + INDEX `IDX_02`(`CrdTime`) USING BTREE + ) ENGINE = InnoDB AUTO_INCREMENT = 108099 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;"; + int ds_sensorAvg = conn.Execute(ss_sensorAvg); + } + result = true; + } + catch (Exception ex) + { + throw ex; + } + conn.Close(); + } + return result; + } + + bool moveData() + { + bool result = false; + using (MySqlConnection conn = new MySqlConnection(Connection1)) + { + conn.Open(); + try + { + var dateTime = DateTime.Now.ToString("yyyy-MM-dd HH"); + + #region station搬移 + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】開始執行[{_siteDB}.s{_siteID}_station]的資料表向[{_siteDB}_history.s{_siteID}_station]搬移"); + string for_insert_station = $@"INSERT {_siteDB}_history.s{_siteID01}_station + SELECT * FROM {_siteDB}.s{_siteID01}_station + WHERE FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d') < '2022-07'"; + int insert_station = conn.Execute(for_insert_station, commandTimeout : 600); + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】{_siteDB}.s{_siteID}_station的七月前資料寫入至{_siteDB}_history.s{_siteID}_station【寫入成功】於{dateTime}"); + + //刪除原本的資料 + string for_delete_station = $@"DELETE FROM {_siteDB}.s{_siteID01}_station + WHERE FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d') < '2022-07'"; + int delete_station = conn.Execute(for_delete_station, commandTimeout: 600); + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】{_siteDB}.s{_siteID}_sensoravg搬移至{_siteDB}_history.s{_siteID}_sensoravg【搬移資料成功】於{dateTime} 共 {delete_station.ToString()} 筆"); + #endregion + + #region inv搬移 + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】開始執行[{_siteDB}.s{_siteID}_inv]的資料表向[{_siteDB}_history.s{_siteID}_inv]搬移"); + string for_insert_inv = $@"INSERT {_siteDB}_history.s{_siteID01}_inv + SELECT * FROM {_siteDB}.s{_siteID01}_inv + WHERE LEFT(crdTime, 7) < '2022-07'"; + int insert_inv = conn.Execute(for_insert_inv, commandTimeout : 600); + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】{_siteDB}.s{_siteID}_inv的七月前資料寫入至{_siteDB}_history.s{_siteID}_inv【寫入成功】於{dateTime}"); + + string for_delete_inv = $@"DELETE FROM {_siteDB}.s{_siteID01}_inv + WHERE LEFT(crdTime, 7) < '2022-07'"; + int delete_inv = conn.Execute(for_delete_inv, commandTimeout: 6000); + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】{_siteDB}.s{_siteID}_sensoravg搬移至{_siteDB}_history.s{_siteID}_sensoravg【搬移資料成功】於{dateTime} 共 {delete_inv.ToString()} 筆"); + #endregion + #region sensoravg搬移 + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】開始執行[{_siteDB}.s{_siteID}_sensoravg]的資料表向[{_siteDB}_history.s{_siteID}_sensoravg]搬移"); + string for_insert_sensoravg = $@"INSERT {_siteDB}_history.s{_siteID01}_sensoravg + SELECT * FROM {_siteDB}.s{_siteID01}_sensoravg + WHERE LEFT(crdTime, 7) < '2022-07'"; + int insert_sensoravg = conn.Execute(for_insert_sensoravg, commandTimeout : 600); + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】{_siteDB}.s{_siteID}_sensoravg的七月前資料寫入至{_siteDB}_history.s{_siteID}_sensoravg【寫入成功】於{dateTime}"); + string for_delete_sensoravg = $@"DELETE FROM {_siteDB}.s{_siteID01}_sensoravg + WHERE LEFT(crdTime, 7) < '2022-07'"; + int delete_sensoravg = conn.Execute(for_delete_sensoravg, commandTimeout: 600); + System.Diagnostics.Debug.WriteLine($"【ArchiveRowData】{_siteDB}.s{_siteID}_sensoravg搬移至{_siteDB}_history.s{_siteID}_sensoravg【搬移資料成功】於{dateTime} 共 {delete_sensoravg.ToString()} 筆"); + #endregion + result = true; + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine("【ArchiveRowData】[搬移資料失敗】"); + throw ex; + } + conn.Close(); + } + return result; + } + + } +} diff --git a/solarApp/fmArchive.cs b/solarApp/fmArchive.cs index 90a74d1..6b41283 100644 --- a/solarApp/fmArchive.cs +++ b/solarApp/fmArchive.cs @@ -629,97 +629,17 @@ namespace solarApp private void button1_Click_1(object sender, EventArgs e) { - //#region 氣象觀測(取資料) - //try - //{ - // logger.LogInformation("【CalcPowerStationJob】【開始取得氣象觀測】"); - // var client = new HttpClient(); - // var UVUri = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0003-001?Authorization=CWB-EA24220B-DDCC-4188-84E5-AD37A0E03F80&elementName=TIME,TEMP"; - // System.Net.Http.HttpResponseMessage response = client.GetAsync(UVUri).Result; - // String jsonUVs = response.Content.ReadAsStringAsync().Result.ToString(); - // observation = JsonConvert.DeserializeObject(jsonUVs); - // logger.LogInformation("【CalcPowerStationJob】【取得成功氣象觀測】"); - //} - //catch (Exception ex) - //{ - // //logger.LogError("【CalcPowerStationJob】【取得失敗氣象觀測】"); - // //logger.LogError("【{0}】{1}", "CalcPowerStationJob", ex.Message); - // observation = null; - //} - //#endregion - //foreach (var powerStation in powerStations) - //{ - // #region 確認是否有觀測站(沒有則新增) - // try - // { - // if (powerStation.WeathersStationId == null) - // { - // var weatherStationId = ""; - // double shortLocation = 9999; - // foreach (var Location in observation.Records.Location) - // { + int i = 0; + var site_list = stationSvc.get_station_list(); - // if (powerStation.Coordinate != null) - // { - // var powerLocation = powerStation.Coordinate.Split(','); - // double p1 = Convert.ToDouble(powerLocation[0]); - // double p2 = Convert.ToDouble(powerLocation[1]); - // double dLat = Convert.ToDouble(Location.Lat); - // double dLon = Convert.ToDouble(Location.Lon); - // double x = Math.Pow(p1 - dLat, 2); - // double y = Math.Pow(p2 - dLon, 2); - // var nowLocation = Math.Sqrt(x + y); - // //var nowLocation = Math.Sqrt(Math.Pow(Convert.ToDouble(powerLocation[0]) - // // - Convert.ToDouble(Location.Lat), 2) - // // + Math.Pow(Convert.ToDouble(powerLocation[1]) - // // - Convert.ToDouble(Location.Lon), 2) - // // ); - // if (nowLocation < shortLocation) - // { - // shortLocation = nowLocation; - // weatherStationId = Location.StationId; - // calcPowerStation.TodayWeatherTemp = Convert.ToDouble(Location.WeatherElement[0].ElementValue); - // } - // } - // } + archiveLowData archiveData = new archiveLowData(); - // calcPowerStation.WeathersStationId = weatherStationId; - // } - - // WeatherObservation weatherObservation = new WeatherObservation(); - // if (powerStation.WeathersStationId != null && observation != null) - // { - // foreach (var Location in observation.Records.Location) - // { - // if (Location.StationId == powerStation.WeathersStationId) - // { - // calcPowerStation.TodayWeatherTemp = Convert.ToDouble(Location.WeatherElement[0].ElementValue); - // weatherObservation.PowerStationId = powerStation.Id; - // weatherObservation.Temp = Convert.ToDouble(Location.WeatherElement[0].ElementValue); - // weatherObservation.ObsTime = !string.IsNullOrEmpty(Location.Time.ObsTime) ? Convert.ToInt32(Location.Time.ObsTime.Substring(0, 4)) >= 1971 ? Location.Time.ObsTime : DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); - // calcPowerStation.WeathersStationId = powerStation.WeathersStationId; - // break; - // } - // } - // weatherObservations.Add(weatherObservation); - // } - - // logger.LogInformation("【CalcPowerStationJob】【開始取得電站[{0}]在{1}的天氣預報的資訊】", powerStation.Code, dateTime); - // var weather = await powerStationRepository.SelectNowWeather(powerStation.CityId); - // logger.LogInformation("【CalcPowerStationJob】【取得成功電站[{0}]在{1}的天氣預報的資訊】", powerStation.Code, dateTime); - // if (weather != null) - // { - // calcPowerStation.TodayWeather = weather.WeatherKey; - // calcPowerStation.RateOfRain = weather.PoP; - // } - // } - // catch (Exception ex) - // { - // logger.LogError("【CalcPowerStationJob】【取得失敗電站[{0}]在{1}的天氣預報的資訊】", powerStation.Code, dateTime); - // logger.LogError("【CalcPowerStationJob】【失敗原因】- {0}", ex.Message); - // } - // #endregion - //} + foreach (var item in site_list) + { + archiveData.archiveData(item.SiteID.Substring(0, 9)); + i++; + } + lbMsgTitle.Text = System.DateTime.Now.ToString() + " 完成!"; } private void button2_Click(object sender, EventArgs e)