-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
1449 lines (1278 loc) · 45.7 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using CumulusMX;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
namespace CreateMissing
{
static class Program
{
public static Cumulus cumulus;
public static string location;
private static ConsoleColor defConsoleColour;
private static DayFile dayfile;
private static readonly List<string> CurrentLogLines = [];
private static string CurrentLogName;
private static int CurrentLogLineNum = 0;
private static readonly List<string> CurrentSolarLogLines = [];
private static string CurrentSolarLogName;
private static int CurrentSolarLogLineNum = 0;
private static int RecsAdded = 0;
private static int RecsUpdated = 0;
private static int RecsNoData = 0;
private static int RecsOK = 0;
private static double TotalChillHours;
static void Main()
{
#if DEBUG
//System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sl-SL")
#endif
TextWriterTraceListener myTextListener = new TextWriterTraceListener($"MXdiags{Path.DirectorySeparatorChar}CreateMissing-{DateTime.Now:yyyyMMdd-HHmmss}.txt", "CMlog");
Trace.Listeners.Add(myTextListener);
Trace.AutoFlush = true;
defConsoleColour = Console.ForegroundColor;
var fullVer = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
var version = $"{fullVer.Major}.{fullVer.Minor}.{fullVer.Build}";
LogMessage("CreateMissing v." + version);
Console.WriteLine("CreateMissing v." + version);
LogMessage("Processing started");
Console.WriteLine();
Console.WriteLine($"Processing started: {DateTime.Now:U}");
Console.WriteLine();
// get the location of the exe - we will assume this is in the Cumulus root folder
location = AppDomain.CurrentDomain.BaseDirectory;
cumulus = new Cumulus();
// load existing day file
dayfile = new DayFile();
// for each day since records began date
var currDate = cumulus.RecordsBeganDateTime;
var dayfileStart = dayfile.DayfileRecs.Count > 0 ? dayfile.DayfileRecs[0].Date : DateTime.MaxValue;
var endDate = SetStartTime(DateTime.Now.AddDays(-1).Date);
LogMessage($"First dayfile record: {dayfileStart:d}");
LogMessage($"Records Began Date : {currDate:d}");
Console.WriteLine($"First dayfile record: {dayfileStart:d}");
Console.WriteLine($"Records Began Date : {currDate:d}");
Console.WriteLine();
// Sanity check #1. Is the first date in the day file order than the records began date?
if (dayfileStart < currDate)
{
LogMessage($"The first dayfile record ({dayfileStart:d}) is older than the records began date ({currDate:d}), using that date");
Console.WriteLine($"The first dayfile record ({dayfileStart:d}) is older than the records began date ({currDate:d}), using that date");
currDate = dayfileStart;
}
if (!GetUserConfirmation($"This will attempt to create/update your day file records from {currDate:D}. Continue? [Y/N]: "))
{
Console.WriteLine("Exiting...");
Environment.Exit(1);
}
Console.WriteLine();
// Sanity check #2
if (currDate >= DateTime.Today)
{
LogMessage("Start date is today!???");
LogConsole("Start date is today!???", ConsoleColor.Cyan);
LogConsole("Press any key to exit", ConsoleColor.DarkYellow);
Console.ReadKey(true);
Console.WriteLine("Exiting...");
Environment.Exit(1);
}
// convert to meteo date if required.
currDate = SetStartTime(currDate);
for (var i = 0; i < dayfile.DayfileRecs.Count; i++)
{
// check if the day record exists in the day file?
if (dayfile.DayfileRecs[i].Date > currDate)
{
// Extract the Total Chill Hours from the last record we have to continue incrementing it
// First check if total chill hours needs to be reset
if (currDate.Month == cumulus.ChillHourSeasonStart && currDate.Day == 1)
{
TotalChillHours = 0;
}
else
{
// use whatever we have in the dayfile
TotalChillHours = dayfile.DayfileRecs[i].ChillHours;
// unless we don't have anything, then start at zero
if (TotalChillHours == -9999)
TotalChillHours = 0;
}
while (dayfile.DayfileRecs[i].Date > currDate)
{
// if not step through the monthly log file(s) to recreate it
// 9am rollover means we may have to process two files
LogMessage($"Date: {currDate:d} : Creating missing day entry ... ");
Console.Write($"Date: {currDate:d} : Creating missing day entry ... ");
var newRec = GetDayRecFromMonthly(currDate);
if (newRec == null)
{
LogMessage($"Date: {currDate:d} : No monthly data was found, not creating a record");
LogConsole("No monthly data was found, not creating a record", ConsoleColor.Yellow);
RecsNoData++;
}
else
{
newRec = GetSolarDayRecFromMonthly(currDate, newRec);
dayfile.DayfileRecs.Insert(i, newRec);
LogConsole("done.", ConsoleColor.Green);
RecsAdded++;
i++;
}
// step forward a day
currDate = IncrementMeteoDate(currDate);
// check if total chill hours needs to be reset
if (currDate.Month == cumulus.ChillHourSeasonStart && currDate.Day == 1)
{
TotalChillHours = 0;
}
// increment our index to allow for the newly inserted record
if (i >= dayfile.DayfileRecs.Count)
{
break;
}
}
// undo the last date increment in the while loop, it gets incremented in the main loop now
currDate = currDate.AddDays(-1);
i--;
}
else
{
// dayfile entry already exists, does it have the correct number of populated fields?
if (dayfile.DayfileRecs[i].HasMissingData())
{
AddMissingData(i, currDate);
}
else
{
LogMessage($"Date: {currDate:d} : Entry is OK");
Console.Write($"Date: {currDate:d} : ");
LogConsole("Entry is OK", ConsoleColor.Green);
RecsOK++;
}
}
currDate = IncrementMeteoDate(currDate);
// check if total chill hours needs to be reset
if (currDate.Month == cumulus.ChillHourSeasonStart && currDate.Day == 1)
{
TotalChillHours = 0;
}
if (currDate >= DateTime.Today)
{
// We don't do the future!
break;
}
}
currDate = IncrementMeteoDate(dayfile.DayfileRecs[^1].Date);
// We need the last total chill hours to increment if there are missing records at the end of the day file
// check if total chill hours needs to be reset
if (currDate.Month == cumulus.ChillHourSeasonStart && currDate.Day == 1)
{
TotalChillHours = 0;
}
else
{
TotalChillHours = dayfile.DayfileRecs[^1].ChillHours;
}
// that is the dayfile processed, but what if it had missing records at the end?
while (currDate <= endDate)
{
LogMessage($"Date: {currDate:d} : Creating missing day entry ... ");
Console.Write($"Date: {currDate:d} : Creating missing day entry ... ");
var newRec = GetDayRecFromMonthly(currDate);
if (newRec == null)
{
LogMessage($"Date: {currDate:d} : No monthly data was found, not creating a record");
LogConsole("No monthly data was found, not creating a record", ConsoleColor.Yellow);
RecsNoData++;
}
else
{
newRec = GetSolarDayRecFromMonthly(currDate, newRec);
dayfile.DayfileRecs.Add(newRec);
LogConsole("done.", ConsoleColor.Green);
RecsAdded++;
}
currDate = IncrementMeteoDate(currDate);
// check if total chill hours needs to be reset
if (currDate.Month == cumulus.ChillHourSeasonStart && currDate.Day == 1)
{
TotalChillHours = 0;
}
}
// create the new dayfile.txt with a different name
LogMessage("Saving new dayfile.txt");
Console.WriteLine();
Console.WriteLine("Saving new dayfile.txt");
dayfile.WriteDayFile();
LogMessage("Created new dayfile.txt, the old is saved as dayfile.txt.sav");
Console.WriteLine("Created new dayfile.txt, the original file has been saved as dayfile.txt.sav");
LogMessage($"Number of records added : {RecsAdded}");
LogMessage($"Number of records updated: {RecsUpdated}");
LogMessage($"Number of records No Data: {RecsNoData}");
LogMessage($"Number of records were OK: {RecsOK}");
Console.WriteLine();
Console.WriteLine($"Number of records processed: {RecsAdded + RecsUpdated + RecsNoData + RecsOK}");
Console.WriteLine($" Were OK: {RecsOK}");
Console.WriteLine($" Added : {RecsAdded}");
Console.WriteLine($" Updated: {RecsUpdated}");
LogConsole( $" No Data: {RecsNoData}", ConsoleColor.Red, false);
if (RecsNoData > 0)
{
LogConsole(" - please check the log file for the errors", ConsoleColor.Cyan);
}
else
{
Console.WriteLine();
}
LogMessage("Processing complete.");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Processing complete.");
LogConsole("Press any key to exit", ConsoleColor.DarkYellow);
Console.ReadKey(true);
}
public static void LogMessage(string message)
{
Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + message);
}
public static void LogConsole(string msg, ConsoleColor colour, bool newLine = true)
{
Console.ForegroundColor = colour;
if (newLine)
{
Console.WriteLine(msg);
}
else
{
Console.Write(msg);
}
Console.ForegroundColor = defConsoleColour;
}
private static Dayfilerec GetDayRecFromMonthly(DateTime date)
{
var rec = new Dayfilerec()
{
ET = 0,
SunShineHours = 0,
HighSolar = 0,
HighUv = 0,
HighHourlyRain = 0,
HeatingDegreeDays = 0,
CoolingDegreeDays = 0,
TotalRain = 0,
WindRun = 0,
ChillHours = 0
};
var inv = CultureInfo.InvariantCulture;
var started = false;
var finished = false;
var recCount = 0;
var idx = 0;
var lastentrydate = DateTime.MinValue;
var lasttempvalue = 0.0;
var startTime = date;
var endTime = IncrementMeteoDate(date);
var startTimeMinus1 = startTime.AddDays(-1);
// get the monthly log file name
var fileName = GetLogFileName(startTimeMinus1);
var fileDate = startTimeMinus1;
var rain1hLog = new Queue<LastHourRainLog>();
var rain24hLog = new Queue<LastHourRainLog>();
var totalwinddirX = 0.0;
var totalwinddirY = 0.0;
var totalMins = 0.0;
var totalTemp = 0.0;
// what do we deem to be too large a jump in the rainfall counter to be true? use 20 mm or 0.8 inches
var counterJumpTooBig = cumulus.Units.Rain == 0 ? 20 : 0.8;
var totalRainfall = 0.0;
var lastentryrain = 0.0;
var lastentrycounter = 0.0;
double rainThisHour;
double rainLast24Hr;
rec.Date = date;
// n-minute logfile. Fields are comma-separated:
// 0 Date in the form dd/mm/yy (the slash may be replaced by other characters)
// 1 Current time - hh:mm
// 2 Current temperature
// 3 Current humidity
// 4 Current dewpoint
// 5 Current wind speed
// 6 Recent (10-minute) high gust
// 7 Average wind bearing
// 8 Current rainfall rate
// 9 Total rainfall today so far
// 10 Current sea level pressure
// 11 Total rainfall counter as held by the station
// 12 Inside temperature
// 13 Inside humidity
// 14 Current gust (i.e. 'Latest')
// 15 Wind chill
// 16 Heat Index
// 17 UV Index
// 18 Solar Radiation
// 19 Evapotranspiration
// 20 Annual Evapotranspiration
// 21 Apparent temperature
// 22 Current theoretical max solar radiation
// 23 Hours of sunshine so far today
// 24 Current wind bearing
// 25 RG-11 rain total
// 26 Rain since midnight
// 27 Feels like
// 28 Humidex
while (!finished)
{
if (File.Exists(fileName))
{
// Have we determined the line endings for dayfile.txt yet?
if (dayfile.LineEnding == string.Empty)
{
Utils.TryDetectNewLine(fileName, out dayfile.LineEnding);
}
try
{
if (CurrentLogName != fileName)
{
LogMessage($"LogFile: Loading log file - {fileName}");
CurrentLogLines.Clear();
CurrentLogLines.AddRange(File.ReadAllLines(fileName));
CurrentLogName = fileName;
}
double valDbl;
int valInt;
CurrentLogLineNum = 0;
while (CurrentLogLineNum < CurrentLogLines.Count)
{
// we use idx 0 & 1 together (date/time), set the idx to 1
idx = 1;
// process each record in the file
// first a sanity check for an empty line!
if (string.IsNullOrWhiteSpace(CurrentLogLines[CurrentLogLineNum]))
{
CurrentLogLineNum++;
LogMessage($"LogFile: Error at line {CurrentLogLineNum}, an empty line was detected!");
continue;
}
//var st = new List<string>(Regex.Split(line, CultureInfo.CurrentCulture.TextInfo.ListSeparator))
// Regex is very expensive, let's assume the separator is always a single character
var st = new List<string>(CurrentLogLines[CurrentLogLineNum++].Split(','));
var entrydate = Utils.DdmmyyhhmmStrToDate(st[0], st[1]);
if (entrydate < startTimeMinus1)
continue;
// are we within 24 hours of the start time?
// if so initialise the 24 hour rain process
if (entrydate >= startTimeMinus1 && entrydate <= startTime)
{
// logging format changed on with C1 v1.9.3 b1055 in Dec 2012
// before that date the 00:00 log entry contained the rain total for the day before and the next log entry was reset to zero
// after that build the total was reset to zero in the entry
// messy!
// no final rainfall entry after this date (approx). The best we can do is add in the increase in rain counter during this preiod
var rain = double.Parse(st[9], inv); // 9
var raincounter = double.Parse(st[11], inv); // 11
// we need to initalise the rain counter on the first record
if (rain1hLog.Count == 0)
{
lastentrycounter = raincounter;
}
if (entrydate == startTime)
{
if (rain == 0 && (raincounter - lastentrycounter > 0) && (raincounter - lastentrycounter < counterJumpTooBig))
{
rain = lastentryrain + (raincounter - lastentrycounter) * cumulus.CalibRainMult;
}
else if (rain == 0)
{
rain = lastentryrain;
}
}
else if (entrydate == startTimeMinus1)
{
rain = 0;
}
AddLastHoursRainEntry(entrydate, raincounter, ref rain1hLog, ref rain24hLog);
lastentryrain = rain;
if (entrydate < startTime)
{
lastentrycounter = raincounter;
lastentrydate = entrydate;
continue;
}
}
// same meto day, or first record of the next day
// we want data from 00:00/09:00 to 00:00/09:00
// but next day 00:00/09:00 values are only used for summation functions and rainfall in x hours
if (entrydate >= startTime && entrydate <= endTime)
{
recCount++;
var outsidetemp = double.Parse(st[++idx], inv); // 2
var hum = int.Parse(st[++idx]); // 3
var dewpoint = double.Parse(st[++idx], inv); // 4
var speed = double.Parse(st[++idx], inv); // 5
var gust = double.Parse(st[++idx], inv); // 6
var avgbearing = int.Parse(st[++idx], inv); // 7
var rainrate = double.Parse(st[++idx], inv); // 8
var raintoday = double.Parse(st[++idx], inv); // 9
var pressure = double.Parse(st[++idx], inv); // 10
var raincounter = double.Parse(st[++idx], inv); // 11
if (!started)
{
lasttempvalue = outsidetemp;
lastentrydate = entrydate;
totalRainfall = lastentryrain;
started = true;
}
// Special case, the last record of the day is only used for averaging and summation purposes
if (entrydate != endTime)
{
// current gust
idx = 14;
if (st.Count > idx && double.TryParse(st[idx], inv, out valDbl) && valDbl > rec.HighGust)
{
rec.HighGust = valDbl;
rec.HighGustTime = entrydate;
idx = 24;
if (st.Count > idx && int.TryParse(st[idx], inv, out valInt))
{
rec.HighGustBearing = valInt;
}
else
{
rec.HighGustBearing = avgbearing;
}
}
// low chill
idx = 15;
if (st.Count > idx && double.TryParse(st[idx], inv, out valDbl) && valDbl < rec.LowWindChill)
{
rec.LowWindChill = valDbl;
rec.LowWindChillTime = entrydate;
}
// not logged, calculate it
else
{
var wchill = Utils.TempCToUser(MeteoLib.WindChill(Utils.UserTempToC(outsidetemp), Utils.UserWindToKPH(speed)));
if (wchill < rec.LowWindChill)
{
rec.LowWindChill = wchill;
rec.LowWindChillTime = entrydate;
}
}
// hi heat
idx = 16;
if (st.Count > idx && double.TryParse(st[idx], inv, out valDbl) && valDbl > rec.HighHeatIndex)
{
rec.HighHeatIndex = valDbl;
rec.HighHeatIndexTime = entrydate;
}
// not logged, calculate it
else
{
var heatIndex = Utils.TempCToUser(MeteoLib.HeatIndex(Utils.UserTempToC(outsidetemp), hum));
if (heatIndex > rec.HighHeatIndex)
{
rec.HighHeatIndex = heatIndex;
rec.HighHeatIndexTime = entrydate;
}
}
// hi/low appt
idx = 21;
if (st.Count > idx && double.TryParse(st[idx], inv, out valDbl))
{
if (valDbl > rec.HighAppTemp)
{
rec.HighAppTemp = valDbl;
rec.HighAppTempTime = entrydate;
}
if (valDbl < rec.LowAppTemp)
{
rec.LowAppTemp = valDbl;
rec.LowAppTempTime = entrydate;
}
}
// no logged apparent, calculate it
else
{
var apparent = Utils.TempCToUser(MeteoLib.ApparentTemperature(Utils.UserTempToC(outsidetemp), Utils.UserWindToMS(speed), hum));
if (apparent > rec.HighAppTemp)
{
rec.HighAppTemp = apparent;
rec.HighAppTempTime = entrydate;
}
if (apparent < rec.LowAppTemp)
{
rec.LowAppTemp = apparent;
rec.LowAppTempTime = entrydate;
}
}
// hi/low feels like
idx = 27;
if (st.Count > idx && double.TryParse(st[idx], inv, out valDbl))
{
if (valDbl > rec.HighFeelsLike)
{
rec.HighFeelsLike = valDbl;
rec.HighFeelsLikeTime = entrydate;
}
if (valDbl < rec.LowFeelsLike)
{
rec.LowFeelsLike = valDbl;
rec.LowFeelsLikeTime = entrydate;
}
}
// no logged feels like data available, calculate it
else
{
var feels = Utils.TempCToUser(MeteoLib.FeelsLike(Utils.UserTempToC(outsidetemp), Utils.UserWindToKPH(speed), hum));
if (feels > rec.HighFeelsLike)
{
rec.HighFeelsLike = feels;
rec.HighFeelsLikeTime = entrydate;
}
if (feels < rec.LowFeelsLike)
{
rec.LowFeelsLike = feels;
rec.LowFeelsLikeTime = entrydate;
}
}
// hi humidex
idx = 28;
if (st.Count > idx && double.TryParse(st[idx], inv, out valDbl))
{
if (valDbl > rec.HighHumidex)
{
rec.HighHumidex = valDbl;
rec.HighHumidexTime = entrydate;
}
}
// no logged humidex available, calculate it
else
{
var humidex = Utils.TempCToUser(MeteoLib.Humidex(Utils.UserTempToC(outsidetemp), hum));
if (humidex > rec.HighHumidex)
{
rec.HighHumidex = humidex;
rec.HighHumidexTime = entrydate;
}
}
// hi temp
if (outsidetemp > rec.HighTemp)
{
rec.HighTemp = outsidetemp;
rec.HighTempTime = entrydate;
}
// lo temp
if (outsidetemp < rec.LowTemp)
{
rec.LowTemp = outsidetemp;
rec.LowTempTime = entrydate;
}
// hi dewpoint
if (dewpoint > rec.HighDewPoint)
{
rec.HighDewPoint = dewpoint;
rec.HighDewPointTime = entrydate;
}
// low dewpoint
if (dewpoint < rec.LowDewPoint)
{
rec.LowDewPoint = dewpoint;
rec.LowDewPointTime = entrydate;
}
// hi hum
if (hum > rec.HighHumidity)
{
rec.HighHumidity = hum;
rec.HighHumidityTime = entrydate;
}
// lo hum
if (hum < rec.LowHumidity)
{
rec.LowHumidity = hum;
rec.LowHumidityTime = entrydate;
}
// hi baro
if (pressure > rec.HighPress)
{
rec.HighPress = pressure;
rec.HighPressTime = entrydate;
}
// lo hum
if (pressure < rec.LowPress)
{
rec.LowPress = pressure;
rec.LowPressTime = entrydate;
}
// hi gust
if (gust > rec.HighGust)
{
rec.HighGust = gust;
rec.HighGustTime = entrydate;
idx = 28;
if (st.Count > idx && int.TryParse(st[idx], out valInt))
{
rec.HighGustBearing = valInt;
}
else // have to use the average bearing
{
rec.HighGustBearing = avgbearing;
}
}
// hi wind
if (speed > rec.HighAvgWind)
{
rec.HighAvgWind = speed;
rec.HighAvgWindTime = entrydate;
}
// hi rain rate
if (rainrate > rec.HighRainRate)
{
rec.HighRainRate = rainrate;
rec.HighRainRateTime = entrydate;
}
// total rain - just take the last value - the user may have edited the value during the day
rec.TotalRain = raintoday * cumulus.CalibRainMult;
// add last hours rain - the first record of the day has already been added as the last record of the previous day
if (entrydate > startTime)
{
AddLastHoursRainEntry(entrydate, raincounter, ref rain1hLog, ref rain24hLog);
}
// rainfall in last hour
rainThisHour = Math.Round((rain1hLog.Last().Raincounter - rain1hLog.Peek().Raincounter) * cumulus.CalibRainMult, cumulus.Units.RainDPlaces);
if (rainThisHour > rec.HighHourlyRain)
{
rec.HighHourlyRain = rainThisHour;
rec.HighHourlyRainTime = entrydate;
}
// rainfall in last 24 hours
rainLast24Hr = Math.Round((rain24hLog.Last().Raincounter - rain24hLog.Peek().Raincounter) * cumulus.CalibRainMult, cumulus.Units.RainDPlaces);
if (rainLast24Hr > rec.HighRain24h)
{
rec.HighRain24h = rainLast24Hr;
rec.HighRain24hTime = entrydate;
}
// tot up wind run
rec.WindRun += entrydate.Subtract(lastentrydate).TotalHours * speed;
// average temp values
var intervalMins = entrydate.Subtract(lastentrydate).TotalMinutes;
totalMins += intervalMins;
totalTemp += intervalMins * (outsidetemp + lasttempvalue) / 2;
// dominate wind direction values
totalwinddirX += (speed * Math.Sin((avgbearing * (Math.PI / 180))));
totalwinddirY += (speed * Math.Cos((avgbearing * (Math.PI / 180))));
// heating/cooling degree days
if (outsidetemp < cumulus.NOAAheatingthreshold)
{
if (rec.HeatingDegreeDays == -9999)
{
rec.HeatingDegreeDays = 0;
}
rec.HeatingDegreeDays += (((cumulus.NOAAheatingthreshold - outsidetemp) * intervalMins) / 1440);
}
else if (outsidetemp > cumulus.NOAAcoolingthreshold)
{
if (rec.CoolingDegreeDays == -9999)
{
rec.CoolingDegreeDays = 0;
}
rec.CoolingDegreeDays += (((outsidetemp - cumulus.NOAAcoolingthreshold) * intervalMins) / 1440);
}
// chill hours
if (outsidetemp < cumulus.ChillHourThreshold)
{
TotalChillHours += intervalMins / 60.0;
}
rec.ChillHours = TotalChillHours;
lastentryrain = raintoday;
lastentrycounter = raincounter;
lasttempvalue = outsidetemp;
lastentrydate = entrydate;
continue;
}
else // we are outside the time range of the current day
{
// These values need to include the last record for completeness
// tot up wind run
rec.WindRun += entrydate.Subtract(lastentrydate).TotalHours * speed;
// average temp values
var intervalMins = entrydate.Subtract(lastentrydate).TotalMinutes;
totalMins += intervalMins;
totalTemp += intervalMins * (outsidetemp + lasttempvalue) / 2;
// dominant wind direction values
totalwinddirX += (speed * Math.Sin((avgbearing * (Math.PI / 180))));
totalwinddirY += (speed * Math.Cos((avgbearing * (Math.PI / 180))));
// heating/cooling degree days
if (outsidetemp < cumulus.NOAAheatingthreshold)
{
if (rec.HeatingDegreeDays == -9999)
{
rec.HeatingDegreeDays = 0;
}
rec.HeatingDegreeDays += (((cumulus.NOAAheatingthreshold - outsidetemp) * intervalMins) / 1440);
}
else if (outsidetemp > cumulus.NOAAcoolingthreshold)
{
if (rec.CoolingDegreeDays == -9999)
{
rec.CoolingDegreeDays = 0;
}
rec.CoolingDegreeDays += (((outsidetemp - cumulus.NOAAcoolingthreshold) * intervalMins) / 1440);
}
// chill hours
if (outsidetemp < cumulus.ChillHourThreshold)
{
TotalChillHours += intervalMins / 60.0;
}
rec.ChillHours = TotalChillHours;
// logging format changed on with C1 v1.9.3 b1055 in Dec 2012
// before that date the 00:00 log entry contained the rain total for the day before and the next log entry was reset to zero
// after that build the total was reset to zero in the 00:00 entry
// messy!
// no final rainfall entry after this date (approx). The best we can do is add in the increase in rain counter during this preiod
//var rolloverRain = double.Parse(st[9]); // 9 - rain so far today
var rolloverRaincounter = double.Parse(st[11], inv); // 11 - rain counter
rec.TotalRain += (rolloverRaincounter - lastentrycounter) * cumulus.CalibRainMult;
//if (rolloverRain > 0)
//{
// raintoday = lastentryrain + rolloverRain;
//}
//if (rolloverRain == 0 && (raincounter - lastentrycounter > 0) && (raincounter - lastentrycounter < counterJumpTooBig))
//{
// raintoday += (raincounter - lastentrycounter) * cumulus.CalibRainMult;
//}
// add last hours rain for this last record.
AddLastHoursRainEntry(entrydate, rolloverRaincounter, ref rain1hLog, ref rain24hLog);
// rainfall in last hour
rainThisHour = Math.Round((rain1hLog.Last().Raincounter - rain1hLog.Peek().Raincounter) * cumulus.CalibRainMult, cumulus.Units.RainDPlaces);
if (rainThisHour > rec.HighHourlyRain)
{
rec.HighHourlyRain = rainThisHour;
rec.HighHourlyRainTime = entrydate;
}
rainLast24Hr = Math.Round((rain24hLog.Last().Raincounter - rain24hLog.Peek().Raincounter) * cumulus.CalibRainMult, cumulus.Units.RainDPlaces);
if (rainLast24Hr > rec.HighRain24h)
{
rec.HighRain24h = rainLast24Hr;
rec.HighRain24hTime = entrydate.AddMinutes(-1); // we want the high rate for the day to be at the end of the day we are closing
}
// total rain
totalRainfall += rec.TotalRain;
lastentrycounter = raincounter;
// flag we are done with this record
finished = true;
}
}
if (started && recCount >= 5) // need at least five records to create a day
{
// we were in the right day, now we aren't
// calc average temp for the day, edge case we only have one record, in which case the totals will be zero, use hi or lo temp, they will be the same!
rec.AvgTemp = totalMins > 0 ? totalTemp / totalMins : rec.HighTemp;
// calc dominant wind direction for the day
rec.DominantWindBearing = Utils.CalcAvgBearing(totalwinddirX, totalwinddirY);
return rec;
}
else if (started && recCount <= 5)
{
// Oh dear, we have done the day and have less than five records
return null;
}
else if (!started && entrydate > endTime)
{
// We didn't find any data
return null;
}
lastentrydate = entrydate;
} // end while
}
catch (Exception e)
{
LogMessage($"LogFile: Error at line {CurrentLogLineNum}, field {idx + 1} of {fileName} : {e.Message}");
LogMessage("LogFile: Please edit the file to correct the error");
LogMessage("LogFile: Line = " + CurrentLogLines[CurrentLogLineNum - 1]);
LogConsole($"Error at line {CurrentLogLineNum}, field {idx + 1} of {fileName} : {e.Message}", ConsoleColor.Red);
LogConsole("Please edit the file to correct the error", ConsoleColor.Red);
Environment.Exit(1);
}
}
else
{
LogMessage($"LogFile: Log file not found - {fileName}");
// have we run out of log files without finishing the current day?
if (started && !finished)
{
// yes we have, so do the final end of day stuff now
// calc average temp for the day, edge case we only have one record, in which case the totals will be zero, use hi or lo temp, they will be the same!
rec.AvgTemp = totalMins > 0 ? totalTemp / totalMins : rec.HighTemp;
// calc dominant wind direction for the day
rec.DominantWindBearing = Utils.CalcAvgBearing(totalwinddirX, totalwinddirY);
return rec;
}
}
if (fileDate > date)
{
finished = true;
LogMessage("LogFile: Finished processing all log files");
}
else
{
LogMessage($"LogFile: Finished processing log file - {fileName}");
fileDate = fileDate.AddMonths(1);
fileName = GetLogFileName(fileDate);
}
}
if (started)
return rec;
else
return null;
}
private static Dayfilerec GetSolarDayRecFromMonthly(DateTime date, Dayfilerec rec)
{
var started = false;
var finished = false;
var fileDate = date;
var startTime = date;
var endTime = IncrementMeteoDate(date);
var solarStartTime = startTime;
var solarEndTime = endTime;
// total sunshine is a pain for meteo days starting at 09:00 because we need to total to midnight only
// starting at 00:01 on the meteo day
if (startTime.Hour != 0)
{
solarStartTime = startTime.Date;
solarEndTime = solarStartTime.AddDays(1);
}
// get the monthly log file name
var fileName = GetLogFileName(solarStartTime);
// n-minute logfile. Fields are comma-separated:
// 0 Date in the form dd/mm/yy (the slash may be replaced by a dash in some cases)
// 1 Current time - hh:mm
// 2 Current temperature
// 3 Current humidity
// 4 Current dewpoint
// 5 Current wind speed
// 6 Recent (10-minute) high gust
// 7 Average wind bearing
// 8 Current rainfall rate
// 9 Total rainfall today so far
// 10 Current sea level pressure
// 11 Total rainfall counter as held by the station
// 12 Inside temperature
// 13 Inside humidity
// 14 Current gust (i.e. 'Latest')
// 15 Wind chill
// 16 Heat Index
// 17 UV Index
// 18 Solar Radiation
// 19 Evapotranspiration
// 20 Annual Evapotranspiration
// 21 Apparent temperature
// 22 Current theoretical max solar radiation
// 23 Hours of sunshine so far today
// 24 Current wind bearing
// 25 RG-11 rain total
// 26 Rain since midnight
// 27 Feels like
// 28 Humidex