using CsvHelper; using CsvHelper.Configuration; using OrpaonEMS.Model; using ScottPlot.TickGenerators.TimeUnits; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace OrpaonEMS.App.Services { /// /// 储能数据记录服务 /// public class EsDataLogService { public ILogService LogService { get; } public IFreeSql FreeSql { get; } public ConfigDataService ConfigDataService { get; } public BmsDataService BmsDataService { get; } public SolarEnergyService SolarEnergyService { get; } public InPowerPCSDataService InPowerPCSDataService { get; } /// /// 缓存的集合信息数据 /// private List ListCacheESData = new List(); /// /// 周期定时器 /// private System.Timers.Timer CycleTimer { get; set; } public EsDataLogService(ILogService logService, IFreeSql freeSql, ConfigDataService configDataService, BmsDataService bmsDataService, SolarEnergyService solarEnergyService, InPowerPCSDataService inPowerPCSDataService) { LogService = logService; FreeSql = freeSql; ConfigDataService = configDataService; BmsDataService = bmsDataService; SolarEnergyService = solarEnergyService; InPowerPCSDataService = inPowerPCSDataService; //10秒触发一次 CycleTimer = new System.Timers.Timer(1000); CycleTimer.Elapsed += CycleAction; CycleTimer.AutoReset = true; CycleTimer.Enabled = true; } /// /// Append to the file. /// CsvConfiguration CSVconfig = new CsvConfiguration(CultureInfo.InvariantCulture) { // Don't write the header again. HasHeaderRecord = false, }; private int _Month; /// /// 月份信息 数据文件删除用 /// public int Month { get { return _Month; } set { if (_Month != value) { _Month = value; Task.Run(new Action(DeleteFile)); } } } private void CycleAction(object? sender, ElapsedEventArgs e) { try { ListCacheESData.Add(new ESData() { BmsAccCharg = BmsDataService.BmsAccCharg.RtValue, BmsAccDisCharg = BmsDataService.BmsAccDisCharg.RtValue, BmsCur = BmsDataService.BmsCur.RtValue, BmsMaxBatTemp = BmsDataService.BmsMaxBatTemp.RtValue, BmsMaxChargePowerCell = BmsDataService.MaxChargePowerCell.RtValue, BmsMaxDisChargePowerCell = BmsDataService.MaxDisChargePowerCell.RtValue, BmsMinBatTemp = BmsDataService.BmsMinBatTemp.RtValue, BmsSOC = BmsDataService.BmsSOC.RtValue, BmsSOE = BmsDataService.BmsSOE.RtValue, BmsSOH = BmsDataService.BmsSOH.RtValue, BmsVol = BmsDataService.BmsVol.RtValue, PcsACur = InPowerPCSDataService.ACur, PcsAVol = InPowerPCSDataService.AVol, PcsBCur = InPowerPCSDataService.BCur, PcsBVol = InPowerPCSDataService.BVol, PcsCCur = InPowerPCSDataService.CCur, PcsCurCmdPw = InPowerPCSDataService.CurCmdPw, PcsCVol = InPowerPCSDataService.CVol, PcsPower = InPowerPCSDataService.Power, PcsStateMsg = InPowerPCSDataService.PcsRunState.PcsStateMsg, CreateTime = DateTime.Now, }); if (ListCacheESData.Count() >= 5) { //如果Execute执行的是一个很耗时的方法,会导致方法未执行完毕,定时器又启动了一个线程来执行Execute方法 CycleTimer.Stop(); //先关闭定时器 RecordData(); //清空缓存数据 ListCacheESData.Clear(); CycleTimer.Start(); //先关闭定时器 Month = DateTime.Now.Month; } } catch (Exception ex) { //CycleTimer.Start(); //执行完毕后再开启器 LogService.Info($"时间:{DateTime.Now.ToString()}-【PwAnalyze-CycleAction】-{ex.Message}"); } } private void RecordData() { try { //本地文件夹路径 var PathInfo = GetFilePath(ConfigDataService.DataLogFile, DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString()); if (!Directory.Exists(PathInfo)) { Directory.CreateDirectory(PathInfo); } //文件全部路径信息 var FileFullInfo = GetLocalFullFilePath(ConfigDataService.DataLogFile, DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString()); if (!File.Exists(FileFullInfo))//是否存在文件 { using (var writer = new StreamWriter(FileFullInfo, false, encoding: Encoding.Unicode)) using (var csv = new CsvWriter(writer, CultureInfo.CurrentCulture)) { csv.WriteRecords(ListCacheESData); } } else//存在文件的话则新增数据 { using (var stream = File.Open(FileFullInfo, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) //using (var stream = new FileStream(FileFullInfo, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) using (var writer = new StreamWriter(stream, encoding: Encoding.Unicode)) using (var csv = new CsvWriter(writer, CSVconfig)) { //csv.Context.RegisterClassMap(); csv.WriteRecords(ListCacheESData); } } } catch (Exception ex) { LogService.Info($"时间:{DateTime.Now.ToString()}-【PwAnalyze-CycleAction】-{ex.Message}"); } } /// /// 删除文件夹 /// 最多存两个月的数据 /// /// private void DeleteFile() { var dateTime = DateTime.Now; var DateList = new List() { dateTime.AddMonths(-2), dateTime.AddMonths(-3), dateTime.AddMonths(-4), dateTime.AddMonths(-5), dateTime.AddMonths(-6), dateTime.AddMonths(-7) }; try { string folderPath; foreach (var item in DateList) { folderPath = $@"{ConfigDataService.DataLogFile}\{item.ToString("yyyy")}\{item.ToString("yyyy")}-{item.Month}\"; if (Directory.Exists(folderPath)) { Directory.Delete(folderPath, true); // 第二个参数为 true,表示递归删除包括子文件夹和文件 Console.WriteLine("文件夹删除成功。"); } else { Console.WriteLine("文件夹不存在。"); } } } catch (Exception ex) { LogService.Info($"时间:{DateTime.Now.ToString()}-【PwAnalyze-CycleAction】-{ex.Message}"); } } /// /// 获取文件路径 /// /// /// public static string GetFilePath(string FileRootPath, string Month, string Day) { return $@"{FileRootPath}\{DateTime.Now.ToString("yyyy")}\{DateTime.Now.ToString("yyyy")}-{Month}\{Day}\"; } /// /// 获取本地文件路径 /// /// /// public static string GetLocalFullFilePath(string FileRootPath, string Month, string Day) { return $@"{FileRootPath}\{DateTime.Now.ToString("yyyy")}\{DateTime.Now.ToString("yyyy")}-{Month}\{Day}\{GetFileName(Month, Day)}.csv"; } /// /// 获取CSV文件名称 /// /// /// public static string GetFileName(string Month, string Day) { return $"{DateTime.Now.ToString("yyyy")}-{Month}-{Day}"; } } }