-
Notifications
You must be signed in to change notification settings - Fork 2
/
sensorsManager.cs
1475 lines (1137 loc) · 46.4 KB
/
sensorsManager.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
/*
* Yocto-Visualization, a free application to visualize Yoctopuce Sensors.
*
* Sensor abstraction class
*
*
* - - - - - - - - - License information: - - - - - - - - -
*
* Copyright (C) 2017 and beyond by Yoctopuce Sarl, Switzerland.
*
* Yoctopuce Sarl (hereafter Licensor) grants to you a perpetual
* non-exclusive license to use, modify, copy and integrate this
* file into your software for the sole purpose of interfacing
* with Yoctopuce products.
*
* You may reproduce and distribute copies of this file in
* source or object form, as long as the sole purpose of this
* code is to interface with Yoctopuce products. You must retain
* this notice in the distributed source file.
*
* You should refer to Yoctopuce General Terms and Conditions
* for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO
* EVENT SHALL LICENSOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
* COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR
* SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT
* LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
* CONTRIBUTION, OR OTHER SIMILAR COSTS, WHETHER ASSERTED ON THE
* BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE), BREACH OF
* WARRANTY, OR OTHERWISE.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading;
using System.Xml;
using System.Diagnostics;
namespace YoctoVisualisation
{
public class TimedSensorValue
{
public double DateTime { get; set; }
public double Value { get; set; }
}
public class NullYSensor : CustomYSensor
{
public NullYSensor() : base(null, "",null)
{
hwdName = "NOTAREALSENSOR";
friendlyname = "NOTAREALSENSOR";
}
public new string get_unit() { return ""; }
public new void registerCallback(Form f) { }
public new void forceUpdate() { }
public new string get_frequency() { return ""; }
public new void set_frequency(string frequencyToSet) { }
public new YSensor get_sensor() { return null; }
public override string ToString() { return "(none)"; }
public override void setAlarmCondition(int index, int condition) { }
public override int getAlarmCondition(int index) { return 0; }
public override void setAlarmValue(int index,double value) { }
public override double getAlarmValue(int index) { return 0; }
public override void setAlarmDelay(int index, int value) { }
public override int getAlarmDelay(int index) { return 0; }
public override void setAlarmCommandline(int index, string value) { }
public override string getAlarmCommandline(int index) { return ""; }
}
public class AlarmSettings
{ int index;
int Condition = 0;
int Source = 0;
double Value = 0;
int Delay = 15;
string Commandline = "";
CustomYSensor parent;
DateTime lastAlarm = DateTime.MinValue;
static void ExecuteCommand(string source, string command)
{
string shell = "cmd.exe";
string shellcommand = "/c " + command;
if (constants.MonoRunning) { shell = "bash"; shellcommand = "-c \"" + command + "\""; }
LogManager.Log(source + " executing :" + shell + " " + shellcommand);
var processInfo = new ProcessStartInfo(shell, shellcommand);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
try
{
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
LogManager.Log(source + " output :" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
LogManager.Log(source + " error : " + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
// Console.WriteLine(source + " ExitCode: " + process.ExitCode.ToString());
process.Close();
}
catch (Exception e)
{
LogManager.Log(source + " execution raised an exception :" + e.Message);
}
}
public AlarmSettings(int index, CustomYSensor owner, XmlNode xmldata)
{
this.index = index;
parent = owner;
if (xmldata != null)
{
Source = int.Parse(xmldata.Attributes["Source"].InnerText);
Condition = int.Parse(xmldata.Attributes["Condition"].InnerText);
Value = double.Parse(xmldata.Attributes["Value"].InnerText);
Commandline = xmldata.Attributes["Cmd"].InnerText;
Delay = int.Parse(xmldata.Attributes["Delay"].InnerText);
}
}
public AlarmSettings(int index, CustomYSensor owner)
: this(index, owner, null) { }
public string getXmlData()
{ return "<Alarm "
+ "Source=\"" + Source.ToString() + "\" "
+ "Condition=\"" + Condition.ToString() + "\" "
+ "Value=\"" + Value.ToString() + "\" "
+ "Cmd=\"" + System.Security.SecurityElement.Escape(Commandline) + "\" "
+ "Delay=\"" + Delay.ToString() + "\"/>\n";
}
public void setCondition( int condition) { this.Condition = condition; }
public int getCondition() { return this.Condition; }
public void setSource(int source) { this.Source = source; }
public int getSource() { return this.Source; }
public void setValue( double value) { this.Value = value; }
public double getValue() { return this.Value; }
public void setDelay( int value) { this.Delay = value; }
public int getDelay() { return this.Delay; }
public void setCommandline( string value) { this.Commandline = value; }
public string getCommandline() { return this.Commandline; }
public void check(YMeasure m )
{ bool alarm = false;
string reason = "";
string src = "";
double SensorValue = 0;
switch (Source)
{
case 1: src = "MIN"; SensorValue = m.get_minValue(); break;
case 2: src = "MAX"; SensorValue = m.get_maxValue(); break;
default: src = "AVG"; SensorValue = m.get_averageValue(); break;
}
switch (Condition)
{ default : return; // alarm disabled
case 1: reason = ">"; if (SensorValue > Value) alarm = true;break;
case 2: reason = ">="; if (SensorValue >= Value) alarm = true; break;
case 3: reason = "="; if (SensorValue == Value) alarm = true; break;
case 4: reason = "<="; if (SensorValue <= Value) alarm = true; break;
case 5: reason = "<"; if (SensorValue < Value) alarm = true; break;
}
if (!alarm) return;
if (((DateTime.Now - lastAlarm).TotalSeconds) < Delay) return;
string source = "ALARM " + (index + 1).ToString();
LogManager.Log(source+" on " + parent.get_hardwareId() + "/" + parent.get_friendlyName() + " (" + SensorValue.ToString() + reason + Value.ToString() + ")");
string Execute = Commandline;
Execute = Execute.Replace("$SENSORVALUE$", SensorValue.ToString());
Execute = Execute.Replace("$HWDID$", parent.get_hardwareId());
Execute = Execute.Replace("$NAME$", parent.get_friendlyName());
Execute = Execute.Replace("$UNIT$", parent.get_unit());
Execute = Execute.Replace("$CONDITION$", reason);
Execute = Execute.Replace("$DATATYPE$", src);
Execute = Execute.Replace("$TRIGGER$", Value.ToString());
Execute = Execute.Replace("$NOW$", DateTime.Now.ToString("yyyy/MM/dd h:mm:ss.ff"));
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
ExecuteCommand(source,Execute);
}).Start();
lastAlarm = DateTime.Now;
}
}
public class CustomYSensor
{
private class DataLoggerBoundary
{ private double _start=0;
private double _stop = 0;
public DataLoggerBoundary(double start, double stop) { _start = start; _stop = stop; }
public double start { get { return _start; } }
public double stop { get { return _stop; } }
}
YSensor sensor;
protected string hwdName;
protected string friendlyname;
string unit = "";
string frequency = "";
double resolution = 1;
bool recording = false;
private List<Form> FormsToNotify;
bool online = false;
bool preloadDone = false;
bool loadDone = false;
bool dataLoggerFeature = false;
private readonly Mutex dataMutex = new Mutex();
bool cfgChgNotificationsSupported = false;
bool mustReloadConfig = false;
bool mustCheckForSuspicionTimeStamps = false;
int ignoredSuspicionTimeStampsCount = 0;
// private bool _isReadOnly = false;
public bool isReadOnly { get { if (sensor != null) return sensor.isReadOnly(); else return true; } }
ulong lastGetConfig = 0;
int recordedDataLoadProgress = 0;
YDataSet recordedData = null;
bool loadFailed = false;
double firstLiveDataTimeStamp = 0;
double firstDataloggerTimeStamp = 0;
double lastDataTimeStamp = 0;
string lastDataSource = "";
int consecutiveBadTimeStamp = 0;
int globalDataLoadProgress = 0;
public List<TimedSensorValue> minData = new List<TimedSensorValue>();
public List<TimedSensorValue> curData = new List<TimedSensorValue>();
public List<TimedSensorValue> maxData = new List<TimedSensorValue>();
public List<TimedSensorValue> previewMinData;
public List<TimedSensorValue> previewCurData;
public List<TimedSensorValue> previewMaxData;
double _lastAvgValue = Double.NaN;
double _lastMinValue = Double.NaN;
double _lastMaxValue = Double.NaN;
BackgroundWorker predloadProcess;
BackgroundWorker loadProcess;
long dataLoggerStartReadTime = 0;
List<AlarmSettings> Alarms = new List<AlarmSettings>();
private static int _MaxDataRecords = 0;
public static int MaxDataRecords
{
get { return _MaxDataRecords; }
set { _MaxDataRecords = value; }
}
private static int _MaxLoggerRecords = 0;
public static int MaxLoggerRecords
{
get { return _MaxLoggerRecords; }
set { _MaxLoggerRecords = value; }
}
public double get_lastAvgValue()
{
if (online) return _lastAvgValue;
return Double.NaN;
}
public double get_lastMaxValue()
{
if (online) return _lastMaxValue;
return Double.NaN;
}
public double get_lastMinValue()
{
if (online) return _lastMinValue;
return Double.NaN;
}
public void ConfigHasChanged()
{
cfgChgNotificationsSupported = true;
mustReloadConfig = true;
}
public CustomYSensor(YSensor s, string name, XmlNode SensorLocalConfig)
{
FormsToNotify = new List<Form>();
sensor = s;
hwdName = name;
friendlyname = name;
if (s == null) return;
predloadProcess = new BackgroundWorker();
predloadProcess.DoWork += new DoWorkEventHandler(preload_DoWork);
predloadProcess.RunWorkerCompleted += new RunWorkerCompletedEventHandler(preload_Completed);
predloadProcess.ProgressChanged += new ProgressChangedEventHandler(load_ProgressChanged);
loadProcess = new BackgroundWorker();
loadProcess.WorkerReportsProgress = true;
loadProcess.WorkerSupportsCancellation = true;
loadProcess.DoWork += new DoWorkEventHandler(load_DoWork);
loadProcess.RunWorkerCompleted += new RunWorkerCompletedEventHandler(load_Completed);
loadProcess.ProgressChanged += new ProgressChangedEventHandler(load_ProgressChanged);
if (s.isOnline())
{
hwdName = s.get_hardwareId();
friendlyname = s.get_friendlyName();
configureSensor();
if (this.isReadOnly) LogManager.Log(hwdName + " is read only");
online = true;
// loadDatalogger(); // will be done automatically at device arrival
}
if (SensorLocalConfig != null)
{
int index = 0;
foreach (XmlNode n in SensorLocalConfig)
{
if (n.Name == "Alarm")
{
checkAlarmIndex(index);
Alarms[index] =new AlarmSettings(index, this, n);
index++;
}
}
}
}
private void checkAlarmIndex(int index)
{ while (Alarms.Count < index + 1) Alarms.Add(new AlarmSettings(Alarms.Count, this));
}
public int getAlarmCount()
{
return Alarms.Count;
}
public virtual void setAlarmCondition(int index,int condition) { checkAlarmIndex(index); this.Alarms[index].setCondition( condition); }
public virtual int getAlarmCondition(int index) { checkAlarmIndex(index); return this.Alarms[index].getCondition(); }
public virtual void setAlarmSource(int index, int source) { checkAlarmIndex(index); this.Alarms[index].setSource(source); }
public virtual int getAlarmSource(int index) { checkAlarmIndex(index); return this.Alarms[index].getSource(); }
public virtual void setAlarmValue(int index, double value) { checkAlarmIndex(index); this.Alarms[index].setValue(value); }
public virtual double getAlarmValue(int index) { checkAlarmIndex(index); return this.Alarms[index].getValue(); }
public virtual void setAlarmDelay(int index, int value) { checkAlarmIndex(index); this.Alarms[index].setDelay( value); }
public virtual int getAlarmDelay(int index) { checkAlarmIndex(index); return this.Alarms[index].getDelay(); }
public virtual void setAlarmCommandline(int index, string value) { checkAlarmIndex(index); this.Alarms[index].setCommandline( value); }
public virtual string getAlarmCommandline(int index) { checkAlarmIndex(index); return this.Alarms[index].getCommandline(); }
public string GetXmlData()
{ string res = "<Sensor ID=\"" + get_hardwareId() + "\">\n";
for (int i = 0; i < getAlarmCount(); i++)
res = res + Alarms[i].getXmlData();
res = res + "</Sensor>\n";
return res;
}
public int getGetaLoadProgress() { return globalDataLoadProgress; }
public double get_firstLiveDataTimeStamp()
{ return firstLiveDataTimeStamp; }
public double get_firstDataloggerTimeStamp()
{ return firstDataloggerTimeStamp; }
public double get_lastDataTimeStamp()
{ return lastDataTimeStamp; }
protected void preload_DoWork(object sender, DoWorkEventArgs e)
{
DataLoggerBoundary arg = (DataLoggerBoundary)(e.Argument);
LogManager.Log(hwdName + ": preloading data from " + arg.start.ToString() + " to "+ arg.stop.ToString() +"(delta= "+(arg.stop- arg.start).ToString("F3")+")");
recordedData = sensor.get_recordedData(arg.start, arg.stop );
try
{
recordedDataLoadProgress = recordedData.loadMore();
}
catch (Exception ex) { LogManager.Log(hwdName + ": load more caused an exception " + ex.ToString()); }
globalDataLoadProgress = recordedDataLoadProgress;
List<YMeasure> measures = recordedData.get_preview();
previewMinData = new List<TimedSensorValue>();
previewCurData = new List<TimedSensorValue>();
previewMaxData = new List<TimedSensorValue>();
int startIndex = 0;
if ((_MaxDataRecords > 0) && (measures.Count > _MaxDataRecords)) startIndex = measures.Count - _MaxDataRecords;
for (int i = startIndex; i < measures.Count; i++)
{
double t = measures[i].get_endTimeUTC();
if ((t>= arg.start) && (t <= arg.stop)) // returned dataset might be slightly larger than what we asked for
{
previewMinData.Add(new TimedSensorValue { DateTime = t, Value = measures[i].get_minValue() });
previewCurData.Add(new TimedSensorValue { DateTime = t, Value = measures[i].get_averageValue() });
previewMaxData.Add(new TimedSensorValue { DateTime = t, Value = measures[i].get_maxValue() });
}
}
if (previewCurData.Count > 1)
{
LogManager.Log(hwdName + ": preloaded data from " + previewCurData[0].DateTime.ToString() + " to " + previewCurData[previewCurData.Count - 1].DateTime.ToString());
if ((_MaxLoggerRecords > 0) && (arg.start == 0))
{ // find out where to start reading datalogger to make sure we don't read more the _MaxLoggerRecords records
// tested only when loading initial data (arg.start==0)
List<YDataStream> list = recordedData.get_privateDataStreams();
int index = list.Count - 1;
int totalRecords = 0;
while ((index > 0) && (totalRecords < _MaxLoggerRecords))
{
totalRecords += list[index].get_rowCount();
dataLoggerStartReadTime = list[index].get_startTimeUTC();
index--;
}
int n = 0;
while ((n < previewMinData.Count) && (previewMinData[n].DateTime < dataLoggerStartReadTime)) n++;
if (n > 1)
{
previewMinData.RemoveRange(0, n - 1);
previewCurData.RemoveRange(0, n - 1);
previewMaxData.RemoveRange(0, n - 1);
}
}
}
// pass the start stop parameter to the preload_Completed
e.Result = e.Argument;
}
protected void findMergeBoundaries(List<TimedSensorValue> previewMinData, out int MergeSourceStart, out int MergeSourceStop)
{
MergeSourceStart = 0;
MergeSourceStop = 0;
if (minData.Count > 0)
{
while ((MergeSourceStart < minData.Count) && (previewMinData[0].DateTime > minData[MergeSourceStart].DateTime)) MergeSourceStart++;
MergeSourceStop = MergeSourceStart;
while ((MergeSourceStop < minData.Count) && (previewMinData[previewMinData.Count - 1].DateTime >= minData[MergeSourceStop].DateTime)) MergeSourceStop++;
}
}
protected void preload_Completed(object sender, RunWorkerCompletedEventArgs e)
{
LogManager.Log(hwdName + " : datalogger preloading completed (" + previewMinData.Count + " rows )");
/*
string s = "";
for (int j = 0; j < curData.Count; j++)
s += curData[j].DateTime.ToString() + " ; " + curData[j].Value.ToString() + "\r\n";
System.IO.File.WriteAllText("C:\\tmp\\data-before.csv", s);
*/
if (previewMinData == null) return;
if (previewMinData.Count > 1) // make sure there is enough data not enough data for rendering
{
int MergeSourceStart = 0;
int MergeSourceStop = 0;
// find out where datalogger data fit in the already there data
findMergeBoundaries(previewMinData, out MergeSourceStart, out MergeSourceStop);
/*
s = "";
for (int j = 0; j < curData.Count; j++)
s += previewCurData[j].DateTime.ToString() + " ; " + previewCurData[j].Value.ToString() + "\r\n";
System.IO.File.WriteAllText("C:\\tmp\\datalogger.csv", s);
*/
// insert loaded data in current data
dataMutex.WaitOne();
minData.RemoveRange(MergeSourceStart, MergeSourceStop - MergeSourceStart);
minData.InsertRange(MergeSourceStart, previewMinData);
curData.RemoveRange(MergeSourceStart, MergeSourceStop - MergeSourceStart);
curData.InsertRange(MergeSourceStart, previewCurData);
maxData.RemoveRange(MergeSourceStart, MergeSourceStop - MergeSourceStart);
maxData.InsertRange(MergeSourceStart, previewMaxData);
dataMutex.ReleaseMutex();
/*
s = "MergeStart = "+ MergeStart.ToString()+ "; MergeStop= " + MergeStop.ToString() + "\r\n"; ;
for (int j=0;j< curData.Count;j++)
s += curData[j].DateTime.ToString() + " ; " + curData[j].Value.ToString() + "\r\n";
System.IO.File.WriteAllText("C:\\tmp\\data-after.csv", s);
*/
foreach (Form f in FormsToNotify)
if (f is GraphForm)
((GraphForm)f).SensorNewDataBlock(this, MergeSourceStart, MergeSourceStart + previewMinData.Count-1, 0, true);
}
int count = curData.Count;
if (count > 0)
if (curData[count - 1].DateTime > lastDataTimeStamp)
{
lastDataTimeStamp = curData[count - 1].DateTime;
lastDataSource = "last preload timestamp";
}
// if (recordedDataLoadProgress < 100)
{
LogManager.Log(hwdName + " : start datalogger loading");
loadProcess.RunWorkerAsync(e.Result); // e.result contains the start stop parameters
}
}
public string get_frequency()
{
if (online)
{
if (sensor.isOnline())
{
frequency = sensor.get_reportFrequency();
return frequency;
}
else online = false;
}
return "";
}
public void set_frequency(string frequencyToSet)
{
if (online)
{
if (sensor.isOnline())
{
frequency = frequencyToSet;
sensor.set_reportFrequency(frequency);
string lfreq = sensor.get_logFrequency();
try
{
if (lfreq != "OFF") sensor.set_logFrequency(frequency);
sensor.get_module().saveToFlash();
} catch (Exception e)
{
LogManager.Log("failed to change "+hwdName + " log frequency (" + e.Message+")");
}
}
else online = false;
}
}
public bool get_recording()
{
if (!dataLoggerFeature) return false;
if (online)
{
if (sensor.isOnline())
{
recording = sensor.get_logFrequency() != "OFF";
return recording;
}
else online = false;
}
return false;
}
public void set_recording(bool recordingStatus)
{
if (!dataLoggerFeature) return;
if (online)
{
if (sensor.isOnline())
{
recording = recordingStatus;
try
{
sensor.set_logFrequency(recording ? frequency : "OFF");
YDataLogger dl = YDataLogger.FindDataLogger(sensor.get_module().get_serialNumber() + ".dataLogger");
dl.set_recording(recording ? YDataLogger.RECORDING_ON : YDataLogger.RECORDING_OFF);
dl.set_autoStart(recording ? YDataLogger.AUTOSTART_ON : YDataLogger.RECORDING_OFF);
sensor.get_module().saveToFlash();
}
catch (Exception e)
{
LogManager.Log("failed to change " + hwdName + " recording (" + e.Message + ")");
}
}
else online = false;
}
}
protected void load_DoWork(object sender, DoWorkEventArgs e)
{
DataLoggerBoundary arg = (DataLoggerBoundary)(e.Argument);
LogManager.Log(hwdName + " loading main data from datalogger");
if (dataLoggerStartReadTime>0)
{
recordedData = sensor.get_recordedData(dataLoggerStartReadTime, 0);
}
while (recordedDataLoadProgress < 100)
{
if ((((BackgroundWorker)sender).CancellationPending == true))
{
globalDataLoadProgress = 100;
loadDone = true;
loadFailed = false;
e.Cancel = true;
break;
}
try
{
recordedDataLoadProgress = recordedData.loadMore();
//LogManager.Log(hwdName + " loading " + recordedDataLoadProgress.ToString() + "%");
}
catch (Exception) { loadFailed = true; return; }
if (globalDataLoadProgress != (int)(recordedDataLoadProgress))
{
globalDataLoadProgress = (int)(recordedDataLoadProgress);
((BackgroundWorker)sender).ReportProgress(globalDataLoadProgress);
}
}
List<YMeasure> measures = recordedData.get_measures();
previewMinData = new List<TimedSensorValue>();
previewCurData = new List<TimedSensorValue>();
previewMaxData = new List<TimedSensorValue>();
for (int i = 0; i < measures.Count; i++)
{
double t = measures[i].get_endTimeUTC();
if ((t>=arg.start) && (t<=arg.stop)) // trust no one!
if ( (previewMinData.Count == 0) || (t > previewMinData[previewMinData.Count - 1].DateTime) )
{
previewMinData.Add(new TimedSensorValue { DateTime = t, Value = measures[i].get_minValue() });
previewCurData.Add(new TimedSensorValue { DateTime = t, Value = measures[i].get_averageValue() });
previewMaxData.Add(new TimedSensorValue { DateTime = t, Value = measures[i].get_maxValue() });
}
}
if (_MaxDataRecords > 0) previewDataCleanUp();
for (int i = 0; i < previewMinData.Count - 1; i++)
{
if (previewMinData[i].DateTime >= previewMinData[i + 1].DateTime)
throw new Exception("Time-stamp inconsistency");
}
if (previewCurData.Count > 1)
LogManager.Log(hwdName + " loaded " + previewCurData.Count.ToString() + "/" + measures.Count.ToString() + " records over " + (previewCurData[previewCurData.Count - 1].DateTime - previewCurData[0].DateTime).ToString("F3") + " sec");
else
LogManager.Log(hwdName + " loaded " + previewCurData.Count.ToString() + " records");
if (previewMinData.Count > 2)
{
globalDataLoadProgress = 100;
dataMutex.WaitOne();
double lastPreviewTimeStamp = previewMinData[previewMinData.Count - 1].DateTime;
//while ((index < minData.Count) && (minData[index].DateTime < lastPreviewTimeStamp)) index++;
//LogManager.Log(hwdName + " time range is ["+constants.UnixTimeStampToDateTime(previewMinData[0].DateTime)+".."+ constants.UnixTimeStampToDateTime(lastPreviewTimeStamp)+"]");
int MergeSourceStart;
int MergeSourceStop;
// find out where datalogger data fit in the already there data
findMergeBoundaries(previewMinData, out MergeSourceStart, out MergeSourceStop);
int recordcount = MergeSourceStop - MergeSourceStart;
minData.RemoveRange(MergeSourceStart, recordcount);
curData.RemoveRange(MergeSourceStart, recordcount);
maxData.RemoveRange(MergeSourceStart, recordcount);
minData.InsertRange(MergeSourceStart, previewMinData);
curData.InsertRange(MergeSourceStart, previewCurData);
maxData.InsertRange(MergeSourceStart, previewMaxData);
dataMutex.ReleaseMutex();
firstDataloggerTimeStamp = curData[0].DateTime;
}
loadDone = true;
loadFailed = false;
int count = curData.Count;
if (count > 0)
if (curData[count - 1].DateTime > lastDataTimeStamp)
{
lastDataTimeStamp = curData[count - 1].DateTime;
lastDataSource = "end of datalogger";
}
e.Result = e.Argument; // pass the start stop argument to load_Completed;
}
protected void load_Completed(object sender, RunWorkerCompletedEventArgs e)
{
if (loadFailed)
{
LogManager.Log(hwdName + " : datalogger loading failed");
return;
}
if ((e.Cancelled == true))
{
LogManager.Log(hwdName + " : datalogger loading was canceled");
previewMinData.Clear();
previewCurData.Clear();
previewMaxData.Clear();
preloadDone = false;
loadDone = false;
return;
}
if (previewCurData.Count<=2)
{
preloadDone = false;
loadDone = false;
}
LogManager.Log(hwdName + " : datalogger loading completed (" + previewMinData.Count + " rows )");
loadDone = true;
globalDataLoadProgress = 100;
if (previewMinData.Count <= 0)
{
foreach (Form f in FormsToNotify)
if (f is GraphForm)
((GraphForm)f).DataLoggerProgress();
return;
}
foreach (Form f in FormsToNotify)
if (f is GraphForm)
{
((GraphForm)f).DataloggerCompleted(this);
((GraphForm)f).DataLoggerProgress();
}
previewMinData.Clear();
previewCurData.Clear();
previewMaxData.Clear();
preloadDone = false;
loadDone = false;
}
private void dataCleanUp()
{ if (_MaxDataRecords <= 0) return;
int newsize = (_MaxDataRecords * 90) / 100;
if ((curData!=null) && (_MaxDataRecords< curData.Count))
{
minData.RemoveRange(0,minData.Count - newsize);
curData.RemoveRange(0,curData.Count - newsize);
maxData.RemoveRange(0,maxData.Count - newsize);
}
}
private void previewDataCleanUp()
{
if (_MaxDataRecords <= 0) return;
int newsize = (_MaxDataRecords * 90) / 100;
if ((previewMinData != null) && (_MaxDataRecords < previewMinData.Count))
{
previewMinData.RemoveRange(0,previewMinData.Count - newsize);
previewCurData.RemoveRange(0,previewCurData.Count - newsize);
previewMaxData.RemoveRange(0,previewMaxData.Count - newsize);
}
}
public void stopDataloggerloading()
{
dataMutex.WaitOne();
minData.Clear();
curData.Clear();
maxData.Clear();
dataMutex.ReleaseMutex();
firstLiveDataTimeStamp = 0;
firstDataloggerTimeStamp = 0;
lastDataTimeStamp = 0;
lastDataSource = "stop";
if (!loadProcess.CancellationPending) loadProcess.CancelAsync();
load_ProgressChanged(null, null);
}
protected void load_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
foreach (Form f in FormsToNotify)
if (f is GraphForm)
{
((GraphForm)f).DataLoggerProgress();
}
}
public bool isOnline()
{
return online;
}
public void reloadConfig()
{
if (online)
{
bool ison = sensor.isOnline();
if (ison)
{
try
{
unit = sensor.get_unit();
friendlyname = sensor.get_friendlyName();
resolution = sensor.get_resolution();
lastGetConfig = YAPI.GetTickCount();
mustReloadConfig = false;
}
catch (Exception e) { LogManager.Log("reload configuration error: " + e.Message); }
}
else online = false;
}
}
public string get_unit()
{
if ((cfgChgNotificationsSupported) && (!mustReloadConfig)) return unit;
if ((lastGetConfig <= 0) || (YAPI.GetTickCount() - lastGetConfig > 5000)) reloadConfig();
return unit;
}
public double get_resolution()
{
if ((cfgChgNotificationsSupported) && (!mustReloadConfig)) return resolution;
if ((lastGetConfig <= 0) || (YAPI.GetTickCount() - lastGetConfig > 5000)) reloadConfig();
return resolution;
}
public void loadDatalogger(double start, double stop)
{
if (!dataLoggerFeature) return;
if (predloadProcess.IsBusy) return;
if (loadProcess.IsBusy) return;
if (constants.maxPointsPerDataloggerSerie < 0)
{
LogManager.Log(hwdName + " : datalogger access is disabled");
return;
}
if (this.isReadOnly)
{
LogManager.Log(hwdName + " is read only, cannot load the datalogger contents (yes that's a bug)");
return;
}
if ((!preloadDone) && dataLoggerFeature)
{
LogManager.Log(hwdName + " : start datalogger preloading");
predloadProcess.RunWorkerAsync(new DataLoggerBoundary(start,stop));
}
else if ( (preloadDone) && (!loadDone) && dataLoggerFeature)
{
LogManager.Log(hwdName + " : start datalogger loading");
loadProcess.RunWorkerAsync(null);
}
}
public void arrival(bool dataloggerOn)
{
configureSensor();