~rhys-gardener/miceonlinemonitoring/trunk

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
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <string.h> 
#include <typeinfo> 
#include <signal.h>
// Unpacking includes
#include "MDprocessManager.h"
#include "MDevent.h"
#include "MDfileManager.h"
#include "MDargumentHandler.h"
#include "MDargumentHandler.h"

// online monitoring includes
#include "MDHistogram.h"
#include "MDSharedRootFile.h"
#include "MDHistogramV1290.h"
#include "MDHistogramV1724.h"
#include "MDHistogramV1731.h"
#include "MDHistogramV830.h"
#include "MDHistogramVLSB.h" 
#include "MDHistogramDBB.h"
#include "MDHistogramDAQTrigger.h"
#include "MDHistogramPartTrigger.h"
#include "MDComHandler.h"
#include "RefRootFile.h"
#include "config.h"

//Include TApplication to ensure some root libraries are autoloaded.. 
#include "TApplication.h"
//Epics

#ifdef EPICS_FOUND
#include "OnMonEpicsClient.hh"
#endif
#ifdef MDMONITOR_FOUND
#include "MDdateMonitor.h"
#include "monitor.h"
#endif


volatile sig_atomic_t interrupted=false;

int nEvent(0); 
int LastException(0);
int numberExceptions(0);
int CurrentState(0);

int Reset_Warning_Counter(0);		

unsigned char *eventBuffer;
using namespace std;
#ifdef EPICS_FOUND
   OnMonEpicsClient PVwrite;
#endif
#define CREATE_HISTO_FILLER(equip)   Fill<MDHistogram##equip>* fill##equip = new  Fill<MDHistogram##equip>(theRootFile, theRefFile);

//********* OnFirstEvent **************

class OnFirstEvent : public MDprocessor {
 public:
  OnFirstEvent(MDSharedRootFile &aRootFile):MDprocessor(),myRootFile(&aRootFile){}
  virtual ~OnFirstEvent(){}
  virtual int Process(MDdataContainer*);

  MDSharedRootFile* myRootFile;
  
};

int OnFirstEvent::Process(MDdataContainer* aEvtPtr){
//	std::cout<<"On first event :"<<GetRunNumber()<<std::endl;
 // cout << "First Event for " << GetRunNumber() << " on " <<  GetTimeString() << endl;
 // myRootFile->SetRunNumber(GetRunNumber());
 // cout << " Opening Root file " << myRootFile->GetFileName(GetRunNumber()) << endl;
 
 
 MDevent anEvent(eventBuffer); //To get RunNb here,
 std::cout<<"inside OnFirstEvent::Process"<<std::endl;
  std::cout<<"On first event :"<<anEvent.RunNb()<<std::endl;
 // cout << "First Event for " << RunNb() << " on " <<  GetTimeString() << endl;
  myRootFile->SetRunNumber(anEvent.RunNb());
  cout << " Opening Root file " << myRootFile->GetFileName(anEvent.RunNb()) << endl;   
   // This will open the root file
  return OK;
}

//********* OnStartOfRun **************

class OnStartOfRun : public MDprocessor {
 public:
  OnStartOfRun(MDSharedRootFile &aRootFile):MDprocessor(),myRootFile(&aRootFile){}
  virtual ~OnStartOfRun(){}
  virtual int Process(MDdataContainer*);

  MDSharedRootFile* myRootFile;
 
};

int OnStartOfRun::Process(MDdataContainer* aEvtPtr){
  //myRootFile->SetRunNumber(GetRunNumber());
  cout << "Starting run " << GetRunNumber() << " on " <<  GetTimeString() << endl;
  myRootFile->SetRunNumber(GetRunNumber()); // This will open a new root file only if the run number has changed
 //  cout << "Starting run " << MDevent::RunNb() << " on " <<  GetTimeString() << endl;
//  myRootFile->SetRunNumber(GetRunNumber()); // This will open a new root file only if the run number has changed
  
  CurrentState=1;
  #ifdef EPICS_FOUND
	if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",1)) {
		std::cout << "Write status PV failed" << std::endl;
	}
  #endif
  
  return OK;
}

//********* OnEndOfRun **************

class OnEndOfRun : public MDprocessor {
 public:
  OnEndOfRun(MDSharedRootFile &aRootFile):MDprocessor(),myRootFile(&aRootFile){}
  virtual ~OnEndOfRun(){}
  virtual int Process(MDdataContainer*);

  MDSharedRootFile* myRootFile;
  
};

int OnEndOfRun::Process(MDdataContainer* aEvtPtr){
  cout << "End of run " << GetRunNumber() << " on " <<  GetTimeString() << endl;
  myRootFile->Write();
  myRootFile->Close();
  return OK;
}
//********* Template Histogram filling processor **************

template <class MDHistogramXXX>
class Fill: public MDprocessor {
 public:
  Fill(MDSharedRootFile &aRootFile, RefRootFile &aRefFile):MDprocessor(),myRootFile(&aRootFile),myRefFile(&aRefFile){
    myHistograms.SetPool(myRootFile);
   
    myHistograms.SetRefPool(myRefFile);
	
  }
  virtual ~Fill(){}
  virtual int Process(MDdataContainer*);
  void SetParameters(void* ptr){myParameters=ptr;}

  RefRootFile*		myRefFile;
  MDSharedRootFile* myRootFile;
  MDHistogramXXX  myHistograms;
  void*           myParameters;
};

template <class MDHistogramXXX>
int Fill<MDHistogramXXX>::Process(MDdataContainer* aDataContainer){
  try {
	
    myHistograms.SetParameters(myParameters);
    
	myHistograms.FillHisto(aDataContainer);
	//if(nEvent%100==0){
	//	myHistograms.CompareHisto(aDataContainer);
  //  }
  }catch ( MDexception & lExc) {
    std::cerr <<  lExc.GetDescription() << endl;
    std::cerr << "Unpacking exception,  DAQ Event skipped" << std::endl;
  }catch(std::exception & lExc) {
    std::cerr << "Standard exception" << std::endl;
    std::cerr << lExc.what() << std::endl;
  }
  catch( ... ){
    cerr << "ERROR while trying to fill Histograms in " << typeid(*this).name() << "! Ignoring. " << endl;
  }
  myRootFile->Flush();
  return OK;
}

//********* Histogram Filling processor for MDHistogramPartTrigger  **************
// We can't use the template here because the histograms are only filled for PHYSICS_EVENT

class FillMDHistogramPartTrigger: public MDprocessor {
 public:
  FillMDHistogramPartTrigger(MDSharedRootFile &aRootFile, RefRootFile &aRefFile):MDprocessor(),myRootFile(&aRootFile),myRefFile(&aRefFile){
    myHistograms.SetPool(myRootFile);
    myHistograms.SetRefPool(myRefFile);
  }
  virtual ~FillMDHistogramPartTrigger(){}
  virtual int Process(MDdataContainer*);
  
  RefRootFile*		myRefFile;
  MDSharedRootFile* myRootFile;  
  MDHistogramPartTrigger  myHistograms;
};

int FillMDHistogramPartTrigger::Process(MDdataContainer* anEventFragment){
  if (GetEventType() == PHYSICS_EVENT) {
    try {
      myHistograms.FillHisto(anEventFragment);
      if(nEvent%100){
		  myHistograms.CompareHisto(anEventFragment);
	  }
    }
    catch( ... ){
      cerr << "ERROR while trying to fill Histograms in " << typeid(*this).name() << "! Ignoring. " << endl;
    }
    myRootFile->Flush();
  }
  return OK;
}

//Function to run on ctrl-c signal

void my_handler(int s){
   printf("Caught signal %d\n",s);
   #ifdef EPICS_FOUND
   //Tell epics that the program is terminating
   if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",0)) {
      std::cout << "Write status PV failed" << std::endl;
      
   }
   #endif
   CurrentState = 0;
   //close the root file
  // theRootFile->Close();
   
   interrupted=true;
   
   
   
  exit(1); 

}


void SetEpicsExceptionState(int Eventno, int ExFlag){
	//std::cout<<"CurrentState"<<CurrentState<<std::endl;
	switch(CurrentState){
	 case(1):
	  //  std::cout<<"here2"<<std::endl;
	    if (ExFlag==1){
		//	std::cout<<"here"<<std::endl;
			
			CurrentState=2;
			LastException = nEvent;
			numberExceptions++;
			std::cout<<"Exception state WARNING"<<std::endl;
		}
		break;
	 case(2):
	  //  std::cout<<"here3"<<std::endl;
		if (ExFlag==0){
			if (nEvent - LastException > Reset_Warning_Counter){
				#ifdef EPICS_FOUND
				if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",1)) {
				   std::cout << "Write status PV failed" << std::endl;
				}
				#endif
				CurrentState=1;
				std::cerr<<"Exception state NORMAL"<<std::endl;
			}
		}
		
		else if (ExFlag==1){
				#ifdef EPICS_FOUND
				if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",3)) {
				   std::cout << "Write status PV failed" << std::endl;
				}
				#endif
			CurrentState=3;
			LastException = nEvent;
			std::cerr<<"Exception state SERIOUS"<<std::endl;
		}
		break;
     case(3):
          if (ExFlag==0){
			if ((nEvent - LastException) > 100){
				#ifdef EPICS_FOUND
				if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",1)) {
				   std::cout << "Write status PV failed" << std::endl;
				}
				#endif
				CurrentState=1;
				std::cerr<<"Exception state NORMAL"<<std::endl;
			}
		}
		else if (ExFlag==1){
				#ifdef EPICS_FOUND
				if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",3)) {
				   std::cout << "Write status PV failed" << std::endl;
				}
				#endif
			CurrentState=3;
			LastException = nEvent;
			std::cerr<<"Exception state SERIOUS"<<std::endl;
		}
	}
}
///////////////////////////////////////////////////////


TFile *_ref_file;

int main( int argc, char **argv ) {

  string rootFilePath;
  string refFilePath;
  string fileName;
  string filePath;
  int eventMax;
  bool ThereIsRefFile = false;
  TApplication a("a", 0, 0); // just to make sure that the autoloading of ROOT libraries works
 // gROOT->SetBatch(1);
 // gROOT->ProcessLine( "gErrorIgnoreLevel = 1001;");
  
  // process the arguments
#ifdef MDMONITOR_FOUND
  MDargumentHandler argh("MICE Online Monitoring Application. Maintained by Rhys Gardener");
  argh.AddArgument("file","Full data file name OR data source key ","f","<string>","@miceraid5:");
#else
  MDargumentHandler argh("MICE Online Monitoring Application -- Stand alone version (from files only)");
  argh.AddArgument("file","Data file name or run number","f","<string>","mandatory");
  argh.AddArgument("directory","path for the data file","d","<string>","/home/daq/Downloads" );
#endif

  argh.AddArgument("output_path","Path for the output root file","o","<string>","." );
  //Argument for the reference root file
  argh.AddArgument("reference_plots","Path for the reference plots root file","r","<string>","../ref_data/reference_pots.root" );
  
  argh.AddArgument("event_max","Maximum number of events to process (0 for no limit)","n","<int>","0");
  argh.AddArgument("stay_alive","Ask for user input before quitting at the end of file (zombie)","z");
  argh.AddArgument("help","Print this message","h");

  if ( argh.ProcessArguments(argc,argv) ) { argh.Usage(); return -1; }
  if ( argh.GetValue("help") ) { argh.Usage(); return 0; }
  if ( argh.GetValue("file",fileName) != MDARGUMENT_STATUS_OK ) return -1;
 // if ( argh.GetValue("directory", filePath) != MDARGUMENT_STATUS_OK ) return -1;
  if ( argh.GetValue("event_max",eventMax) != MDARGUMENT_STATUS_OK ) return -1;
  if ( argh.GetValue("output_path",rootFilePath) != MDARGUMENT_STATUS_OK ) return -1;
  //check if reference root file exists
  if (argh.GetValue("reference_plots",refFilePath)!= MDARGUMENT_STATUS_OK ) return -1;
  //See if it opens
  _ref_file = new TFile( refFilePath.c_str(), "READ");
  if (!_ref_file->IsOpen()) {
     std::cout << "Error: Can not open reference file " << refFilePath << std::endl;
     std::cout<<"Proceeding without reference data. To use ref data, check the ref plots are in ref_data/reference_lots.root, or use the '-r' option to define a new path/file."<<std::endl;
  
  }
  //Don't leave it open! 
  else {
	  _ref_file->Close(); 
	  ThereIsRefFile = true;
  }
  rootFilePath += "/";
  cout << "Saving histograms in " << rootFilePath << endl ; 
  // end processing the arguments
  
#ifdef MDMONITOR_FOUND
  MDdateMonitor theDataSource(fileName); // use date library to read from file or from the socket
#else
  MDfileManager theDataSource(fileName.c_str(), filePath.c_str()); // use stand alone unpacking to read from file only
#endif

  // Create a shared root file (with protected access for multithreading). 
  // A new file will be opened at each start of run
  
  //Set the variable for the number of spills before warning reset
  
  ifstream read("Spills_Before_Reset.txt");
 
  if(read.is_open()){
	  read >> Reset_Warning_Counter;	
	  std::cout<<"OnMon set up to reset warning after "<<Reset_Warning_Counter<<" spills."<<std::endl;
	}
	else std::cout<<"Config File not open!"<<std::endl;
  
  
  
  
  MDSharedRootFile theRootFile(rootFilePath);
 
 
  RefRootFile theRefFile(refFilePath);
 
 //Testing std::cerr<<"In main function: file :"<<theRefFile.GetNHistograms()<<std::endl;


  //Notify EPICS that the OnMon is running??
// EPICS CODE - Running
   #ifdef EPICS_FOUND
   if (!PVwrite.Set_PV_value("MICE-OL-ONMON-01:STA",1)) {
      std::cout << "Write status PV failed" << std::endl;
     
   }
   #endif	
   CurrentState=1;
   //Something to catch an ctrl-c exit:
   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);


	
  // Create and configure the process manager 
  MDprocessManager thePM;
   // Declare and define the processors
  OnFirstEvent*      firstEventProc = new OnFirstEvent(theRootFile);
  OnStartOfRun*      sorProc = new OnStartOfRun(theRootFile);
  OnEndOfRun*        eorProc = new OnEndOfRun(theRootFile);
  CREATE_HISTO_FILLER(DBB);
  CREATE_HISTO_FILLER(V1290);
  CREATE_HISTO_FILLER(V1724);
  CREATE_HISTO_FILLER(V1731);
  CREATE_HISTO_FILLER(V830);
  CREATE_HISTO_FILLER(DAQTrigger);
  CREATE_HISTO_FILLER(VLSB);
  FillMDHistogramPartTrigger*  fillPartTrg = new FillMDHistogramPartTrigger(theRootFile, theRefFile);  
  // can't use the macro for MDHistogramPartTrigger since it is not created using the template
 
  // Seting some parameters for the histogram filling processes. 
  // The pointer to the parameter should be casted properly in the MDHistogramXXX implementation 
  int limits[2];
  limits[0]=0 ; limits[1]=4096;
 // fillV1724->SetParameters(limits);

  // Set the user processors (can't automatize this part since the ProcessManager Set functions differ)
  thePM.SetFirstEventProc(firstEventProc); 
  thePM.SetStartOfRunProc(sorProc); 
  thePM.SetEndOfRunProc(eorProc);    
  thePM.SetSuperHeaderProc(fillDAQTrigger); 
  thePM.SetEquipmentHeaderProc(fillPartTrg); 
  thePM.SetFragmentProc("DBB",fillDBB);
  thePM.SetPartEventProc("V1290",fillV1290);
  thePM.SetPartEventProc("V1724",fillV1724);
  thePM.SetFragmentProc("VLSB",fillVLSB);
  thePM.SetPartEventProc("V1731",fillV1731);
  thePM.SetFragmentProc("V830",fillV830);

  // Let the user check the configuration
  thePM.DumpProcessors();
  // Disable decoding of CKOV FADC until it's fixed
  //thePM.Disable("V1731");

  // Start communication with the GUI on the ROOT socket
  
  MDComHandler theCom(theRootFile, theRefFile);  // The communication handler will serve histograms filled by the 
                                  // process manager on request from the miceOLMGUI process
  

  
  //MDComHandler theCom(theRootFile);
  // Loop over the DAQ events
//  unsigned char *eventBuffer;
  dateFileStatus_t fileStatus;
   
  try {
    fileStatus = theDataSource.OpenFile();
  }
  catch ( MDexception & lExc) {
    std::cerr << "Exception while trying to open the file " << std::endl;
    std::cerr <<  lExc.GetDescription() << endl;
 
    return 1;
  }
  
  //

  if ( fileStatus == DATE_FILE_OK ) {
	  if(!interrupted){
    try {
      eventBuffer =  theDataSource.GetNextEvent();
    }
    catch ( MDexception & lExc) {
      std::cerr << "Exception while trying to GetNextEvent() from the data source." << std::endl;
      std::cerr <<  lExc.GetDescription() << endl;
 
      return 1;
    }
   
   // std::cout<<"Run number is :" <<GetRunNumber()<<std::endl;
		while ( eventBuffer && theCom.IsActive() ) {
		  if (eventMax && nEvent>eventMax) break;
		  if(interrupted) break;
		  try {
			thePM.Process(eventBuffer); // Loop over the data and call the Proccess() function
										// of the appropriate MDprocessor object when the corresponding
										// structure is met.
		  }
		  
		  
		  catch ( MDexception & lExc) {
			 std::cerr << "Unpacking exception while processing the DAQ event.  DAQ Event skipped" << std::endl;
			 std::cerr <<  lExc.GetDescription() << endl;
		// EPICS CODE - state machine. 
		     SetEpicsExceptionState(nEvent, 1);
		
			

		  }
		  catch(std::exception & lExc) {
			std::cerr << "Standard exception" << std::endl;
			std::cerr << lExc.what() << std::endl;
			SetEpicsExceptionState(nEvent, 1);
		
	    
		  }
		  catch(...) {
			std::cerr << "Unknown exception occurred..." << std::endl;
			SetEpicsExceptionState(nEvent, 1);
		

		  }
		  nEvent++;
		//  std::cout<<"nEvent: "<<nEvent<<std::endl;
		  eventBuffer =  theDataSource.GetNextEvent();
		  SetEpicsExceptionState(nEvent, 0);
		  
		}
	}
  } else {
    cout << "Error in opening the file. Aborted." << endl;
  }
 
  theRootFile.Write();
  
  if (argh.GetValue("stay_alive")) {
    cout << " End of File. Press any key and then enter to quit the application" << endl ;
    string dummy;
    cin >> dummy;
  }
  return 0;



}