Files
YuPu-OrpaonEMS/OrpaonEMS.App/Services/EsDataLogService.cs
2025-02-28 22:23:13 +08:00

260 lines
9.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
{
/// <summary>
/// 储能数据记录服务
/// </summary>
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; }
/// <summary>
/// 缓存的集合信息数据
/// </summary>
private List<ESData> ListCacheESData = new List<ESData>();
/// <summary>
/// 周期定时器
/// </summary>
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;
}
/// <summary>
/// Append to the file.
/// </summary>
CsvConfiguration CSVconfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
// Don't write the header again.
HasHeaderRecord = false,
};
private int _Month;
/// <summary>
/// 月份信息 数据文件删除用
/// </summary>
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<DC10ModelMap>();
csv.WriteRecords(ListCacheESData);
}
}
}
catch (Exception ex)
{
LogService.Info($"时间:{DateTime.Now.ToString()}-【PwAnalyze-CycleAction】-{ex.Message}");
}
}
/// <summary>
/// 删除文件夹
/// 最多存两个月的数据
/// </summary>
/// <param name="dateTime"></param>
private void DeleteFile()
{
var dateTime = DateTime.Now;
var DateList = new List<DateTime>()
{
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}");
}
}
/// <summary>
/// 获取文件路径
/// </summary>
/// <param name="DcInfo"></param>
/// <returns></returns>
public static string GetFilePath(string FileRootPath, string Month, string Day)
{
return $@"{FileRootPath}\{DateTime.Now.ToString("yyyy")}\{DateTime.Now.ToString("yyyy")}-{Month}\{Day}\";
}
/// <summary>
/// 获取本地文件路径
/// </summary>
/// <param name="DcInfo"></param>
/// <returns></returns>
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";
}
/// <summary>
/// 获取CSV文件名称
/// </summary>
/// <param name="DcInfo"></param>
/// <returns></returns>
public static string GetFileName(string Month, string Day)
{
return $"{DateTime.Now.ToString("yyyy")}-{Month}-{Day}";
}
}
}