using System using System Collections Generic using System Data using

  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
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Technekon.DomainObjects;
using Technekon.VDECommon;
using Technekon.VDEConnectivity;
namespace Technekon.VDESrv.Operations
{
/// <summary>
/// Операция получения отчета по обследованию
/// </summary>
partial class GetInspRepOperation : BaseOperation
{
/// <summary> Описание ОД параметра виброточки для последующего анализа </summary>
protected struct InspRepParameterDescriptor
{
private InspRepParameterDO m_Parameter;
private Double m_AlarmLevel;
private Guid m_PointID;
private Guid m_ChannelID;
private Guid m_ParameterID;
/// <summary>
/// ОД параметра
/// </summary>
public InspRepParameterDO Parameter
{
get { return m_Parameter; }
set { m_Parameter = value; }
}
/// <summary>
/// Уровень тревожности
/// </summary>
public double AlarmLevel
{
get { return m_AlarmLevel; }
set { m_AlarmLevel = value; }
}
/// <summary>
/// ID точки
/// </summary>
public Guid PointID
{
get { return m_PointID; }
set { m_PointID = value; }
}
/// <summary>
/// ID канала
/// </summary>
public Guid ChannelID
{
get { return m_ChannelID; }
set { m_ChannelID = value; }
}
/// <summary>
/// ID параметра
/// </summary>
public Guid ParameterID
{
get { return m_ParameterID; }
set { m_ParameterID = value; }
}
}
/// <summary> Условия формирования данных в отчете </summary>
private readonly InspRep_FilterDO m_filter;
/// <summary> Данные отчета </summary>
private readonly InspRepDataDO m_RepData;
private DateTime? m_TimeFrom;
private DateTime? m_TimeTo;
private readonly List<InspRepParameterDescriptor> m_ParametersForPrognosis = new List<InspRepParameterDescriptor>();
private const Int32 modelTypeElement = 0;
private const Int32 modelTypeMachine = 1;
public GetInspRepOperation(BaseOperation parentOperation, DataControlObject contextObject, InspRep_FilterDO filter)
: base(parentOperation, contextObject)
{
m_filter = filter;
m_RepData = new InspRepDataDO();
}
public override void DoExecute()
{
if (m_filter == null)
{ return; }
try
{
FillReport();
}
catch (Exception ex)
{
VDException.Report(ex, m_CurrentHandler.CurrentClientHandler.ClientName, m_CurrentHandler.OperationName);
throw;
}
}
/// <summary>
/// Генерация отчета
/// </summary>
private void FillReport()
{
#region Формирование sql запроса для получения списка агрегатов
String typeName = m_filter.NodeType.ToString();
String getMachinesQuery = String.Format(m_Query.GetMachines, typeName + "." + typeName + "_ID = @Element_ID OR t.Division_Child = 1");
SqlCommand commandGetReportHeader = new SqlCommand(getMachinesQuery, m_ContextObject.DBConnection);
commandGetReportHeader.Parameters.AddWithValue("@Element_ID", m_filter.NodeID);
if (m_filter.NodeType != InspRepNodeType.Division)
{ commandGetReportHeader.Parameters.AddWithValue("@Division_ID_Req", DBNull.Value); }
else
{ commandGetReportHeader.Parameters.AddWithValue("@Division_ID_Req", m_filter.NodeID); }
SqlDataAdapter adapter = new SqlDataAdapter(commandGetReportHeader);
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable table = ds.Tables[0];
#endregion
Int32 colOrganization_Name = GetColIndex(table, "Organization_Name");
Int32 colOrganization_Code = GetColIndex(table, "Organization_Code");
Int32 colPlant_Name = GetColIndex(table, "Plant_Name");
Int32 colPlant_Code = GetColIndex(table, "Plant_Code");
Int32 colDivision_ID = GetColIndex(table, "Division_ID");
Int32 colShop_Name = GetColIndex(table, "Shop_Name");
Int32 colShop_Code = GetColIndex(table, "Shop_Code");
Int32 colMachine_Name = GetColIndex(table, "Machine_Name");
Int32 colMachine_Code = GetColIndex(table, "Machine_Code");
Int32 colMachine_ID = GetColIndex(table, "Machine_ID");
Int32 colPicture = GetColIndex(table, "Picture");
//Заполнение шапки ОД отчета по обследованию
//InspRepDataDO
if (table.Rows.Count != 0)
{
m_RepData.OrganizationCode = Convert.ToInt32(table.Rows[0][colOrganization_Code]);
m_RepData.OrganizationName = table.Rows[0][colOrganization_Name].ToString();
}
m_RepData.InspRepMachines = new List<InspRepMachineDO>(table.Rows.Count);
for (Int32 i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepMachineDO machineDO = new InspRepMachineDO();
m_RepData.InspRepMachines.Add(machineDO);
machineDO.PlantName = row[colPlant_Name].ToString();
machineDO.PlantCode = Convert.ToInt32(row[colPlant_Code]);
//Сделать выбор пути если у машины есть подразделение которому она принадлежит
GetDivisionPath(machineDO, row[colDivision_ID].ToString());
machineDO.ShopName = row[colShop_Name].ToString();
machineDO.ShopCode = Convert.ToInt32(row[colShop_Code]);
machineDO.MachineName = row[colMachine_Name].ToString();
machineDO.MachineCode = Convert.ToInt32(row[colMachine_Code]);
Guid machineID = new Guid(row[colMachine_ID].ToString());
//Получение схемы агрегата
if ((m_filter.ParametersFilter & InspRepParametersFilter.MachineSchema) == InspRepParametersFilter.MachineSchema)
{
if (!row.IsNull(colPicture))
{
byte[] pictureArray = (byte[])row.ItemArray[colPicture];
machineDO.Picture.Flush();
machineDO.Picture.Position = 0;
machineDO.Picture.Write(pictureArray, 0, pictureArray.Length);
}
else
{
machineDO.Picture.Flush();
}
}
//Получение оборотных
machineDO.InspRepRotations = GetRotations(machineDO, machineID);
//Заполнение данных виброточек
machineDO.InspRepPoints = (m_filter.ParametersFilter & InspRepParametersFilter.VibroParameters) == InspRepParametersFilter.VibroParameters ? GetPoints(machineDO, machineID) : new List<InspRepPointDO>(0);
//Заполнение данных режимных параметров
machineDO.InspRepRegimeParameters = (m_filter.ParametersFilter & InspRepParametersFilter.RegimeParameers) == InspRepParametersFilter.RegimeParameers ? GetRegimeParameters(machineDO, machineID) : new List<InspRepParameterDO>(0);
//Получение формул контроля
machineDO.InspRepMonitoringFormulas = (m_filter.ParametersFilter & InspRepParametersFilter.MonitoringFormulas) == InspRepParametersFilter.MonitoringFormulas ? GetMonitoringFormulas(machineDO, machineID) : new List<InspRepParameterDO>(0);
///Построение прогноза
BuildPrognosis(machineDO, machineID);
m_ParametersForPrognosis.Clear();
machineDO.ResetChanges();
m_RepData.TimeFrom = m_TimeFrom;
m_RepData.TimeTo = m_TimeTo;
}
}
/// <summary>
/// Получение пути родительских подразделений у цеха
/// </summary>
/// <param name="machineDO">ОД агрегата куда записываются данные</param>
/// <param name="division_ID">Идентификатор подразделения</param>
private void GetDivisionPath(InspRepMachineDO machineDO, string division_ID)
{
if (division_ID != "")
{
//Получение пути в подразделении
String sqlText = String.Format(m_Query.GetMachineDivisionPath, division_ID);
SqlCommand commandGetDivisionsPath = new SqlCommand(sqlText, m_ContextObject.DBConnection);
SqlDataAdapter adapterPath = new SqlDataAdapter(commandGetDivisionsPath);
DataSet data = new DataSet();
adapterPath.Fill(data);
DataTable tablePath = data.Tables[0];
Int32 colDivision_Name = GetColIndex(tablePath, "Division_Name");
Int32 colDivision_Code = GetColIndex(tablePath, "Division_Code");
machineDO.DivisionCodes = new int[tablePath.Rows.Count];
machineDO.DivisionNames = new String[tablePath.Rows.Count];
for (Int32 j = 0; j < tablePath.Rows.Count; j++)
{
DataRow rowPath = tablePath.Rows[j];
machineDO.DivisionCodes[j] = Convert.ToInt32(rowPath[colDivision_Code]);
machineDO.DivisionNames[j] = rowPath[colDivision_Name].ToString();
}
}
else
{
machineDO.DivisionCodes = new int[0];
machineDO.DivisionNames = new String[0];
}
}
/// <summary>
/// Получение оборотных по указанному агрегату
/// </summary>
/// <param name="machineDO"></param>
/// <param name="machineID">Идентификатор агрегата</param>
/// <returns></returns>
private List<InspRepRotationDO> GetRotations(InspRepMachineDO machineDO, Guid machineID)
{
//Формирование sql запроса в зависимости от диапазона данных которые необходимо выбрать
SqlCommand commandGetRotations = new SqlCommand();
MakeTimeIntervalSQLFilter(commandGetRotations, m_Query.GetRotationPoints);
commandGetRotations.Connection = m_ContextObject.DBConnection;
commandGetRotations.Parameters.AddWithValue("@Signal_Type_ID", SignalTypes.SignalTypeRPM);
commandGetRotations.Parameters.AddWithValue("@Machine_ID", machineID);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetRotations);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
//Сохранение данных
Int32 colPointName = GetColIndex(table, "Point_Name");
Int32 colPointNumber = GetColIndex(table, "Point_Number");
Int32 colSuffix = GetColIndex(table, "Suffix");
Int32 colParameterSettingName = GetColIndex(table, "Parameter_Setting_Name");
Int32 colValue = GetColIndex(table, "Value");
Int32 colUnitTypeID = GetColIndex(table, "Unit_Type_ID");
Int32 colEventTime = GetColIndex(table, "Event_Time");
List<InspRepRotationDO> result = new List<InspRepRotationDO>(table.Rows.Count);
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepRotationDO rotationDO = new InspRepRotationDO();
String paramName = row[colParameterSettingName].ToString();
Int32 pointNumber = Convert.ToInt32(row[colPointNumber]);
String suffix = row[colSuffix].ToString();
rotationDO.PointCode = CommonRoutines.MakeParamName(paramName, ValueTypes.ValueTypeUndefined, SignalTypes.SignalTypeRPM, pointNumber, "", suffix);
rotationDO.PointName = row[colPointName].ToString();
if (row.IsNull(colValue))
{
rotationDO.Value = 0;
rotationDO.IsHaveData = false;
}
else
{
rotationDO.Value = Convert.ToSingle(row[colValue]);
rotationDO.IsHaveData = true;
//Сохранение диапазонов времени для отчета и агрегата
DateTime time = Convert.ToDateTime(row[colEventTime]);
ProcessEventTime(time, machineDO);
}
rotationDO.UnitId = Convert.ToInt32(row[colUnitTypeID]);
result.Add(rotationDO);
}
return result;
}
/// <summary>
/// Получение данных по виброточкам
/// </summary>
/// <param name="machineDO">ОД агрегата, для которого получаем параметры виброточек</param>
/// <param name="machineID">Идентификатор агрегата</param>
/// <returns></returns>
private List<InspRepPointDO> GetPoints(InspRepMachineDO machineDO, Guid machineID)
{
SqlCommand commandGetPoints = new SqlCommand(m_Query.GetPoints, m_ContextObject.DBConnection);
commandGetPoints.Parameters.AddWithValue("@Machine_ID", machineID);
commandGetPoints.Parameters.AddWithValue("@Signal_Type_ID", SignalTypes.SignalTypeWave);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetPoints);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
List<InspRepPointDO> result = new List<InspRepPointDO>(table.Rows.Count);
int colPointName = GetColIndex(table, "Point_Name");
int colPointNumber = GetColIndex(table, "Point_Number");
int colSuffix = GetColIndex(table, "Suffix");
int colParameterSettingName = GetColIndex(table, "Parameter_Setting_Name");
int colElementModelSettingID = GetColIndex(table, "Element_Model_Setting_ID");
int colParameterSettingID = GetColIndex(table, "Parameter_Setting_ID");
int colChannelSettingID = GetColIndex(table, "Channel_Setting_ID");
int colPointID = GetColIndex(table, "Point_ID");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepPointDO point = new InspRepPointDO();
String pointName = row[colPointName].ToString();
Int32 pointNumber = Convert.ToInt32(row[colPointNumber]);
String suffix = row[colSuffix].ToString();
String parameterSettingName = row[colParameterSettingName].ToString();
Guid elementModelSettingID = new Guid(row[colElementModelSettingID].ToString());
Guid parameterSettingID = new Guid(row[colParameterSettingID].ToString());
Guid channelSettingID = new Guid(row[colChannelSettingID].ToString());
Guid pointID = new Guid(row[colPointID].ToString());
switch (m_filter.PointNamesFilter)
{
case InspRepPointNamesFilter.FullPointName:
point.PointName = pointName;
break;
case InspRepPointNamesFilter.ShortPointCode:
point.PointName = CommonRoutines.MakeParamName(parameterSettingName, ValueTypes.ValueTypeUndefined,
SignalTypes.SignalTypeWave, pointNumber, "", suffix);
break;
}
point.InspRepParameters = GetPointParameters(machineDO, machineID, elementModelSettingID, channelSettingID, pointID, parameterSettingID);
GetFormulasNearWave(point.InspRepParameters, machineDO, machineID, elementModelSettingID, pointID, channelSettingID);
result.Add(point);
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="parameters"></param>
/// <param name="machineDO"></param>
/// <param name="machineID"></param>
/// <param name="elementModelSettingID"></param>
/// <param name="pointID"></param>
/// <param name="channelSettingID"></param>
private void GetFormulasNearWave(ICollection<InspRepParameterDO> parameters, InspRepMachineDO machineDO, Guid machineID, Guid elementModelSettingID, Guid pointID, Guid channelSettingID)
{
SqlCommand commandGetFormulas = new SqlCommand();
MakeTimeIntervalSQLFilter(commandGetFormulas, m_Query.GetFormulasNearWave);
commandGetFormulas.Connection = m_ContextObject.DBConnection;
commandGetFormulas.Parameters.AddWithValue("@Machine_ID", machineID);
commandGetFormulas.Parameters.AddWithValue("@Point_ID", pointID);
commandGetFormulas.Parameters.AddWithValue("@Channel_Setting_ID", channelSettingID);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetFormulas);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
Int32 colParameterSettingID = GetColIndex(table, "Parameter_Setting_ID");
Int32 colMachineEventID = GetColIndex(table, "Machine_Event_ID");
Int32 colUnitTypeID = GetColIndex(table, "Unit_Type_ID");
Int32 colParameterName = GetColIndex(table, "Parameter_Name");
Int32 colValue = GetColIndex(table, "Value");
Int32 colEventTime = GetColIndex(table, "Event_Time");
Int32 colOrderID = GetColIndex(table, "Order_ID");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepParameterDO parameter = new InspRepParameterDO();
parameter.ParamName = row[colParameterName].ToString();
parameter.OrderID = Convert.ToInt32(row[colOrderID]);
if (row.IsNull(colValue))
{
parameter.IsHaveData = false;
parameter.Value = 0;
}
else
{
parameter.IsHaveData = true;
parameter.Value = Convert.ToSingle(row[colValue]);
//Сохранение диапазонов времени для отчета и агрегата
DateTime time = Convert.ToDateTime(row[colEventTime]);
ProcessEventTime(time, machineDO);
Guid pointParameterSettingID = new Guid(row[colParameterSettingID].ToString());
Guid machineEventID = new Guid(row[colMachineEventID].ToString());
FillRegionLevels(parameter, elementModelSettingID, channelSettingID, pointID, pointParameterSettingID, machineEventID, modelTypeElement);
}
parameter.UnitId = Convert.ToInt32(row[colUnitTypeID]);
//если задано условия получения точек со сработавшими уставками, то исключаем точки "безаварийных" точек
if (m_filter.RegionsFilter == InspRepRegionsFilter.AlarmsOnly)
{
if (parameter.AssetCode != InspRepAssertCode.None)
{
parameters.Add(parameter);
}
}
else
{ parameters.Add(parameter); }
}
}
/// <summary>
/// Получение данных о параметрах виброточки
/// </summary>
/// <param name="machineDO">ОД данных агрегата для которого получаем данные о виброточках</param>
/// <param name="machineID">ID агрегата</param>
/// <param name="elementModelSettingID">ID элемента модели</param>
/// <param name="channelSettingID">ID свойств канала</param>
/// <param name="pointID">ID точки</param>
/// <param name="parameterSettingID">ID свойств параметра</param>
/// <returns></returns>
private List<InspRepParameterDO> GetPointParameters(InspRepMachineDO machineDO, Guid machineID, Guid elementModelSettingID, Guid channelSettingID, Guid pointID, Guid parameterSettingID)
{
SqlCommand commandGetPointParameters = new SqlCommand();
MakeTimeIntervalSQLFilter(commandGetPointParameters, m_Query.GetPointParameters);
commandGetPointParameters.Connection = m_ContextObject.DBConnection;
commandGetPointParameters.Parameters.AddWithValue("@Machine_ID", machineID);
commandGetPointParameters.Parameters.AddWithValue("@Element_Model_Setting_ID", elementModelSettingID);
commandGetPointParameters.Parameters.AddWithValue("@Parent_Parameter_ID", parameterSettingID);
commandGetPointParameters.Parameters.AddWithValue("@Channel_Setting_ID", channelSettingID);
commandGetPointParameters.Parameters.AddWithValue("@Point_ID", pointID);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetPointParameters);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
List<InspRepParameterDO> result = new List<InspRepParameterDO>(table.Rows.Count);
Int32 colParameterSettingID = GetColIndex(table, "Parameter_Setting_ID");
Int32 colMachineEventID = GetColIndex(table, "Machine_Event_ID");
Int32 colUnitTypeID = GetColIndex(table, "Unit_Type_ID");
Int32 colParameterName = GetColIndex(table, "Parameter_Name");
Int32 colValue = GetColIndex(table, "Value");
Int32 colEventTime = GetColIndex(table, "Event_Time");
Int32 colOrderID = GetColIndex(table, "Order_ID");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepParameterDO parameter = new InspRepParameterDO();
parameter.ParamName = row[colParameterName].ToString();
parameter.OrderID = Convert.ToInt32(row[colOrderID]);
if (row.IsNull(colValue))
{
parameter.IsHaveData = false;
parameter.Value = 0;
}
else
{
parameter.IsHaveData = true;
parameter.Value = Convert.ToSingle(row[colValue]);
//Сохранение диапазонов времени для отчета и агрегата
DateTime time = Convert.ToDateTime(row[colEventTime]);
ProcessEventTime(time, machineDO);
Guid pointParameterSettingID = new Guid(row[colParameterSettingID].ToString());
Guid machineEventID = new Guid(row[colMachineEventID].ToString());
FillRegionLevels(parameter, elementModelSettingID, channelSettingID, pointID, pointParameterSettingID, machineEventID, modelTypeElement);
}
parameter.UnitId = Convert.ToInt32(row[colUnitTypeID]);
//если задано условия получения точек со сработавшими уставками, то исключаем точки "безаварийных" точек
if (m_filter.RegionsFilter == InspRepRegionsFilter.AlarmsOnly)
{
if (parameter.AssetCode != InspRepAssertCode.None)
{
result.Add(parameter);
}
}
else
{ result.Add(parameter); }
}
return result;
}
/// <summary>
/// Получение режимных параметров
/// </summary>
/// <param name="machineDO">ОД агрегата</param>
/// <param name="machineID">Идентификатор агрегата</param>
/// <returns></returns>
private List<InspRepParameterDO> GetRegimeParameters(InspRepMachineDO machineDO, Guid machineID)
{
SqlCommand commandGetPointParameters = new SqlCommand();
MakeTimeIntervalSQLFilter(commandGetPointParameters, m_Query.GetRegimeParameters);
commandGetPointParameters.Connection = m_ContextObject.DBConnection;
commandGetPointParameters.Parameters.AddWithValue("@Machine_ID", machineID);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetPointParameters);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
List<InspRepParameterDO> result = new List<InspRepParameterDO>(table.Rows.Count);
Int32 colUnitTypeID = GetColIndex(table, "Unit_Type_ID");
Int32 colPointName = GetColIndex(table, "Point_Name");
Int32 colValue = GetColIndex(table, "Value");
Int32 colEventTime = GetColIndex(table, "Event_Time");
Int32 colChannelSettingID = GetColIndex(table, "Channel_Setting_ID");
Int32 colParameterSettingID = GetColIndex(table, "Parameter_Setting_ID");
Int32 colPointID = GetColIndex(table, "Point_ID");
Int32 colMachineEventID = GetColIndex(table, "Machine_Event_ID");
Int32 colMachineModelSettingID = GetColIndex(table, "Machine_Model_Setting_ID");
Int32 colOrderID = GetColIndex(table, "Order_ID");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepParameterDO parameter = new InspRepParameterDO();
parameter.ParamName = row[colPointName].ToString();
parameter.OrderID = Convert.ToInt32(row[colOrderID]);
if (row.IsNull(colValue))
{
parameter.IsHaveData = false;
parameter.Value = 0;
}
else
{
parameter.IsHaveData = true;
parameter.Value = Convert.ToSingle(row[colValue]);
//Сохранение диапазонов времени для отчета и агрегата
DateTime time = Convert.ToDateTime(row[colEventTime]);
ProcessEventTime(time, machineDO);
Guid channelSettingID = new Guid(row[colChannelSettingID].ToString());
Guid parameterSettingID = new Guid(row[colParameterSettingID].ToString());
Guid pointID = new Guid(row[colPointID].ToString());
Guid machineEventID = new Guid(row[colMachineEventID].ToString());
Guid machineModelSettingID = new Guid(row[colMachineModelSettingID].ToString());
FillRegionLevels(parameter, machineModelSettingID, channelSettingID, pointID, parameterSettingID, machineEventID, modelTypeMachine);
}
parameter.UnitId = Convert.ToInt32(row[colUnitTypeID]);
//если задано условия получения точек со сработавшими уставками, то исключаем точки "безаварийных" точек
if (m_filter.RegionsFilter == InspRepRegionsFilter.AlarmsOnly)
{
if (parameter.AssetCode != InspRepAssertCode.None)
{
result.Add(parameter);
}
}
else
{ result.Add(parameter); }
}
return result;
}
/// <summary>
/// Получение данных формул контроля
/// </summary>
/// <param name="machineDO">ОД агрегата</param>
/// <param name="machineGuid">Идентификатор агрегата</param>
/// <returns></returns>
private List<InspRepParameterDO> GetMonitoringFormulas(InspRepMachineDO machineDO, Guid machineGuid)
{
SqlCommand commandGetMonitoringFormulas = new SqlCommand();
MakeTimeIntervalSQLFilter(commandGetMonitoringFormulas, m_Query.GetMonitoringFormulas);
commandGetMonitoringFormulas.Connection = m_ContextObject.DBConnection;
commandGetMonitoringFormulas.Parameters.AddWithValue("@Machine_ID", machineGuid);
commandGetMonitoringFormulas.Parameters.AddWithValue("Value_Type_ID", ValueTypes.ValueTypeFormula);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetMonitoringFormulas);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
List<InspRepParameterDO> result = new List<InspRepParameterDO>(table.Rows.Count);
Int32 colParameterSettingID = GetColIndex(table, "Parameter_Setting_ID");
Int32 colUnitTypeID = GetColIndex(table, "Unit_Type_ID");
Int32 colParameterName = GetColIndex(table, "Name");
Int32 colOrderID = GetColIndex(table, "Order_ID");
Int32 colValue = GetColIndex(table, "Value");
Int32 colEventTime = GetColIndex(table, "Event_Time");
Int32 colMachineModelSettingID = GetColIndex(table, "Machine_Model_Setting_ID");
Int32 colMachineEventID = GetColIndex(table, "Machine_Event_ID");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
InspRepParameterDO parameter = new InspRepParameterDO();
parameter.ParamName = row[colParameterName].ToString();
parameter.OrderID = Convert.ToInt32(row[colOrderID]);
if (row.IsNull(colValue))
{
parameter.IsHaveData = false;
parameter.Value = 0;
}
else
{
parameter.IsHaveData = true;
parameter.Value = Convert.ToSingle(row[colValue]);
//Сохранение диапазонов времени для отчета и агрегата
DateTime time = Convert.ToDateTime(row[colEventTime]);
ProcessEventTime(time, machineDO);
//Guid pointParameterSettingID = new Guid(row[colParameterSettingID].ToString());
Guid ChannelSettingID = Guid.Empty;
Guid PointID = Guid.Empty;
Guid ParameterSettingID = new Guid(row[colParameterSettingID].ToString());
Guid MachineEventID = new Guid(row[colMachineEventID].ToString());
Guid MachineModelSettingID = new Guid(row[colMachineModelSettingID].ToString());
FillRegionLevels(parameter, MachineModelSettingID, ChannelSettingID, PointID, ParameterSettingID, MachineEventID, modelTypeMachine);
}
parameter.UnitId = Convert.ToInt32(row[colUnitTypeID]);
//если задано условия получения точек со сработавшими уставками, то исключаем точки "безаварийных" точек
if (m_filter.RegionsFilter == InspRepRegionsFilter.AlarmsOnly)
{
if (parameter.AssetCode != InspRepAssertCode.None)
{
result.Add(parameter);
}
}
else
{ result.Add(parameter); }
}
return result;
}
/// <summary>
/// Формирование sql-запроса по шаблону в котором используется условие отбора данных по времени
/// </summary>
/// <param name="command">SqlCommand добавляется текст сформированного запроса</param>
/// <param name="template">Шаблон sql-запроса куда добавляется условие фильтрации</param>
/// <returns></returns>
private void MakeTimeIntervalSQLFilter(SqlCommand command, String template)
{
string resultSQL;
switch (m_filter.TimeInterval)
{
case InspRepTimeIntervalFilter.LastMachineData:
resultSQL = String.Format(template, m_RotationWhereTemplates.LastMachineData);
break;
case InspRepTimeIntervalFilter.LastMachineDataInInterval:
resultSQL = String.Format(template, m_RotationWhereTemplates.LastMachineDataInInterval);
command.Parameters.AddWithValue("@EventFrom", m_filter.TimeFrom);
command.Parameters.AddWithValue("@EventTo", m_filter.TimeTo);
break;
case InspRepTimeIntervalFilter.LastMachineInspection:
resultSQL = String.Format(template, m_RotationWhereTemplates.LastMachineInspection);
break;
default:// По умолчанию получаем последние данные по агрегату
resultSQL = String.Format(template, m_RotationWhereTemplates.LastMachineData);
break;
}
command.CommandText = resultSQL;
}
/// <summary>
/// Обработка времени события. Для сохранения его в диапазоне времени отчета и ОД агрегата
/// </summary>
/// <param name="time">Время события</param>
/// <param name="machineDO">ОД агрегата, для которого обрабатываем время события</param>
private void ProcessEventTime(DateTime time, InspRepMachineDO machineDO)
{
//Установка диапазона данных для всего отчета
if ((m_TimeFrom == null) || (time < m_TimeFrom))
{ m_TimeFrom = time; }
if ((m_TimeTo == null) || (time > m_TimeTo))
{ m_TimeTo = time; }
//Установка диапазона данных для агрегата
if ((machineDO.InspFrom == null) || (time < machineDO.InspFrom))
{ machineDO.InspFrom = time; }
if ((machineDO.InspTo == null) || (time > machineDO.InspTo))
{ machineDO.InspTo = time; }
}
/// <summary>
/// <summary>
/// Заполнение ОД виброточки данными о параметрах уставок и их срабатывания
/// </summary>
/// <param name="parameterDO">ОД для записи информации по уставкам</param>
/// <param name="parentModelID">ID родительского жлемента (элемента или агрегата)</param>
/// <param name="channelSettingID">ID канала</param>
/// <param name="parameterSettingID">ID параметра</param>
/// <param name="pointID">ID точки</param>
/// <param name="machineEventID">ID события измерения</param>
/// <param name="modelType"> Тип родительского элемента (агрегат\элемент)</param>
private void FillRegionLevels(InspRepParameterDO parameterDO, Guid parentModelID,
Guid channelSettingID, Guid pointID, Guid parameterSettingID, Guid machineEventID, int modelType)
{
#region Получение уставок по точке
String query = modelType == modelTypeElement ? m_Query.GetRegionsForElement : m_Query.GetRegionsForMachine;
SqlCommand commandGetRegions = new SqlCommand(query, m_ContextObject.DBConnection);
commandGetRegions.Parameters.AddWithValue("@ParentModelID", parentModelID);
commandGetRegions.Parameters.AddWithValue("@ParentParameterID", parameterSettingID);
commandGetRegions.Parameters.AddWithValue("@Channel_Setting_ID", channelSettingID);
commandGetRegions.Parameters.AddWithValue("@Point_ID", pointID);
commandGetRegions.Parameters.AddWithValue("@Machine_Event_ID", machineEventID);
SqlDataAdapter adapter = new SqlDataAdapter(commandGetRegions);
DataSet data = new DataSet();
adapter.Fill(data);
DataTable table = data.Tables[0];
#endregion
parameterDO.WarnLevel = "-";
parameterDO.AlarmLevel = "-";
parameterDO.AbsChng = "-";
parameterDO.RelChng = "-";
Int32 colRegionType = GetColIndex(table, "PARAM_REGION_TYPE_ID");
Int32 colParentValueType = GetColIndex(table, "PARENT_VALUE_TYPE");
Int32 colHighWarningLevel = GetColIndex(table, "HIGH_WARNING_LEVEL");
Int32 colHighAlarmLevel = GetColIndex(table, "HIGH_ALARM_LEVEL");
Int32 colLowWarningLevel = GetColIndex(table, "LOW_WARNING_LEVEL");
Int32 colLowAlarmLevel = GetColIndex(table, "LOW_ALARM_LEVEL");
Int32 colTimeInterval = GetColIndex(table, "TIME_INTERVAL");
Int32 colAlarmID = GetColIndex(table, "ALARM_ID");
EventStatusTypes[] regionStates = new EventStatusTypes[] { EventStatusTypes.EventStatusTypePassive,
EventStatusTypes.EventStatusTypePassive, EventStatusTypes.EventStatusTypePassive };
Double prognososHighAlarmLevel = 0;
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
int regionType = Convert.ToInt32(row[colRegionType]);
int parentValueType = Convert.ToInt32(row[colParentValueType]);
EventStatusTypes eventStatus = row.IsNull(colAlarmID) ? EventStatusTypes.EventStatusTypePassive : (EventStatusTypes)row[colAlarmID];
regionStates[regionType - 1] = eventStatus;
#region Формирование текста граничных значений уставок
Single highWarningLevel = Convert.ToSingle(row[colHighWarningLevel]);
Single highAlarmLevel = Convert.ToSingle(row[colHighAlarmLevel]);
Single lowWarningLevel = Convert.ToSingle(row[colLowWarningLevel]);
Single lowAlarmLevel = Convert.ToSingle(row[colLowAlarmLevel]);
Int32 timeInterval = Convert.ToInt32(row[colTimeInterval]);
Int32 daysInterval = (timeInterval + 3600 * 12) / (36 * 2400);
switch ((ParamRegionTypes)regionType)
{
case (ParamRegionTypes.ParamRegionTypeAbsVal): // Уставка на абсолютное значение
if ((ValueTypes)parentValueType == ValueTypes.ValueTypeRms)
{
parameterDO.WarnLevel = String.Format("{0:G}", highWarningLevel);
parameterDO.AlarmLevel = String.Format("{0:G}", highAlarmLevel);
}
else
{
parameterDO.WarnLevel = String.Format("{0:G}|{1:G}", highWarningLevel, lowWarningLevel);
parameterDO.AlarmLevel = String.Format("{0:G}|{1:G}", highAlarmLevel, lowAlarmLevel);
}
prognososHighAlarmLevel = highAlarmLevel;
break;
case (ParamRegionTypes.ParamRegionTypeAbsDiff): //Уставка на абсолютное изменение
String days = ResourceLoaderStr.GetString("GetInspRepOperation_Days");
parameterDO.AbsChng = String.Format("{0:G} / {1:G} {2:G}", highWarningLevel, timeInterval, daysInterval, days);
break;
case (ParamRegionTypes.ParamRegionTypeRelDiff): //Уставка на относительное изменение
parameterDO.AbsChng = String.Format("{0:G} / {1:G}%", highWarningLevel, timeInterval, daysInterval);
break;
}
#endregion
#region Установка флага тревожности
if ((regionStates[0] == EventStatusTypes.EventStatusTypeLowAlarm) || (regionStates[0] == EventStatusTypes.EventStatusTypeHighAlarm))
{
parameterDO.AssetCode = InspRepAssertCode.Alarm;
}
else
{
if ((regionStates[0] == EventStatusTypes.EventStatusTypeLowWarning) || (regionStates[0] == EventStatusTypes.EventStatusTypeHighWarning))
{
parameterDO.AssetCode = InspRepAssertCode.Warning;
}
else
{
if ((regionStates[1] == EventStatusTypes.EventStatusTypeLowAlarm) || (regionStates[1] == EventStatusTypes.EventStatusTypeHighAlarm)
|| (regionStates[1] == EventStatusTypes.EventStatusTypeLowWarning) || (regionStates[1] == EventStatusTypes.EventStatusTypeHighWarning))
{
parameterDO.AssetCode = InspRepAssertCode.AbsChng;
}
else
{
if ((regionStates[2] == EventStatusTypes.EventStatusTypeLowAlarm) || (regionStates[2] == EventStatusTypes.EventStatusTypeHighAlarm)
|| (regionStates[2] == EventStatusTypes.EventStatusTypeLowWarning) || (regionStates[2] == EventStatusTypes.EventStatusTypeHighWarning))
{
parameterDO.AssetCode = InspRepAssertCode.RelGhg;
}
else
{
parameterDO.AssetCode = InspRepAssertCode.None;
}
}
}
}
#endregion
//Добавление данных параметра виброточки для расчета прогноза
if (((m_filter.RegionsFilter == InspRepRegionsFilter.AlarmsOnly) && (parameterDO.AssetCode != InspRepAssertCode.None))
|| (m_filter.RegionsFilter == InspRepRegionsFilter.All))
{
InspRepParameterDescriptor descriptor = new InspRepParameterDescriptor();
descriptor.Parameter = parameterDO;
descriptor.AlarmLevel = prognososHighAlarmLevel;
descriptor.PointID = pointID;
descriptor.ChannelID = channelSettingID;
descriptor.ParameterID = parameterSettingID;
m_ParametersForPrognosis.Add(descriptor);
}
}
}
/// <summary>
/// Построение прогноза по параметру виброточки
/// </summary>
/// <param name="machine">ОД агрегата, на котором находится виброточка</param>
/// <param name="machineID">ИД агрегата, на котором находится виброточка</param>
private void BuildPrognosis(InspRepMachineDO machine, Guid machineID)
{
#region Получение диапазона времени когда необходимо расчитывать прогноз
DateTime timeTo;
if ((m_filter.TimeInterval == InspRepTimeIntervalFilter.LastMachineDataInInterval))
{
timeTo = m_filter.TimeTo;
}
else
{
if (machine.InspTo != null)
{ timeTo = (DateTime)machine.InspTo; }
else
{
timeTo = new DateTime(0);
}
}
DateTime timeFrom = timeTo.Ticks < GetInspRepOperationPrognosisBuilder.GetHistoryLeghth() ?
new DateTime(0) : timeTo.AddTicks(-GetInspRepOperationPrognosisBuilder.GetHistoryLeghth());
#endregion
#region Формирование запроса получения данных для запроса
SqlCommand command = new SqlCommand(m_Query.GetDataForPrognosis, m_ContextObject.DBConnection);
command.Parameters.AddWithValue("@TimeFrom", timeFrom);
command.Parameters.AddWithValue("@TimeTo", timeTo);
command.Parameters.AddWithValue("MachineID", machineID);
command.Parameters.AddWithValue("@PointID", new Guid());
command.Parameters.AddWithValue("@ChannelSettingID", new Guid());
command.Parameters.AddWithValue("@ParameterSettingID", new Guid());
#endregion
#region Расчет прогноза
foreach (InspRepParameterDescriptor descriptor in m_ParametersForPrognosis)
{
command.Parameters["@PointID"].Value = descriptor.PointID;
command.Parameters["@ChannelSettingID"].Value = descriptor.ChannelID;
command.Parameters["@ParameterSettingID"].Value = descriptor.ParameterID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet data = new DataSet();
adapter.Fill(data);
//MachineAlarmPrognosisResult result;
//prognosis.Prognose(0, highAlarmLevel, null, null, out result);
}
#endregion
}
/// <summary>
/// Получение данных отчета по обследованию
/// </summary>
/// <param name="Result">Отчет</param>
/// <returns>Наличие данных в отчете</returns>
public override Boolean GetResult(out Object Result)
{
Result = m_RepData;
return m_RepData != null ? true : false;
}
/// <summary>
/// Получение индекса столбца в таблице по его имени
/// </summary>
/// <param name="tbl">Таблица содержащая столбец</param>
/// <param name="ColName">Имя столбца</param>
/// <returns></returns>
private Int32 GetColIndex(DataTable tbl, String ColName)
{
int iColIndex = tbl.Columns.IndexOf(ColName);
if (iColIndex == -1)
throw new VDSrvException(m_CurrentHandler.CurrentClientHandler.ClientName, m_ContextObject.m_DBName, m_OperationName, MessageType.ERROR, -1, "GetColIndex",
ResourceLoaderStr.GetString("InvalidColumn"), ReportType.ALL);
return iColIndex;
}
}
}