using System; using System.Linq; using System.Threading.Tasks; using GenCycleVDP.Resources; using DbCycleVDP; namespace GenCycleVDP { internal class GenCycle(int vdp) { private readonly int vdp = vdp; private CycleStatus currCycle = CycleStatus.EndTechCycle; private DateTime factStart = DateTime.Now; private DateTime factEnd = DateTime.Now; private DateTime thinkEnd = DateTime.Now; private bool cycle = false; private Task taskCycle = Task.CompletedTask; public void Start() { cycle = true; taskCycle = this.Cycle(); } public void Stop() { cycle = false; taskCycle.Wait(); } async public Task Cycle() { while (cycle) { if (GetCurrCycle()) //Can get info form DB. { if (DateTime.Now >= factEnd) { GetNextCycle(); GetTimeStart(); GetTimeThinkEnd(); GetTimeFactEnd(); while (!SaveToDB()) { Console.WriteLine("VDP " + vdp.ToString("D2") + ": Can't connect to DB."); await Task.Delay(5000); } } } else //It's new Cycle. { GetTimeStart(); GetTimeThinkEnd(); GetTimeFactEnd(); while (!SaveToDB()) { Console.WriteLine("VDP " + vdp.ToString("D2") + ": Can't connect to DB."); await Task.Delay(5000); } } while (cycle && (DateTime.Now < factEnd)) { var secAwait = (factEnd - DateTime.Now).TotalSeconds; if (secAwait >= 5) { await Task.Delay(5000); } else { await Task.Delay(Convert.ToInt32(Math.Ceiling(secAwait)) * 1000); } } } } public bool GetCurrCycle() { try { using var db = new DbFurnace(); var tmp = (from u in db.Cycles where u.NumVdp == vdp orderby u.FactStart descending select u).FirstOrDefault(); if (tmp == null) { currCycle = CycleStatus.EndTechCycle; return false; } currCycle = Enum.IsDefined(typeof(CycleStatus), tmp.NumCycle) ? (CycleStatus)tmp.NumCycle : CycleStatus.EndTechCycle; factStart = tmp.FactStart; factEnd = tmp.FactEnd; } catch (Exception e) { Console.WriteLine(e.Message); return false; } return true; } public void GetNextCycle() { currCycle = GenData.GetNextCycle(currCycle); } public void GetTimeStart() { factStart = factEnd; } public void GetTimeThinkEnd() { thinkEnd = factStart.AddMinutes(GenData.GetDuration(currCycle)); } public void GetTimeFactEnd() { factEnd = thinkEnd.AddSeconds(GenData.GetDeviation(currCycle)); } public bool SaveToDB() { try { using var db = new DbFurnace(); var tmp = new TableCycle() { NumVdp = vdp, NumCycle = (int)currCycle, FactStart = factStart, FactEnd = factEnd, ThinkEnd = thinkEnd }; db.Cycles.Add(tmp); db.SaveChanges(); } catch (Exception e) { Console.WriteLine(e.Message); return false; } return true; } public string GetStatus() { return vdp.ToString("D2") + "-" + currCycle.ToString(); } } }