/[PAMELA software]/chewbacca/PamOffLineSW/PacketUser.cpp
ViewVC logotype

Diff of /chewbacca/PamOffLineSW/PacketUser.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1 by mocchiut, Tue Sep 23 07:20:12 2008 UTC revision 1.9 by mocchiut, Thu Oct 1 08:55:42 2009 UTC
# Line 1  Line 1 
1  //============================================================================  //============================================================================
2  // $Id: PacketUser.cpp,v 1.67 2008-09-05 14:33:48 messineo Exp $  // $Id: PacketUser.cpp,v 1.8 2009/08/05 18:48:42 pam-fi Exp $
3  // Description :  // Description :
4  //============================================================================  //============================================================================
5  #include "PacketUser.h"  #include "PacketUser.h"
6  #include <sys/time.h>  #include <sys/time.h>
7    
8  namespace PamOffLineSW  namespace PamOffLineSW {
 {  
9  extern LogUtil* mainLogUtil;  extern LogUtil* mainLogUtil;
10  extern short compression ;  extern short compression;
11  extern  char *outDir;  extern char *outDir;
12  extern TSQLServer *sqlServer;  extern TSQLServer *sqlServer;
13  extern bool multiFile;  extern bool multiFile;
14  extern char* fni;  extern char* fni;
# Line 17  extern char * nome_output; Line 16  extern char * nome_output;
16  extern bool is_new_route;  extern bool is_new_route;
17  extern unsigned int download;  extern unsigned int download;
18    
19  extern unsigned int  mmm_number;  extern unsigned int mmm_number;
20  extern unsigned int orbit_number;        extern unsigned int orbit_number;
21  extern unsigned long int time_Offset;  extern unsigned long int time_Offset;
22  extern bool tryMerge;  extern bool tryMerge;
23  //marco_new_01  //marco_new_01
# Line 28  extern bool single_connection; Line 27  extern bool single_connection;
27  extern bool do_cont_check;  extern bool do_cont_check;
28    
29  //marco_new_31:  //marco_new_31:
30  extern char*  db_user;  extern char* db_user;
31  extern char*  db_pwd;  extern char* db_pwd;
32  extern char* connection;          extern char* connection;
33    
34    //per tenere conto reset obt
35    extern unsigned long int max_pkt_obt;
36    
37    #define TAGVALUELEN 4
38    extern char tag_value[TAGVALUELEN];
39    
40  PacketUser PacketUser::instance;  PacketUser PacketUser::instance;
           
 int PacketUser::numDiscontinity=1;  
 int PacketUser::numPKT=0;  
 int PacketUser::numPKTSaved=0;  
   
 PacketUser& PacketUser::getInstance()  
 {  
         return instance;  
 }  
   
 PacketUser::PacketUser()  
 {        
         gROOT->SetBatch(kTRUE);          
         numDiscontinity=1;  
         numPKTSaved=0;  
         numPKT=0;        
         pkt_number_init=0;  
         obt_init=0;  
         pkt_number_last=0;  
         obt_last=0;  
         obt_time_sync=0;  
         last_time_sync_info=0;  
         real_time_init=0;  
         real_time_last=0;  
         bad_pkt=0;  
         bad_pkt_EventReader=0;  
         bad_pkt_CalibReader=0;  
         reader= NULL;  
         pRun=NULL;  
         reader=new pamela::techmodel::EventReader();  
         Table_ROOT_Good="ROOT_TABLE";  
         Table_ROOT_Bad="ROOT_TABLE_BAD";  
         Table_GL_RESURS_OFFSET="GL_RESURS_OFFSET";  
         Table_ROOT_Merging="ROOT_TABLE_MERGING";          
 //      good_pkt_Calib=0;  
         my_id=0;  
         boot_number=0;  
 }  
   
 PacketUser::~PacketUser()  
 {        
         if(reader){delete reader; reader = NULL;}  
         numDiscontinity=1;  
         numPKTSaved=0;  
         numPKT=0;  
         pkt_number_init=0;  
         obt_init=0;  
         pkt_number_last=0;  
         obt_last=0;  
         obt_time_sync = 0;  
         last_time_sync_info = 0;  
         real_time_init=0;  
         real_time_last=0;  
         bad_pkt=0;  
         bad_pkt_EventReader=0;  
         bad_pkt_CalibReader=0;  
 //      good_pkt_Calib=0;  
         my_id=0;          
         boot_number=0;  
 }  
   
 //Put the packet in a root file. Create a new ROOT file for each group of packets  
 void PacketUser::usePKT(char*& headerPkt, char*& pamPkt, long int length, bool isCons, bool isPKTGood, const PacketType* type,  
                 unsigned long int counter, unsigned long int obt)  
 {                        
         //If the packet type was not recognised before  
         if(!type){return;}  
             
           
 /*      //zzzzzz marco per debug mi salvo il pacchetto vardump  
         if(type==PacketType::VarDump)  
         {                
                 long int  dataLength = length - 2; //the block of data  
                 int b_offset = 4;  
                 while (b_offset < dataLength){  
                  boot_number  = (((UINT32)pamPkt[1+b_offset]<<24)&0xFF000000) + (((UINT32)pamPkt[2+b_offset]<<16)&0x00FF0000) +  (((UINT32)pamPkt[3+b_offset]<<8)&0x0000FF00) + (((UINT32)pamPkt[4+b_offset])&0x000000FF);  
                  cout<<"IN "<<numPKTSaved<<" boot_number "<<boot_number<<" al b_offset "<<b_offset<<" di "<<dataLength<<endl;  
                   
                  b_offset = b_offset + 5;  
                 }  
                   
                  cout<<"IN "<<numPKTSaved<<" FINAL boot_number "<<boot_number<<endl;  
                 savePKT_file(headerPkt,pamPkt,length,false,"vardump");  
                 numPKTSaved++;  
         }  
         return;  
 */  
           
           
         //in order to start ...  
         if(numPKT==0)  
         {                
                 //marco_new_31: metto qui se voglio avere come in origine apertura Connessione all'inizio e chiusura alla fine  
                 //marco_new_01    
                 if(single_connection){  
                         OpenDBConnection(NULL);  
                 }  
   
                 setInit(counter,obt);                            
                 StartGroup();  
         }  
                   
         //here we know if the incoming packet can be considered consecutive to the previuos     one              
         if((!isCons)&&(numPKT!=0))  
         {                        
                 setReal_Time();                          
                 //closing the  group in file rootfilename  
                 FinishGroup(rootfilename);                
                   
                 //numDiscontinity++;  
                 //se gia' e' cambiato download nn cambio numdisco  
                 if(!is_new_route) numDiscontinity++;  
                   
                 //the current pkt will be placed in a new group: rootfilename            
                 setInit(counter,obt);                    
                 StartGroup();  
         }  
           
         //add current packet to the group and calculate bad_pkt_EventReader and bad_pkt_CalibReader  
         int ret=  
         reader->PKT_RunEvent(headerPkt, pamPkt, length, type);  
         /*  
           ret  
             0    packet good  
             1    exception but used    //never happen  
             2    CRC exception but used  
             3    CALIBRATION PACKET with error but used  
            -1    CRC exception  packet DISCARDED  
            -2    FATAL exception packet DISCARDED //never happen  
            -3    No way to read events of this type. packet DISCARDED( es OLD CalibCal)  
         ret = 10 if the packet is good but comes from a cadre with VRL problems  
         */  
           
         //here we know if the packet comes from one or more corrupted cadres  
         //if(!isPKTGood){bad_pkt++;}  
         if((!isPKTGood)&&(!ret)){ret=10;}        
           
         switch (ret)  
         {  
                 case 0: {numPKTSaved++; break;}  
                 case 1: {bad_pkt_EventReader++; numPKTSaved++; break;}  
                 case 2: {bad_pkt_EventReader++;numPKTSaved++;  break;}  
                 case 3: {bad_pkt_CalibReader++; numPKTSaved++; break;}  
                 case 10: {bad_pkt++; numPKTSaved++; break;}  
                 default:{  
                         stringstream oss;  
                         oss.str()="";  
                         oss<<"Packet DISCARDED, reason = "<<ret;  
                         string msg = oss.str();  
                         mainLogUtil->logAll(msg);  
                         break;  
                 }  
         }  
   
 /*        
         if ((ret==0)&&((type==PacketType::CalibTrk1)||(type==PacketType::CalibTrk2)|| (type==PacketType::CalibCalPed)))  
         {                                
                 good_pkt_Calib++;//maybe I will remove this in future  
         }  
 */        
           
         if(ret>=0)// only the packet not discarded of course  
                 setLast(counter,obt);  
           
 //TODO: decide what kind of packet I can use here  
 //      if((ret==0)||(ret==10))//I want to use only good packet  
         if(ret>=0)//I want to use only accepted packet  
         {        
                 setTimeSync(pamPkt, length, type);//marco_new: here I retrieve also the boot_number if packet type is vardump  
         }  
   
         //just to be sure ...  
         if(pamPkt){delete[] pamPkt; pamPkt = NULL;}      
         //just to be sure ...  
         if(headerPkt){delete[] headerPkt; headerPkt = NULL;}  
41    
42          numPKT++;                int PacketUser::numDiscontinity = 1;
43    int PacketUser::numPKT = 0;
44    int PacketUser::numPKTSaved = 0;
45    
46    PacketUser& PacketUser::getInstance() {
47      return instance;
48    }
49    
50    PacketUser::PacketUser() {
51      gROOT->SetBatch(kTRUE);
52      numDiscontinity = 1;
53      numPKTSaved = 0;
54      numPKT = 0;
55      pkt_number_init = 0;
56      obt_init = 0;
57      pkt_number_last = 0;
58      obt_last = 0;
59      obt_time_sync = 0;
60      last_time_sync_info = 0;
61    
62      //(tassa)
63      obt_time_sync_prevvalue = 0;
64      last_time_sync_info_prevvalue = 0;
65      time_is_estimated = false;
66    
67      real_time_init = 0;
68      real_time_last = 0;
69      bad_pkt = 0;
70      bad_pkt_EventReader = 0;
71      bad_pkt_CalibReader = 0;
72      reader = NULL;
73      pRun = NULL;
74      reader = new pamela::techmodel::EventReader();
75      Table_ROOT_Good = "ROOT_TABLE";
76      Table_ROOT_Bad = "ROOT_TABLE_BAD";
77      Table_GL_RESURS_OFFSET = "GL_RESURS_OFFSET";
78      Table_ROOT_Merging = "ROOT_TABLE_MERGING";
79      //    good_pkt_Calib=0;
80      my_id = 0;
81      boot_number = 0;
82      //(tassa)
83      boot_number_prevvalue = 0;
84    
85      //(tassa)
86      //        id_to_recover[1000]; // Emiliano: che si vuole fare con questa riga? cosi` non fa nulla...
87      id_to_recover_index = 0;
88    }
89    
90    PacketUser::~PacketUser() {
91      if (reader) {
92        delete reader;
93        reader = NULL;
94      }
95      numDiscontinity = 1;
96      numPKTSaved = 0;
97      numPKT = 0;
98      pkt_number_init = 0;
99      obt_init = 0;
100      pkt_number_last = 0;
101      obt_last = 0;
102      obt_time_sync = 0;
103      last_time_sync_info = 0;
104      obt_time_sync_prevvalue = 0;
105      last_time_sync_info_prevvalue = 0;
106      time_is_estimated = false;
107    
108      real_time_init = 0;
109      real_time_last = 0;
110      bad_pkt = 0;
111      bad_pkt_EventReader = 0;
112      bad_pkt_CalibReader = 0;
113      //    good_pkt_Calib=0;
114      my_id = 0;
115      boot_number = 0;
116      boot_number_prevvalue = 0;
117    }
118    
119    //Put the packet in a root file. Create a new ROOT file for each group of packets
120    void PacketUser::usePKT(char*& headerPkt, char*& pamPkt, long int length, bool isCons, bool isPKTGood,
121        const PacketType* type, unsigned long int counter, unsigned long int obt) {
122      //If the packet type was not recognised before
123      if (!type) {
124        return;
125      }
126    
127      //in order to start ...
128      if (numPKT == 0) {
129        if (single_connection) {
130          OpenDBConnection(NULL);
131        }
132    
133        setInit(counter, obt);
134        StartGroup();
135      }
136    
137      //here we know if the incoming packet can be considered consecutive to the previuos   one
138      if ((!isCons) && (numPKT != 0)) {
139        setReal_Time();
140        //closing the group in file rootfilename
141        FinishGroup(rootfilename);
142    
143        //se gia' e' cambiato download non cambio numdisco
144        if (!is_new_route) {
145          numDiscontinity++;
146        }
147    
148        //the current pkt will be placed in a new group: rootfilename
149        setInit(counter, obt);
150        StartGroup();
151      }
152    
153      //add current packet to the group and calculate bad_pkt_EventReader and bad_pkt_CalibReader
154      int ret = reader->PKT_RunEvent(headerPkt, pamPkt, length, type);
155      /*
156       ret
157       0    packet good
158       1    exception but used    //never happen
159       2    CRC exception but used
160       3    CALIBRATION PACKET with error but used
161       -1    CRC exception  packet DISCARDED
162       -2    FATAL exception packet DISCARDED //never happen
163       -3    No way to read events of this type. packet DISCARDED( es OLD CalibCal)
164       ret = 10 if the packet is good but comes from a cadre with VRL problems
165       */
166    
167      //here we also know if the packet comes from one or more corrupted cadres
168      if ((!isPKTGood) && (!ret)) {
169        ret = 10;
170      }
171      switch (ret) {
172      case 0: {
173        numPKTSaved++;
174        break;
175      }
176      case 1: {
177        bad_pkt_EventReader++;
178        numPKTSaved++;
179        break;
180      }
181      case 2: {
182        bad_pkt_EventReader++;
183        numPKTSaved++;
184        break;
185      }
186      case 3: {
187        bad_pkt_CalibReader++;
188        numPKTSaved++;
189        break;
190      }
191      case 10: {
192        bad_pkt++;
193        numPKTSaved++;
194        break;
195      }
196      default: {
197        stringstream oss;
198        oss.str() = "";
199        oss << "Packet DISCARDED, reason = " << ret;
200        string msg = oss.str();
201        mainLogUtil->logAll(msg);
202        break;
203      }
204      }
205    
206      /*
207       if ((ret==0)&&((type==PacketType::CalibTrk1)||(type==PacketType::CalibTrk2)|| (type==PacketType::CalibCalPed)))
208       {
209       good_pkt_Calib++;//maybe I will remove this in future
210       }
211       */
212    
213      if (ret >= 0)// only the packet not discarded of course
214        setLast(counter, obt);
215    
216      //TODO: decide what kind of packet I can use here
217      //    if((ret==0)||(ret==10))//I want to use only good packet
218      if (ret >= 0)//I want to use only accepted packet
219      {
220        setTimeSync(pamPkt, length, type);//here I retrieve also the boot_number if packet type is vardump
221      }
222    
223      //just to be sure ...
224      if (pamPkt) {
225        delete[] pamPkt;
226        pamPkt = NULL;
227      }
228      if (headerPkt) {
229        delete[] headerPkt;
230        headerPkt = NULL;
231      }
232    
233      numPKT++;
234  }  }
235    
236  //set the value of the counter and obt of the first packet of the group  //set the value of the counter and obt of the first packet of the group
237  void PacketUser::setInit(unsigned long int counter, unsigned long int obt)  void PacketUser::setInit(unsigned long int counter, unsigned long int obt) {
238  {                                  sprintf(nnnn_mmm_ppp, "%05d_%03d_%03d", orbit_number, mmm_number, download);
239          sprintf(nnnn_mmm_ppp,"%05d_%03d_%03d", orbit_number, mmm_number, download);        sprintf(rootfilename, "%s_%s_%d", nome_output, nnnn_mmm_ppp, numDiscontinity);
240          sprintf(rootfilename,"%s_%s_%d", nome_output, nnnn_mmm_ppp, numDiscontinity);    pkt_number_init = counter;
241          pkt_number_init=counter;    obt_init = obt;
242          obt_init=obt;    pkt_number_last = 0;
243          pkt_number_last=0;    obt_last = 0;
244          obt_last=0;    real_time_init = 0;
245          real_time_init=0;    real_time_last = 0;
246          real_time_last=0;    bad_pkt = 0;
247          bad_pkt=0;          numPKTSaved = 0;
248          numPKTSaved=0;    bad_pkt_EventReader = 0;
249          bad_pkt_EventReader=0; bad_pkt_CalibReader=0;    bad_pkt_CalibReader = 0;
250          //good_pkt_Calib=0;    //good_pkt_Calib=0;
251            
252          //marco_NB:    //marco_NB:
253          //ogni volta che trovo una discontinuit� resetto come se mi trovassi in un nuovo download oppure uso i vecchi valori se esistono?    //ogni volta che trovo una discontinuit� resetto come se mi trovassi in un nuovo download oppure uso i vecchi valori se esistono?
254          obt_time_sync=0; last_time_sync_info=0; boot_number=0;  
255  //      NB: se ho discontinuita in genere non so a che download appartiene potrebbe proprio essere sbagliato tenere i vecchi valori    obt_time_sync_prevvalue = obt_time_sync;
256      last_time_sync_info_prevvalue = last_time_sync_info;
257      time_is_estimated = false;
258      obt_time_sync = 0;
259      last_time_sync_info = 0;
260      boot_number_prevvalue = boot_number;
261      boot_number = 0;
262    
263      //    NB: se ho discontinuita in genere non so a che download appartiene potrebbe proprio essere sbagliato tenere i vecchi valori
264    
265  }  }
266    
267  //starts a new root file  //starts a new root file
268  void PacketUser::StartGroup()  void PacketUser::StartGroup() {
269  {          pRun = new PamelaRun(rootfilename, gSystem->ExpandPathName(outDir), multiFile, compression); // EMI
270          pRun = new PamelaRun(rootfilename, outDir , multiFile, compression);    strcat(rootfilename, ".root");
271          //marco_new: aggiunta estensione .root    reader->Init(pRun);
272          strcat(rootfilename,".root");    stringstream oss;
273          reader->Init(pRun);                        oss.str() = "";
274          stringstream oss;    oss << "######################### Start a new group in file: " << rootfilename << " ############################";
275          oss.str()="";    string msg = oss.str();
276          oss<<"######################### Start a new group in file: "<< rootfilename <<" ############################";    mainLogUtil->logInfo(msg);
         string msg = oss.str();  
         mainLogUtil->logInfo(msg);  
277  }  }
278    
279  //set the value of the counter and obt of the last packet of the group  //set the value of the counter and obt of the last packet of the group
280  void PacketUser::setLast(unsigned long int counter, unsigned long int obt)  void PacketUser::setLast(unsigned long int counter, unsigned long int obt) {
281  {    pkt_number_last = counter;
282          pkt_number_last=counter;    obt_last = obt;
283          obt_last=obt;  }
284  }  
285    //retrieve obt_time_sync and last_time_sync_info from packet if type has special values and BOOT_NUMBER
286    void PacketUser::setTimeSync(char* packet, long int pktLength, const PacketType* type) {
287      //do nothing
288  //retrieve obt_time_sync and last_time_sync_info from packet if type has special values    if (!do_cont_check) {
289  void PacketUser::setTimeSync(char* packet, long int pktLength, const PacketType* type)      if (is_new_route)
290  {        is_new_route = false;
291      //do nothing      return;
292          if(!do_cont_check) {    }
293                  if(is_new_route)  
294                          is_new_route=false;    //TODO: usare anche MCMD ... NOTA: questo da sempre errore ret != 0
295                  return;    //In RunHeader e RunTrailer sono in secondi(?), controllare se aggiungo altri tipi di paccheti se invece sono in secondi
296          }    // devo ricalcolare tutto non per ogni gruppetto (ROOT file) ma solo se cambia download
297              //When I found a new download I need to reset all values
298  //TODO: usare anche MCMD ... NOTA: questo da sempre errore ret != 0    if (is_new_route) {
299  //In RunHeader e RunTrailer sono in secondi(?), controllare se aggiungo altri tipi di paccheti se invece sono in secondi      //reset
300                is_new_route = false;
301                //(tassa) ci ho ripensato se stiamo in un secondo download non prendiamo i bootnumber e timesync del precedente!
302          // devo ricalcolare tutto non per ogni gruppetto (ROOT file) ma solo se cambia download      obt_time_sync_prevvalue = 0;//obt_time_sync;
303                last_time_sync_info_prevvalue = 0;//last_time_sync_info;
304          //When I found a new download I need to reset all values  
305          if(is_new_route)      obt_time_sync = 0;
306          {        last_time_sync_info = 0;
307            //reset      boot_number_prevvalue = 0;//boot_number;
308                  is_new_route=false;      boot_number = 0;
309                  obt_time_sync=0; last_time_sync_info=0;      time_is_estimated = false;
310                  boot_number=0;      if (time_Offset)
311                  if(time_Offset)        timeOffset = time_Offset;
312                          timeOffset=time_Offset;      else
313                  else                    timeOffset = retrieveTimeOffset(Table_GL_RESURS_OFFSET);
314                          timeOffset=retrieveTimeOffset(Table_GL_RESURS_OFFSET);    }
315          }  
316              //retrieve boot number if possible
317          //retrieve boot number if possible    setBootNumber(packet, pktLength, type);
318          setBootNumber(packet,pktLength,type);  
319      //Retrieve if possible obt_time_sync and last_time_sync_info
320          //Retrieve if possible obt_time_sync and last_time_sync_info    int offset = 0;
321          int offset=0;    if (type == PacketType::RunHeader) {
322          if(type==PacketType::RunHeader)      offset = 0;
323          {                  }
324                  offset=0;    else if (type == PacketType::RunTrailer) {
325          }      offset = 3;
326          else if(type==PacketType::RunTrailer)    }
327          {          else if (type == PacketType::Mcmd) {
328                  offset=3;      //          mainLogUtil->logAll("TODO: Packet Mcmd now is not used to retrieve Absolute time. This may cause problems somewhere.");
329          }      return;
330          else if(type==PacketType::Mcmd)    }
331          {          else {
332  //              mainLogUtil->logAll("TODO: Packet Mcmd now is not used to retrieve Absolute time. This may cause problems somewhere.");      return;
333                  return;    }
334          }  
335          else    //I don't need to retrieve them again if they are good
336          {          if ((obt_time_sync) || (last_time_sync_info))
337                  return;      return;
338          }                
339              obt_time_sync = (((UINT32) packet[5 + offset] << 24) & 0xFF000000) + (((UINT32) packet[6 + offset] << 16)
340          //I don't need to retrieve them again if they are good        & 0x00FF0000) + (((UINT32) packet[7 + offset] << 8) & 0x0000FF00) + (((UINT32) packet[8 + offset]) & 0x000000FF);
341          if((obt_time_sync)||(last_time_sync_info)) return;    last_time_sync_info = (((UINT32) packet[9 + offset] << 24) & 0xFF000000) + (((UINT32) packet[10 + offset] << 16)
342          & 0x00FF0000) + (((UINT32) packet[11 + offset] << 8) & 0x0000FF00)
343          obt_time_sync = (((UINT32)packet[5+offset]<<24)&0xFF000000) + (((UINT32)packet[6+offset]<<16)&0x00FF0000) + (((UINT32)packet[7+offset]<<8)&0x0000FF00) + (((UINT32)packet[8+offset])&0x000000FF);        + (((UINT32) packet[12 + offset]) & 0x000000FF);
344          last_time_sync_info = (((UINT32)packet[9+offset]<<24)&0xFF000000) + (((UINT32)packet[10+offset]<<16)&0x00FF0000) + (((UINT32)packet[11+offset]<<8)&0x0000FF00) + (((UINT32)packet[12+offset])&0x000000FF);                
345      stringstream oss;
346          stringstream oss;    oss.str() = "";
347          oss.str()="";    oss << "In download: " << download << " timeOffset: " << timeOffset << " obt_time_sync: " << obt_time_sync
348          oss<<"In download: "<<download<<" timeOffset: "<<timeOffset<<" obt_time_sync: "<<obt_time_sync<<" last_time_sync_info: "<<last_time_sync_info<<" using Packet Type: "<<type->GetName().c_str();        << " last_time_sync_info: " << last_time_sync_info << " using Packet Type: " << type->GetName();
349          string msg = oss.str();    //    oss<<"In download: "<<download<<" timeOffset: "<<timeOffset<<" obt_time_sync: "<<obt_time_sync<<" last_time_sync_info: "<<last_time_sync_info<<" using Packet Type: "<<type->GetName().c_str();
350          mainLogUtil->logAll(msg);    string msg = oss.str();
351      mainLogUtil->logAll(msg);
352  }  }
353    
354  //Boot Number  //Boot Number
355  void PacketUser::setBootNumber(char* packet, long int pktLength, const PacketType* type)  void PacketUser::setBootNumber(char* packet, long int pktLength, const PacketType* type) {
356  {    //se gia calcolato esco: lo calcolo una volta per download e per continuita'
357          //se gia calcolato esco: lo calcolo una volta per download e per continuit�      if (boot_number)
358          if(boot_number) return;      return;
359  //todo: controlla se algo giusto: preso da VarDumpReader.cpp  
360  //mmm e' sbagliatissimo cambiare !!!        if (type == PacketType::VarDump) {
361          if(type==PacketType::VarDump)      int b_offset = 34;//4+5*6
362          {                            boot_number = (((UINT32) packet[1 + b_offset] << 24) & 0xFF000000) + (((UINT32) packet[2 + b_offset] << 16)
363                  long int  dataLength = pktLength - 2; //the block of data          & 0x00FF0000) + (((UINT32) packet[3 + b_offset] << 8) & 0x0000FF00) + (((UINT32) packet[4 + b_offset])
364                  int b_offset = 4;          & 0x000000FF);
365                  while (b_offset < dataLength){  
366                   boot_number  = (((UINT32)packet[1+b_offset]<<24)&0xFF000000) + (((UINT32)packet[2+b_offset]<<16)&0x00FF0000) +  (((UINT32)packet[3+b_offset]<<8)&0x0000FF00) + (((UINT32)packet[4+b_offset])&0x000000FF);      /*
367                   b_offset = b_offset + 5;       long int  dataLength = pktLength - 2; //the block of data
368                  }       int b_offset = 4;
369                  stringstream oss;       while (b_offset < dataLength){
370                  oss.str()="";       boot_number  = (((UINT32)packet[1+b_offset]<<24)&0xFF000000) + (((UINT32)packet[2+b_offset]<<16)&0x00FF0000) +  (((UINT32)packet[3+b_offset]<<8)&0x0000FF00) + (((UINT32)packet[4+b_offset])&0x000000FF);
371                  oss<<"In download: "<<download<<" boot_number: "<<boot_number<<" using Packet Type: "<<type->GetName().c_str();       b_offset = b_offset + 5;
372                  string msg = oss.str();       }
373                  mainLogUtil->logAll(msg);       */
374                  return;      stringstream oss;
375          }      oss.str() = "";
376          else      //          oss<<"In download: "<<download<<" boot_number: "<<boot_number<<" using Packet Type: "<<type->GetName().c_str();
377          {            oss << "In download: " << download << " boot_number: " << boot_number << " using Packet Type: " << type->GetName();
378                  return;      string msg = oss.str();
379          }                    mainLogUtil->logAll(msg);
380        return;
381      }
382      else {
383        return;
384      }
385    
386  }  }
387  //set the real time of the first packet and the last packet oif a group of packet if possible  //set the real time of the first packet and the last packet oif a group of packet if possible
388  void PacketUser::setReal_Time()  void PacketUser::setReal_Time() {
389  {  
390          if((obt_time_sync)||(last_time_sync_info))    if (!obt_time_sync && !last_time_sync_info && numPKTSaved > 1000) {
391          {                    time_is_estimated = true;
392                  real_time_init=(obt_init/1000-obt_time_sync)+last_time_sync_info;      obt_time_sync = obt_time_sync_prevvalue;
393                  real_time_last=(obt_last/1000-obt_time_sync)+last_time_sync_info;            last_time_sync_info = last_time_sync_info_prevvalue;
394                  real_time_init+=timeOffset;    }
395                  real_time_last+=timeOffset;                if (obt_time_sync || last_time_sync_info) {
396          }            real_time_init = (obt_init / 1000 - obt_time_sync) + last_time_sync_info;
397        //se obt si e' resettato
398        if (obt_last < obt_init) {
399          real_time_last = (max_pkt_obt / 1000 + obt_last / 1000 - obt_time_sync) + last_time_sync_info;
400          stringstream oss;
401          oss.str() = "";
402          oss << "obt_last(" << obt_last << ") < obt_init(" << obt_init
403              << "). It is due to Pamela Reset. Adding max_pkt_obt(" << max_pkt_obt
404              << ") to obt_last in order to compute real_time_last";
405          string msg = oss.str();
406          mainLogUtil->logWarning(msg);
407        }
408        else
409          real_time_last = (obt_last / 1000 - obt_time_sync) + last_time_sync_info;
410        real_time_init += timeOffset;
411        real_time_last += timeOffset;
412      }
413  }  }
414    
415  //timeOffset  //timeOffset
416  //retrieve from table Table_GL_RESURS_OFFSET timeOffset    //retrieve from table Table_GL_RESURS_OFFSET timeOffset  
417  unsigned long int PacketUser::retrieveTimeOffset(char * table)  unsigned long int PacketUser::retrieveTimeOffset(const char * table) {
418  {            if (!do_cont_check)
419          if(!do_cont_check) return 0;      return 0;
420            
421          //if(!table){table=Table_GL_RESURS_OFFSET}    //if(!table){table=Table_GL_RESURS_OFFSET}
422    
423          //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve    if (!single_connection) {
424          //marco_new_01        OpenDBConnection(table);//Nota qui ho deciso di lockare solo questa tabella e non tutte
425          if(!single_connection){    }
426                  OpenDBConnection(table);//Nota qui ho deciso di lockare solo questa tabella e non tutte  
427          }    UInt_t t0 = 0;//toffset
428      stringstream oss;
429          UInt_t t0 = 0;  //toffset                  oss.str("");
430                              oss
431          stringstream oss;        << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "
432          oss.str("");        << table << " WHERE SPECIAL_FILE='" << nnnn_mmm_ppp << "';";
433          oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "<<      table <<" WHERE SPECIAL_FILE='"  
434                << nnnn_mmm_ppp << "';";    string msg = oss.str();
435      mainLogUtil->logAll(msg);
436          string msg = oss.str();  
437          mainLogUtil->logAll(msg);          TSQLResult* res = NULL;
438      TSQLRow* row = NULL;
439          TSQLResult* res=NULL;                                res = sqlServer->Query(oss.str().c_str());
440          TSQLRow* row=NULL;          if (!res) {
441          res= sqlServer->Query(oss.str().c_str());                              mainLogUtil->logError("DBError retrieveTimeOffset 1");
442          if(!res)      return 0;
443          {                  }
444                  mainLogUtil->logError("DBError retrieveTimeOffset 1");  
445                  return 0;    row = res->Next();
446          }    if (!row) {
447        if (res) {
448      row=res->Next();        delete res;
449      if (!row )        res = NULL;
450      {      }
451          if(res){delete res; res = NULL;}  
452        oss.str("");
453          oss.str("");      oss
454          oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "<<      table <<" WHERE FROM_ORBIT < "          << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "
455          << orbit_number << " order by FROM_ORBIT desc limit 1;";          << table << " WHERE FROM_ORBIT < " << orbit_number << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
456            
457                  string msg2 = oss.str();      string msg2 = oss.str();
458                  mainLogUtil->logAll(msg2);      mainLogUtil->logAll(msg2);
459    
460                  res= sqlServer->Query(oss.str().c_str());                            res = sqlServer->Query(oss.str().c_str());
461          if(!res)      if (!res) {
462          {          mainLogUtil->logError("DBError retrieveTimeOffset 2");
463                  mainLogUtil->logError("DBError retrieveTimeOffset 2");        return 0;
464                  return 0;      }
465          }      row = res->Next();
466          row=res->Next();      if (!row) {
467          if (!row)        mainLogUtil->logError("DBError retrieveTimeOffset 3");
468          {        return 0;
469                  mainLogUtil->logError("DBError retrieveTimeOffset 3");      }
470                  return 0;  
471          }    }
472                    
473       }    TTimeStamp tu = TTimeStamp((UInt_t) atoi(row->GetField(0)), (UInt_t) atoi(row->GetField(1)), (UInt_t) atoi(
474              row->GetField(2)), (UInt_t) atoi(row->GetField(3)), (UInt_t) atoi(row->GetField(4)), (UInt_t) atoi(row->GetField(
475        TTimeStamp tu = TTimeStamp((UInt_t)atoi(row->GetField(0)),(UInt_t)atoi(row->GetField(1)),(UInt_t)atoi(row->GetField(2)),(UInt_t)atoi(row->GetField(3)),(UInt_t)atoi(row->GetField(4)),(UInt_t)atoi(row->GetField(5)),0,true,0);        5)), 0, true, 0);
476        t0 = (UInt_t)tu.GetSec();    t0 = (UInt_t) tu.GetSec();
477          
478          if(res){delete res; res = NULL;}    if (res) {
479          if(row){delete row; row = NULL;}              delete res;
480        res = NULL;
481          //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve    }
482          //marco_new_01      if (row) {
483          if(!single_connection){      delete row;
484                  CloseDBConnection();                  row = NULL;
485          }    }
486   return t0;  
487      if (!single_connection) {
488        CloseDBConnection();
489      }
490      return t0;
491  }  }
492    
493  //this is public and can be called from the main at the end of the game  //this is public and can be called from the main at the end of the game
494  void PacketUser::FinishLastGroup()  void PacketUser::FinishLastGroup() {
495  {          mainLogUtil->logAll("######################### Closing the last group ############################");
496          mainLogUtil->logAll("######################### Closing the last group ############################");      setReal_Time();
497          setReal_Time();    FinishGroup(rootfilename);
498          FinishGroup(rootfilename);    mainLogUtil->logAll("######################### Closed the last group ############################");
499          mainLogUtil->logAll("######################### Closed the last group ############################");    if (single_connection) {
500                CloseDBConnection();
501          //marco_new_31:metto qui se voglio avere come in origine apertura Connessione all'inizio e chiusura alla fine    }
         //marco_new_01    
         if(single_connection){  
                 CloseDBConnection();              
         }  
502  }  }
503    
504  //Finish the old root file  //Finish the old root file
505  void PacketUser::FinishGroup(char * filename)  void PacketUser::FinishGroup(char * filename) {
506  {    if (pRun) {
507          if(pRun)      pRun->WriteFiles();
508          {      delete pRun;
509                  pRun->WriteFiles();                                  pRun = NULL;
510                  delete pRun; pRun = NULL;                    stringstream close;
511                  stringstream close;      close.str() = "";
512                  close.str()="";      string msg;
513                  string msg;  
514        close << "######################### Close group in file: " << rootfilename << " ############################";
515                  close<<"######################### Close group in file: "<< rootfilename <<" ############################";      msg = close.str();
516                  msg = close.str();      mainLogUtil->logInfo(msg);
517                  mainLogUtil->logInfo(msg);  
518        // se non faccio proprio controlli su continuita' neanche salvo su DB
519                  // se non faccio proprio controlli su continuita' neanche salvo su DB      if (!do_cont_check)
520                  if(!do_cont_check) return;        return;
521            
522                  stringstream oss;      stringstream oss;
523                  oss.str()="";      oss.str() = "";
524                    
525                  //TODO: check when I don't want to log in DB informations      //TODO: check when I don't want to log in DB informations
526        // se non ho salvato nessun pacchetto
527                  // se non ho salvato nessun pacchetto      if (numPKTSaved == 0) {
528                  if(numPKTSaved==0){                            stringstream err;
529                          stringstream err;        err.str() = "";
530                          err.str()="";        err << "NO PACKET SAVED in file: " << rootfilename << " The group is empty: you can remove this file.";
531                          err<<"NO PACKET SAVED in file: "<< rootfilename <<" The group is empty: you can remove this file.";        msg = err.str();
532                          msg = err.str();        mainLogUtil->logError(msg);
533                          mainLogUtil->logError(msg);        return;
534                          return;      }
535                  }  
536                                //se non ho salvato nessun pacchetto buono
537                  //se non ho salvato nessun pacchetto buono      if ((numPKTSaved - bad_pkt_EventReader - bad_pkt_CalibReader - bad_pkt) == 0) {
538                  if((numPKTSaved-bad_pkt_EventReader-bad_pkt_CalibReader-bad_pkt)==0){                          stringstream err;
539                          stringstream err;        err.str() = "";
540                          err.str()="";        err << "NO GOOD PACKET SAVED in file: " << rootfilename << " The group is BAD: you may want to remove this file.";
541                          err<<"NO GOOD PACKET SAVED in file: "<< rootfilename <<" The group is BAD: you may want to remove this file.";        msg = err.str();
542                          msg = err.str();        mainLogUtil->logInfo(msg);
543                          mainLogUtil->logInfo(msg);        //                        mainLogUtil->logError(msg);
544  //                      mainLogUtil->logError(msg);        //                        return; //TODO: decidi se nn vuoi affatto usarlo o addirittura salvarlo tra i BAD???
545  //                      return; //TODO: decidi se nn vuoi affatto usarlo o addirittura salvarlo tra i BAD???      }
546                  }  
547        if (!single_connection) {
548                  //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve        OpenDBConnection(NULL);//Nota qui ho deciso di lockare tutte le tabelle
549                  //marco_new_01        }
550                  if(!single_connection){  
551                          OpenDBConnection(NULL);//Nota qui ho deciso di lockare tutte le tabelle      //don't save in Table_ROOT_Good and don't search for ROOT files in the same temporal range
552                  }      if ((!real_time_init) && (!real_time_last)) {
553                          //saved in another table for future study
554                  //don't save in Table_ROOT_Good and don't search for ROOT files in the same temporal range        if (saveROOT_DB(
555                  if((!real_time_init)&&(!real_time_last))            Table_ROOT_Bad,
556                  {            outDir,// here outDir is good, no expand EMI
557                          //saved in another table for future study            filename, pkt_number_init, pkt_number_last, obt_init, obt_last, obt_time_sync, last_time_sync_info,
558                          if(saveROOT_DB(Table_ROOT_Bad, outDir,            real_time_init, real_time_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
559                                                                  filename,            numPKTSaved, fni, time_is_estimated) == true) {
560                                                             pkt_number_init, pkt_number_last,          oss.str() = "";
561                                                             obt_init, obt_last,          oss << "Saved information regarding file: " << filename << " in table " << Table_ROOT_Bad;
562                                                             obt_time_sync, last_time_sync_info,              msg = oss.str();
563                                                             real_time_init, real_time_last,          mainLogUtil->logInfo(msg);
564                                                             boot_number,        }
565                                                             timeOffset,        else {
566                                                             bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader, numPKTSaved,          oss.str() = "";
567                                                             fni)==true)          oss << "Problem storing information in DB regarding file: " << filename;
568                                  {          msg = oss.str();
569                                          oss.str()="";          mainLogUtil->logError(msg);
570                                          oss<<"Saved information regarding file: "<<filename<<" in table "<<Table_ROOT_Bad;        }
571                                          msg = oss.str();  
572                                          mainLogUtil->logInfo(msg);              if (!single_connection) {
573                                  }          CloseDBConnection();
574                                  else        }
575                                  {        
576                                          oss.str()="";        return;
577                                          oss<<"Problem storing information in DB regarding file: "<<filename;      }
578                                          msg = oss.str();  
579                                          mainLogUtil->logError(msg);                  //saves info in DB in table Table_ROOT_Good
580                                  }                            if (boot_number == 0)
581                          boot_number = boot_number_prevvalue;
582                          //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve  
583                                  //marco_new_01        if (saveROOT_DB(
584                          if(!single_connection){          Table_ROOT_Good,
585                                  CloseDBConnection();                      outDir, // here outDir is good, no expand EMI
586                          }          filename, pkt_number_init, pkt_number_last, obt_init, obt_last, obt_time_sync, last_time_sync_info,
587            real_time_init, real_time_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
588                  return;          numPKTSaved, fni, time_is_estimated) == true) {
589                  }        oss << "Saved information regarding file: " << filename << " in table " << Table_ROOT_Good << " id= " << my_id;
590                                                  msg = oss.str();
591                  //saves info in DB in table Table_ROOT_Good        mainLogUtil->logInfo(msg);
592                  if(saveROOT_DB(Table_ROOT_Good, outDir,  
593                                          filename,        if (tryMerge) {
594                                     pkt_number_init, pkt_number_last,          merge_ROOTfiles();
595                                     obt_init, obt_last,        }
596                                     obt_time_sync, last_time_sync_info,          }
597                                     real_time_init, real_time_last,      else {
598                                     boot_number,        oss << "Problem storing information in DB regarding file: " << filename;
599                                     timeOffset,        msg = oss.str();
600                                     bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader, numPKTSaved,        mainLogUtil->logError(msg);
601                                     fni)==true)      }
602                  {                                                
603                          oss<<"Saved information regarding file: "<<filename<<" in table "<<Table_ROOT_Good<< " id= "<<my_id;      if (!single_connection) {
604                          msg = oss.str();        CloseDBConnection();
605                          mainLogUtil->logInfo(msg);            }
                           
                         //TODO : work on this ....                        
                         if(tryMerge){                            
                             merge_ROOTfiles();  
                         }  
                 }  
                 else  
                 {  
                         oss<<"Problem storing information in DB regarding file: "<<filename;  
                         msg = oss.str();  
                         mainLogUtil->logError(msg);      
                 }                                
   
                 //marco_new_31:metto qui se voglio apriree chiudere Connessione solo quando serve  
                         //marco_new_01    
                 if(!single_connection){  
                         CloseDBConnection();              
                 }  
606    
607          }//pRun    }//pRun
608  }  }
609    
   
610  //save in Table_ROOT_Good or in Table_ROOT_Bad  //save in Table_ROOT_Good or in Table_ROOT_Bad
611  bool PacketUser::saveROOT_DB(char* table_name, char* folder_name, char* file_name,  bool PacketUser::saveROOT_DB(const char* table_name, char* folder_name, char* file_name,
612                  unsigned long int pkt_number_in, unsigned long int pkt_number_fin,      unsigned long int pkt_number_in, unsigned long int pkt_number_fin, unsigned long int obt_in,
613                  unsigned long int obt_in, unsigned long int obt_fin,      unsigned long int obt_fin, unsigned long int oT_sync, unsigned long int lT_sync_info, unsigned long int mtime_init,
614                  unsigned long int  oT_sync, unsigned long int lT_sync_info,              unsigned long int mtime_last, unsigned long int mboot_num, unsigned long int time_offset, int bad_pkt,
615                  unsigned long int mtime_init,   unsigned long int mtime_last,      int bad_pkt_read, int bad_pkt_CalRead, int num_PKT_Saved, char* nome_input, bool _time_is_estimated) {
616                  unsigned long int mboot_num,    //TODO: forse far ritornare ID della cosa appena inserita se e' andatato tutto ok invece che true false?
617                  unsigned long int time_offset,      stringstream oss;
618                  int bad_pkt, int bad_pkt_read, int bad_pkt_CalRead, int num_PKT_Saved,              oss.str("");
619                  char* nome_input){                          oss << "INSERT INTO " << table_name
620          //TODO: forse far ritornare ID della cosa appena inserita se e' andatato tutto ok invece che true false?                << " (ID_N, FOLDER_NAME, FILE_NAME, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, OBT_TIME_SYNC, LAST_TIME_SYNC_INFO, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, TIME_OFFSET,BAD_PKT,BAD_PKT_READ,BAD_PKT_CALREAD,NUM_PKT_SAVED,INPUT_NAME,INSERT_TIME,TIME_IS_ESTIMATED)"
621          stringstream oss;        << " VALUES ('" << 0 << "','" << folder_name << "','" << file_name << "','" << pkt_number_in << "','"
622          oss.str("");            << pkt_number_fin << "','" << obt_in << "','" << obt_fin << "','" << oT_sync << "','" << lT_sync_info << "','"
623          oss << "INSERT INTO "<< table_name <<" (ID_N, FOLDER_NAME, FILE_NAME, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, OBT_TIME_SYNC, LAST_TIME_SYNC_INFO, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, TIME_OFFSET,BAD_PKT,BAD_PKT_READ,BAD_PKT_CALREAD,NUM_PKT_SAVED,INPUT_NAME,INSERT_TIME)"        << mtime_init << "','" << mtime_last << "','" << mboot_num << "','" << time_offset << "','" << bad_pkt << "','"
624      << " VALUES ('"<<0<< "','" <<folder_name<<"','" <<file_name<< "','" << pkt_number_in <<"','"<< pkt_number_fin << "','"<< obt_in <<"','"<< obt_fin<< "','"        << bad_pkt_read << "','" << bad_pkt_CalRead << "','" << num_PKT_Saved << "','" << nome_input << "'," << "NULL,"
625      << oT_sync << "','" << lT_sync_info << "','"        << _time_is_estimated << ");";
626      << mtime_init << "','" << mtime_last << "','"    string msg = oss.str();
627          << mboot_num << "','"    mainLogUtil->logAll(msg);
628      << time_offset << "','"  
629      << bad_pkt <<"','" << bad_pkt_read <<"','"<< bad_pkt_CalRead <<"','"<< numPKTSaved<<"','"    stringstream oss1;
630      << nome_input <<"',"    oss1.str() = "";
631      <<"NULL"<<          string msg1;
632      ")";                string query;
633          string msg = oss.str();  
634          mainLogUtil->logAll(msg);          TSQLResult* res = NULL;
635            
636          stringstream oss1;    query = oss.str();
637          oss1.str()="";    msg1 = "SaveROOT_DB query: ";
638          string msg1;    msg1 += query;
639        mainLogUtil->logInfo(msg1);
640     TSQLResult* res=NULL;          
641     res= sqlServer->Query(oss.str().c_str());    res = sqlServer->Query(query.c_str());
642     if(!res)    if (!res) {
643     {          oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
644             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        msg1 = oss1.str();
645             msg1=oss1.str();      mainLogUtil->logError(msg1);
646             mainLogUtil->logError(msg1);        return false;
647             return false;    }
648     }  
649      //the ID of the current ROOT file in table Table_ROOT_Good
650      my_id = select_maxIDN_DB(table_name);
651      if (!boot_number) {
652        if (id_to_recover_index < 1000)
653          id_to_recover[id_to_recover_index++] = my_id;
654      }
655      else if (boot_number && id_to_recover_index && !is_new_route) {
656        recover_boot_number();
657      }
658      //    cout<<"DBG: my_id = "<<my_id<<endl;
659      if (res) {
660        delete res;
661        res = NULL;
662      }
663      return true;
664    }
665    
666    void PacketUser::recover_boot_number() {
667      string msg1;
668      stringstream oss1;
669      stringstream oss;
670      oss.str("");
671      string query = "";
672      TSQLResult* res = NULL;
673      if (!boot_number || !id_to_recover_index)
674        return;
675    
676      for (int i = 0; i < id_to_recover_index; i++) {
677        oss.str("");
678        oss << "UPDATE " << Table_ROOT_Good << " SET BOOT_NUMBER=" << boot_number << " WHERE ID_N=" << id_to_recover[i]
679            << ";";
680        query = oss.str();
681        res = sqlServer->Query(query.c_str());
682        if (!res) {
683          oss1 << "DBError UNABLE to: " << query.c_str() << endl;
684          msg1 = oss1.str();
685          mainLogUtil->logError(msg1);
686          return;
687        }
688      }
689    
690      for (int i = 0; i < id_to_recover_index; i++) {
691        oss.str("");
692        oss << "UPDATE " << Table_ROOT_Merging << " SET BOOT_NUMBER=" << boot_number << " WHERE ROOT_ID_N="
693            << id_to_recover[i] << ";";
694        query = oss.str();
695        res = sqlServer->Query(query.c_str());
696        if (!res) {
697          oss1 << "DBError UNABLE to: " << query.c_str() << endl;
698          msg1 = oss1.str();
699          mainLogUtil->logError(msg1);
700          return;
701        }
702      }
703    
704     //marco_new: si pu� ottimizzare ...    id_to_recover_index = 0;
    //the ID of the current ROOT file in table Table_ROOT_Good  
          my_id = select_maxIDN_DB(table_name);  
 //      cout<<"DBG: my_id = "<<my_id<<endl;  
    if(res){delete res; res = NULL;}  
    return true;  
705  }  }
706    
707  /**********************************************************************************************/  /**********************************************************************************************/
708  /*###########################################################################################################*/  /*###########################################################################################################*/
709  /**********************************         MERGING          *************************************************/  /**********************************         MERGING          *************************************************/
710  /*###########################################################################################################*/  /*###########################################################################################################*/
711  //      Merge ROOT files: found other ROOT files in the same temporal ranges  //      Merge ROT files: find other ROOT files in the same temporal ranges
712  //    it finds ROOT files that covers particular temporal range of interest and save this info in DB  //    it finds ROOT files that covers particular temporal range of interest and save this info in DB
713  /**********************************************************************************************/  /**********************************************************************************************/
714  //try to merge current ROOT file with files in DB  //try to merge current ROOT file with files in DB
715  bool PacketUser::merge_ROOTfiles()  bool PacketUser::merge_ROOTfiles() {
716  {    stringstream log;
717          mainLogUtil->logInfo("Trying merging ROOT files");    log.str("");
718      string slog;
719    
720      mainLogUtil->logInfo("Trying merging ROOT files");
721      double percentage = (double) (bad_pkt + bad_pkt_EventReader + bad_pkt_CalibReader) / numPKTSaved;
722    
723      TSQLResult* res = NULL;
724      TSQLRow* row = NULL;
725      //numero di ROOT files trovati sul DB che hanno relaz di tipo dato
726      unsigned int num_rows = 0;
727    
728      //Record su DB:
729      unsigned int idN = 0;
730      unsigned int root_id_db = 0;
731      unsigned long int pkt_num_in_db = 0;
732      unsigned long int pkt_num_fin_db = 0;
733      unsigned long int pkt_obt_in_db = 0;
734      unsigned long int pkt_obt_fin_db = 0;
735      unsigned long int time_in_db = 0;
736      unsigned long int time_fin_db = 0;
737      unsigned int boot_num_db = 0;
738      double perc = 0;
739    
740    //marco_new: controlla    //marco_new: non considero mai caso di continuita'(mio finale=DB iniz o viceversa), non mi interessa
   double percentage=(double)(bad_pkt+bad_pkt_EventReader+bad_pkt_CalibReader)/numPKTSaved;  
                   
   TSQLResult* res=NULL;    
   TSQLRow* row =NULL;  
   
   //marco_new: non considero mai caso di continuit�(mio finale=DB iniz o viceversa), non mi interessa  
741    //marco_new: after e before contengono anche smaller ma con un bordo comune    //marco_new: after e before contengono anche smaller ma con un bordo comune
742    for(int relaz=AFTER; relaz<=BIGGER; relaz++)    for (int relaz = AFTER; relaz <= BIGGER; relaz++) {
743    {                  //marco_new: esci se sono arrivato a zero
744          //marco_new: controlla tutto      if (real_time_last == real_time_init) {
745          //marco_new: esci se sono arrivato a zero        log.str("");
746          if(real_time_last==real_time_init){            log << "Current File Lenght=0; real_time_last=real_time_init= " << real_time_last;
747                  mainLogUtil->logInfo("Finish merging ROOT files");                      slog = log.str();
748                  if(res){delete res; res = NULL;}        mainLogUtil->logAll(slog);
749                  if(row){delete row; row = NULL;}        mainLogUtil->logInfo("Finish merging ROOT files");
750                  return true;                                    if (res) {
751          }          delete res;
752            res = NULL;
753          res = Select_merging(Table_ROOT_Merging, real_time_init, real_time_last, (type_Rel_ROOT)relaz);        }
754                  if (row) {
755          unsigned int num_rows=0;          delete row;
756           if (!res)          row = NULL;
757           {        }
758                  mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged RES=null");        return true;
759                   return false;      }
760           }  
761        num_rows = 0;
762           num_rows=res->GetRowCount();      res = Select_merging(Table_ROOT_Merging, real_time_init, real_time_last, (type_Rel_ROOT) relaz);
763  //       cout<<"MMMMM trovati num_rows "<< num_rows<< " per relaz= "<<relaz;  
764        if (!res) {
765           if(num_rows>0)        mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged RES=null");
766           {                              return false;
767                   for(unsigned int i=0; i<num_rows; i++)      }
768                   {  
769                           row=res->Next();      num_rows = res->GetRowCount();
770                           if (!row)      log.str("");
771                           {      log << "Found " << num_rows << " ROOT file in DB with relation of kind = " << relaz;
772                                   mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged. ROW=null");      slog = log.str();
773                                  if(res){delete res; res = NULL;}      mainLogUtil->logAll(slog);
774                                  return false;  
775                           }      if (num_rows > 0) {
776                                  for (unsigned int i = 0; i < num_rows; i++) {
777            row = res->Next();
778                          //TODO ricavare tutte le info che servono          if (!row) {
779                          unsigned int idN = 0;                  mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged. ROW=null");
780                          idN=atoi(row->GetField(0));            if (res) {
781                                delete res;
782                          double perc =0;                              res = NULL;
783                          //marco_new:            }
784                          perc=atof(row->GetField(9));            return false;
785                          //unsigned long int M_pkt_number_in, M_pkt_number_fin, M_obt_in, M_obt_fin, M_mtime_init, M_mtime_last;          }
786                          if(perc>percentage){  
787                                  mainLogUtil->logInfo("Current ROOT file is better than the one in DB");                          //Leggi Record dal DB:
788                                  //modifica DB          idN = atoll(row->GetField(0));
789                                  updateMergeROOT_DB(Table_ROOT_Merging,          root_id_db = atoll(row->GetField(1));
790                                          atoi(row->GetField(1)), atoi(row->GetField(2)),          pkt_num_in_db = atoll(row->GetField(2));
791                                          atoi(row->GetField(3)), atoi(row->GetField(4)),          pkt_num_fin_db = atoll(row->GetField(3));
792                                          atoi(row->GetField(5)), atoi(row->GetField(6)),          pkt_obt_in_db = atoll(row->GetField(4));
793                                          atoi(row->GetField(7)), atoi(row->GetField(8)),          pkt_obt_fin_db = atoll(row->GetField(5));
794                                          perc,          time_in_db = atoll(row->GetField(6));
795                                          idN,(type_Rel_ROOT)relaz);          time_fin_db = atoll(row->GetField(7));
796                          }          boot_num_db = atoll(row->GetField(8));
797                          else{          perc = atof(row->GetField(9));
798                                  mainLogUtil->logInfo("Found ROOT files in DB better than current ROOT file");            
799            log.str("");
800                                  if(relaz == AFTER){          log << "*** ROOT file found in DB has idN= " << idN << "  root_id_db= " << root_id_db;
801                                          mainLogUtil->logInfo("Relaz:AFTER = Changing Init values of the Current ROOT file");          log << " pkt_num_in_db= " << pkt_num_in_db << "  pkt_num_fin_db= " << pkt_num_fin_db << "  pkt_obt_in_db= "
802                                          pkt_number_init= atoi(row->GetField(3));              << pkt_obt_in_db << "  pkt_obt_fin_db= " << pkt_obt_fin_db;
803                                          obt_init= atoi(row->GetField(5));          log << "  time_in_db= " << time_in_db << "  time_fin_db= " << time_fin_db << " boot_num_db= " << boot_num_db
804                                          real_time_init= atoi(row->GetField(7));                                              << "  perc= " << perc << "  ***";
805                                  }          log << "\n*** Current ROOT file has pkt_number_init= " << pkt_number_init << "  obt_init= " << obt_init
806                                  else if(relaz == BEFORE){              << "  real_time_init= " << real_time_init;
807                                          mainLogUtil->logInfo("Relaz:BEFORE = Changing Last values of the Current ROOT file");                    log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
808                                          pkt_number_last= atoi(row->GetField(2));              << real_time_last << " ***";
809                                          obt_last= atoi(row->GetField(4));          slog = log.str();
810                                          real_time_last= atoi(row->GetField(6));          mainLogUtil->logAll(slog);
811                                  }          if (perc > percentage) {
812                                  else if(relaz == SMALLER)            mainLogUtil->logInfo("Current ROOT file is better than the one in DB");
813                                  {            //modifica DB
814                                          //non devo proprio salvarlo ed esco ...                                    updateMergeROOT_DB(Table_ROOT_Merging, root_id_db, pkt_num_in_db, pkt_num_fin_db, pkt_obt_in_db,
815                                          mainLogUtil->logInfo("Relaz:SMALLER = Nothing to save");                pkt_obt_fin_db, time_in_db, time_fin_db, boot_num_db, perc, idN, (type_Rel_ROOT) relaz);
816                                          mainLogUtil->logInfo("Finish merging ROOT files");          }
817                                          if(res){delete res; res = NULL;}          else {
818                                          if(row){delete row; row = NULL;}            mainLogUtil->logInfo("Found ROOT file in DB is better than current ROOT file");
819                                          return true;            if (relaz == AFTER) {
820                                  }              mainLogUtil->logInfo("Relaz:AFTER = Changing Init values of the Current ROOT file");
821                                  else if(relaz == BIGGER)//spezzettamento              pkt_number_init = (pkt_num_fin_db + 1);
822                                  {                    obt_init = pkt_obt_fin_db;
823                                          mainLogUtil->logInfo("Relaz:BIGGER = (1st part) Saving the first part of the Current ROOT file");                                                                    real_time_init = time_fin_db;
824                                          saveMergeROOT_DB(Table_ROOT_Merging, my_id,              log.str("");
825                                                  pkt_number_init, atoi(row->GetField(2)),              log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
826                                                  obt_init, atoi(row->GetField(4)),                  << obt_init << "  real_time_init= " << real_time_init;
827                                                  real_time_init, atoi(row->GetField(6)),              log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
828                                                  boot_number,                  << real_time_last << " ***";
829                                                  percentage);              slog = log.str();
830                                                                                mainLogUtil->logAll(slog);
831                                          mainLogUtil->logInfo("Relaz:BIGGER = (2nd part)Changing Init values of the Current ROOT file");            }
832                                          pkt_number_init= atoi(row->GetField(3));            else if (relaz == BEFORE) {
833                                          obt_init= atoi(row->GetField(5));              mainLogUtil->logInfo("Relaz:BEFORE = Changing Last values of the Current ROOT file");
834                                          real_time_init= atoi(row->GetField(7));              pkt_number_last = (pkt_num_in_db - 1);
835                                  }              obt_last = pkt_obt_in_db;
836                          }              real_time_last = time_in_db;
837                  }//for num_rows      
838            }              log.str("");
839          else{              log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
840                  //marco_new:                  << obt_init << "  real_time_init= " << real_time_init;
841                  mainLogUtil->logInfo("Found 0 ROOT files in DB that can be merged with current ROOT file");                          log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
842                    << real_time_last << " ***";
843          }              slog = log.str();
844                mainLogUtil->logAll(slog);
845          //marco_new:???            }
846          if(res){delete res; res = NULL;}            else if (relaz == SMALLER) {
847          if(row){delete row; row = NULL;}                      //non devo proprio salvarlo ed esco ...
848  }//for              mainLogUtil->logInfo("Relaz:SMALLER = Nothing to save");
849                mainLogUtil->logInfo("\nFinish merging ROOT files");
850          mainLogUtil->logInfo("Saving Current ROOT file");                    if (res) {
851          saveMergeROOT_DB(Table_ROOT_Merging, my_id,                delete res;
852                           pkt_number_init, pkt_number_last,                res = NULL;
853                           obt_init, obt_last,              }
854                           real_time_init, real_time_last,              if (row) {
855                           boot_number,                delete row;
856                           percentage);                row = NULL;
857                }
858                return true;
859              }
860              else if (relaz == BIGGER)//spezzettamento
861              {
862                mainLogUtil->logInfo("Relaz:BIGGER = (1st part) Saving the first part of the Current ROOT file");
863                saveMergeROOT_DB(Table_ROOT_Merging, my_id, pkt_number_init, (pkt_num_in_db - 1), obt_init, pkt_obt_in_db,
864                    real_time_init, time_in_db, boot_number, percentage);
865    
866                mainLogUtil->logInfo("Relaz:BIGGER = (2nd part)Changing Init values of the Current ROOT file");
867                pkt_number_init = (pkt_num_fin_db + 1);
868                obt_init = pkt_obt_fin_db;
869                real_time_init = time_fin_db;
870    
871                log.str("");
872                log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
873                    << obt_init << "  real_time_init= " << real_time_init;
874                log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
875                    << real_time_last << " ***";
876                slog = log.str();
877                mainLogUtil->logAll(slog);
878              }//if relaz
879            }//if perc
880          }//for num_rows
881        }//if num_rows
882    
883        if (res) {
884          delete res;
885          res = NULL;
886        }
887        if (row) {
888          delete row;
889          row = NULL;
890        }
891    
892      }//for relaz
893    
894      mainLogUtil->logInfo("Saving Current ROOT file");
895      saveMergeROOT_DB(Table_ROOT_Merging, my_id, pkt_number_init, pkt_number_last, obt_init, obt_last, real_time_init,
896          real_time_last, boot_number, percentage);
897    
898          mainLogUtil->logInfo("Finish merging ROOT files");          mainLogUtil->logInfo("Finish merging ROOT files");
899    return true;    return true;
900    
901  }  }
902    
903  //unsigned int root_id,  percentage non le devo modificare  //unsigned int root_id,  percentage non le devo modificare
904  bool PacketUser::updateMergeROOT_DB(char* table_name,  bool PacketUser::updateMergeROOT_DB(const char* table_name, unsigned int root_id, unsigned long int pkt_number_in,
905                          unsigned  int root_id,      unsigned long int pkt_number_fin, unsigned long int obt_in, unsigned long int obt_fin,
906                          unsigned long int pkt_number_in, unsigned long int pkt_number_fin,      unsigned long int mtime_init, unsigned long int mtime_last, unsigned long int mboot_num, double bad_perc,
907                          unsigned long int obt_in, unsigned long int obt_fin,      unsigned int ID_record, type_Rel_ROOT type_rel) {
908                  unsigned long int mtime_init,   unsigned long int mtime_last,  
909                          unsigned long int mboot_num,    stringstream oss;
910                          double bad_perc,    oss.str("");
911                          unsigned int ID_record, type_Rel_ROOT type_rel){  
912          stringstream oss;    if (type_rel == AFTER) {
913          oss.str("");          mainLogUtil->logInfo("Relaz:AFTER = Updating Last values of the DB ROOT file");
914                //marco_new:tolti tutti gli apici che qui non devono essere
915          if(type_rel == AFTER){      oss << "UPDATE " << table_name << " SET PKT_NUMBER_FINAL =" << (pkt_number_init - 1) << ", PKT_OBT_FINAL ="
916                  mainLogUtil->logInfo("Relaz:AFTER = Updating Last values of the DB ROOT file");          << obt_init << ", REAL_TIME_LAST =" << real_time_init << " WHERE ID_N =" << ID_record << ";";
917                  //marco_new:tolti tutti gli apici che qui non devono essere  
918                  oss << "UPDATE "<< table_name    }
919                  << " SET PKT_NUMBER_FINAL ="<< pkt_number_init      else if (type_rel == BEFORE) {
920                          <<", PKT_OBT_FINAL ="<< obt_init      mainLogUtil->logInfo("Relaz:BEFORE = Updating Init values of the DB ROOT file");
921                      <<", REAL_TIME_LAST ="<< real_time_init<<" WHERE ID_N ="<< ID_record <<";";      oss << "UPDATE " << table_name << " SET PKT_NUMBER_INIT =" << (pkt_number_last + 1) << ", PKT_OBT_INIT ="
922          }          << obt_last << ", REAL_TIME_INIT =" << real_time_last << " WHERE ID_N =" << ID_record << ";";
923          else if(type_rel == BEFORE){                }
924                          mainLogUtil->logInfo("Relaz:BEFORE = Updating Init values of the DB ROOT file");            else if (type_rel == SMALLER) {
925                  oss << "UPDATE "<< table_name      //spezzettamentento
926                  << " SET PKT_NUMBER_INIT ="<< pkt_number_last        mainLogUtil->logInfo("Relaz:SMALLER = (1st part) Updating Last values of the DB ROOT file");
927                          <<", PKT_OBT_INIT ="<< obt_last  
928                      <<", REAL_TIME_INIT ="<< real_time_last<<" WHERE ID_N ="<< ID_record<<";";      oss << "UPDATE " << table_name << " SET PKT_NUMBER_FINAL=" << (pkt_number_init - 1) << ", PKT_OBT_FINAL ="
929          }          << obt_init << ", REAL_TIME_LAST =" << real_time_init << " WHERE ID_N =" << ID_record << ";";
930          else if(type_rel == SMALLER){            
931                  //spezzettamentento      mainLogUtil->logInfo("Relaz:SMALLER = (2nd part) Saving the second part of the DB ROOT file");
932                  mainLogUtil->logInfo("Relaz:SMALLER = (1st part) Updating Last values of the DB ROOT file");                                                      
933                saveMergeROOT_DB(table_name, root_id, (pkt_number_last + 1), pkt_number_fin, obt_last, obt_fin, real_time_last,
934                  oss << "UPDATE "<< table_name          mtime_last, mboot_num, bad_perc);
935                          << " SET PKT_NUMBER_FINAL="<< pkt_number_init      }
936                          <<", PKT_OBT_FINAL ="<< obt_init    else if (type_rel == BIGGER) {
937                              <<", REAL_TIME_LAST ="<< real_time_init<<" WHERE ID_N ="<< ID_record<<";";      //marco_new: ok anche se coincidenti etc
938                        //    oss << "DELETE FROM "<< table_name <<" WHERE ID_N ="<< ID_record<<";"; // EMILIANO
939                          mainLogUtil->logInfo("Relaz:SMALLER = (2nd part) Saving the second part of the DB ROOT file");                                                oss << "UPDATE " << table_name << " SET GOOD=0 WHERE ID_N =" << ID_record << ";"; // EMILIANO DO NOT DELETE FROM ROOT_TABLE_MERGING JUST SET GOOD FLAG TO ZERO
940        mainLogUtil->logInfo("Record deleted from merging table");
941                          saveMergeROOT_DB(table_name, root_id,    }
942                           pkt_number_last, pkt_number_fin,    else
943                           obt_last, obt_fin,      return false;
944                           real_time_last, mtime_last,  
945                           mboot_num,    string msg = oss.str();
946                           bad_perc);    mainLogUtil->logInfo(msg);
947          }  
948          else if(type_rel == BIGGER){    stringstream oss1;
949          //marco_new: ok anche se coincidenti etc    oss1.str() = "";
950            oss << "DELETE FROM "<< table_name <<" WHERE ID_N ="<< ID_record<<";";    string msg1;
951            mainLogUtil->logInfo("Rimosso record in Tabella merging");      
952          }    TSQLResult* res = NULL;
953          else    res = sqlServer->Query(oss.str().c_str());
954                  return false;    if (!res) {
955        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
956        msg1 = oss1.str();
957        mainLogUtil->logError(msg1);
958          string msg = oss.str();      return false;
959          mainLogUtil->logInfo(msg);          }
960              if (res) {
961          stringstream oss1;      delete res;
962          oss1.str()="";      res = NULL;
963          string msg1;    }
964        return true;
    TSQLResult* res=NULL;          
    res= sqlServer->Query(oss.str().c_str());  
    if(!res)  
    {      
            oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;    
            msg1=oss1.str();  
            mainLogUtil->logError(msg1);    
            return false;  
    }  
    if(res){delete res; res = NULL;}  
    return true;  
965  }  }
966    
967  //marco_new: check here  //cerca eventuali ROOT files in DB che possono venire mergiati
968  TSQLResult* PacketUser::Select_merging(char* table_name, unsigned long int mtime_init, unsigned long int mtime_last, type_Rel_ROOT type_rel)  //marco_new bordi: messo in after a before casi in cui smaller con un bordo in comune
969  {  //marco_new bordi: messo in bigger casi con bordi in comune; tra questi anche caso particolare di coincidente
970    //marco_new bordi: smaller resta solo caso in cui DB e' piu largo sia a dx che a sx
971  //      unsigned  int idN=0;  TSQLResult* PacketUser::Select_merging(const char* table_name, unsigned long int mtime_init, unsigned long int mtime_last,
972          TSQLResult* res=NULL;      type_Rel_ROOT type_rel) {
973          stringstream query;    TSQLResult* res = NULL;
974          query.str("");    stringstream query;
975      query.str("");
976          //marco_new bordi: messo in after a before casi in cui smaller con un bordo in comune  
977          //marco_new bordi: messo in bigger casi con bordi in comune; tra questi anche caso particolare di coincidente    if (type_rel == AFTER)
978          //marco_new bordi: smaller resta solo caso in cui DB � piu largo sia a dx che a sx      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_LAST > " << mtime_init
979          if(type_rel == AFTER)          << " and REAL_TIME_LAST <= " << mtime_last << " and REAL_TIME_INIT < " << mtime_init; // EMI
980            query<<"select * from "<<table_name<<" where REAL_TIME_LAST > "<< mtime_init <<" and REAL_TIME_LAST <= "<< mtime_last <<" and REAL_TIME_INIT < "<< mtime_init;    else if (type_rel == BEFORE)
981          else if(type_rel == BEFORE)      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT >= " << mtime_init
982            query<<"select * from "<<table_name<<" where REAL_TIME_INIT >= "<< mtime_init <<" and REAL_TIME_INIT < "<< mtime_last <<" and REAL_TIME_LAST > "<< mtime_last;          << " and REAL_TIME_INIT < " << mtime_last << " and REAL_TIME_LAST > " << mtime_last; // EMI
983          else if(type_rel == SMALLER)    else if (type_rel == SMALLER)
984            query<<"select * from "<<table_name<<" where REAL_TIME_INIT < "<< mtime_init <<" and REAL_TIME_LAST > "<< mtime_last;      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT < " << mtime_init
985          else if(type_rel == BIGGER)          << " and REAL_TIME_LAST > " << mtime_last; // EMI
986                  query<<"select * from "<<table_name<<" where REAL_TIME_INIT >= "<< mtime_init <<" and REAL_TIME_LAST <= "<< mtime_last;    else if (type_rel == BIGGER)
987          else      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT >= " << mtime_init
988                  return 0;          << " and REAL_TIME_LAST <= " << mtime_last; // EMI
989              else
990          query<< " order by REAL_TIME_INIT ASC";//marco_new: inutile      return 0;
991          //      query<<" and NUM_PKT_SAVED - BAD_PKT_CALREAD - BAD_PKT_READ - BAD_PKT >= 2" ;  
992              query << " order by REAL_TIME_INIT ASC";//marco_new: inutile
993        //se volessi mettere un filtro sulla qualita'
994          string msg = query.str();    //    query<<" and NUM_PKT_SAVED - BAD_PKT_CALREAD - BAD_PKT_READ - BAD_PKT >= 2" ;
995          mainLogUtil->logAll(msg);    string msg = query.str();
996      mainLogUtil->logAll(msg);
997          res= sqlServer->Query(query.str().c_str());    res = sqlServer->Query(query.str().c_str());
998              stringstream oss1;
999          stringstream oss1;    oss1.str() = "";
1000           oss1.str()="";    string msg1;
1001           string msg1;  
1002        if (!res) {
1003           if (!res)      oss1 << "DBError UNABLE to: " << query.str().c_str() << endl;
1004           {      msg1 = oss1.str();
1005                   oss1<<"DBError UNABLE to: "<<query.str().c_str()<<endl;        mainLogUtil->logError(msg1);
1006                   msg1=oss1.str();    }
1007                   mainLogUtil->logError(msg1);    
1008           }          return res;
1009    }
1010          return res;  
1011  }  bool PacketUser::saveMergeROOT_DB(const char* table_name, unsigned int root_id, unsigned long int pkt_number_in,
1012        unsigned long int pkt_number_fin, unsigned long int obt_in, unsigned long int obt_fin,
1013  bool PacketUser::saveMergeROOT_DB(char* table_name,  unsigned int root_id,      unsigned long int mtime_init, unsigned long int mtime_last, unsigned long int mboot_num, double percentage) {
1014                          unsigned long int pkt_number_in, unsigned long int pkt_number_fin,  
1015                          unsigned long int obt_in, unsigned long int obt_fin,    stringstream oss;
1016                  unsigned long int mtime_init,   unsigned long int mtime_last,    oss.str("");
1017                          unsigned long int mboot_num,    oss << "INSERT INTO " << table_name
1018                          double percentage)        << " (ID_N, ROOT_ID_N, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, BAD_PKT_PERCENTAGE, INSERT_TIME, INSERTED_BY)"
1019  {        << " VALUES ('" << 0 << "','" << root_id << "','" << pkt_number_in << "','" << pkt_number_fin << "','" << obt_in
1020          << "','" << obt_fin << "','" << mtime_init << "','" << mtime_last << "','" << mboot_num << "','" << percentage
1021          stringstream oss;        << "'," << "NULL" << ",'" << tag_value << "'" << ")";
1022          oss.str("");      
1023          oss << "INSERT INTO "<< table_name <<" (ID_N, ROOT_ID_N, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, BAD_PKT_PERCENTAGE, INSERT_TIME)"    string msg = oss.str();
1024      << " VALUES ('"<<0<< "','" <<root_id<<"','"<< pkt_number_in <<"','"<< pkt_number_fin << "','"<< obt_in <<"','"<< obt_fin<< "','"    mainLogUtil->logAll(msg);
1025      << mtime_init << "','" << mtime_last << "','"  
1026          << mboot_num <<"','"    //marco_new: controlla
1027          << percentage <<"',"          //marco_new: esci se sono arrivato a zero
1028      <<"NULL"<<          //    if(real_time_last==real_time_init){
1029      ")";    if (mtime_init == mtime_last) {
1030        mainLogUtil->logAll("Nothing to be saved");
1031          string msg = oss.str();  
1032          mainLogUtil->logAll(msg);            //          if(res){delete res; res = NULL;}
1033        //          if(row){delete row; row = NULL;}
1034          //marco_new: controlla      return true;
1035          //marco_new: esci se sono arrivato a zero    }
1036  //      if(real_time_last==real_time_init){      
1037          if(mtime_init==mtime_last){    stringstream oss1;
1038                  mainLogUtil->logAll("Nothing to be saved");        oss1.str() = "";
1039                              string msg1;
1040  //              if(res){delete res; res = NULL;}  
1041  //              if(row){delete row; row = NULL;}    TSQLResult* res = NULL;
1042                  return true;                                res = sqlServer->Query(oss.str().c_str());
1043          }    if (!res) {
1044        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1045        msg1 = oss1.str();
1046          stringstream oss1;      mainLogUtil->logError(msg1);
1047          oss1.str()="";      return false;
1048          string msg1;    }
1049      if (res) {
1050     TSQLResult* res=NULL;              delete res;
1051     res= sqlServer->Query(oss.str().c_str());      res = NULL;
1052     if(!res)    }
1053     {        return true;
            oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;    
            msg1=oss1.str();  
            mainLogUtil->logError(msg1);    
            return false;  
    }  
    if(res){delete res; res = NULL;}  
    return true;  
1054  }  }
1055    
1056  //Utility: return max(IDN)  //Utility: return max(IDN)
1057  unsigned  int PacketUser::select_maxIDN_DB(char* table_name)  unsigned int PacketUser::select_maxIDN_DB(const char* table_name) {
 {  
1058    
1059  if (!strcmp(table_name,Table_ROOT_Bad))    if (!strcmp(table_name, Table_ROOT_Bad)) {
1060  {      return 0;
1061          return 0;          }
1062  }    unsigned int idN = 0;
1063          unsigned  int idN=0;    TSQLResult* res = NULL;
1064          TSQLResult* res=NULL;    stringstream oss;
1065          stringstream oss;    oss.str("");
1066      oss.str("");    oss << "select max(ID_N) from " << table_name;
1067      oss<<"select max(ID_N) from "<<table_name;    //    string msg = oss.str();
1068          string msg = oss.str();    //    mainLogUtil->logAll(msg);
1069          mainLogUtil->logAll(msg);          res = sqlServer->Query(oss.str().c_str());
1070      res= sqlServer->Query(oss.str().c_str());  
1071                      stringstream oss1;
1072          stringstream oss1;    oss1.str() = "";
1073          oss1.str()="";    string msg1;
1074          string msg1;  
1075              if (!res) {
1076          if(!res)      oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1077          {            msg1 = oss1.str();
1078             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        mainLogUtil->logError(msg1);
1079                  msg1=oss1.str();      return 0;
1080                  mainLogUtil->logError(msg1);      }
1081                  return 0;  
1082          }    TSQLRow* row = NULL;
1083                row = res->Next();
1084          TSQLRow* row=NULL;          if (!row) {
1085          row=res->Next();      oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1086      if (!row )      msg1 = oss1.str();
1087      {      mainLogUtil->logError(msg1);
1088             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        return 0;
1089                  msg1=oss1.str();    }
1090                  mainLogUtil->logError(msg1);    
1091                  return 0;    idN = atoi(row->GetField(0));
1092          }    if (row) {
1093        delete row;
1094          idN=atoi(row->GetField(0));      row = NULL;
1095          if(row){delete row; row = NULL;}    }
1096          if(res){delete res; res = NULL;}    if (res) {
1097          return idN;      delete res;
1098        res = NULL;
1099      }
1100    
1101      oss << ". idN = " << idN;
1102      string msg = oss.str();
1103      mainLogUtil->logAll(msg);
1104    
1105      return idN;
1106  }  }
1107    
1108  /**  /**
1109   * Lock par=table, if par=null lock all tables   * Lock par=table, if par=null lock all tables
1110   */   */
1111  int PacketUser::LockTables(char* tableTobeLocked)  int PacketUser::LockTables(const char* tableTobeLocked) {
1112  {      //se non ho il DB  :)
1113          //se non ho il DB  :)    if (!do_cont_check)
1114          if(!do_cont_check) return 999;      return 999;
1115    
1116          TSQLResult* res=NULL;    TSQLResult* res = NULL;
1117          stringstream oss;    stringstream oss;
1118      oss.str("");    oss.str("");
1119          if(!tableTobeLocked)    if (!tableTobeLocked)
1120                  oss << "lock table "<<Table_ROOT_Good<<" write, "<<Table_ROOT_Bad<<" write, "<<Table_GL_RESURS_OFFSET<<" write, "<<Table_ROOT_Merging<<" write;";      oss << "lock table " << Table_ROOT_Good << " write, " << Table_ROOT_Bad << " write, " << Table_GL_RESURS_OFFSET
1121          else          << " write, " << Table_ROOT_Merging << " write;";
1122                  oss << "lock table "<<tableTobeLocked<<" write; ";    else
1123        oss << "lock table " << tableTobeLocked << " write; ";
1124          string msg = oss.str();  
1125          mainLogUtil->logAll(msg);          string msg = oss.str();
1126      mainLogUtil->logAll(msg);
1127          res= sqlServer->Query(oss.str().c_str());  
1128                      res = sqlServer->Query(oss.str().c_str());
1129          stringstream oss1;  
1130          oss1.str()="";    stringstream oss1;
1131          string msg1;    oss1.str() = "";
1132              string msg1;
1133          if(!res)  
1134          {          if (!res) {
1135             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1136                  msg1=oss1.str();      msg1 = oss1.str();
1137                  mainLogUtil->logError(msg1);        mainLogUtil->logError(msg1);
1138                  return 1;      return 1;
1139          }    }
1140              
1141          if(res){delete res; res = NULL;}            if (res) {
1142          mainLogUtil->logAll("######################### TABLES LOCKED ############################");                          delete res;
1143          return 0;            res = NULL;
1144      }
1145      mainLogUtil->logAll("TABLES LOCKED");
1146      return 0;
1147  }  }
1148    
1149  /**  /**
1150   * UNLock tables   * UNLock tables
1151   */   */
1152  int PacketUser::UnLockTables(){    int PacketUser::UnLockTables() {
1153          //se non ho il DB  :)      //se non ho il DB  :)
1154          if(!do_cont_check) return 999;    if (!do_cont_check)
1155        return 999;
1156          TSQLResult* res=NULL;  
1157          stringstream oss;    TSQLResult* res = NULL;
1158      oss.str("");    stringstream oss;
1159          oss << "unlock tables;";    oss.str("");
1160      oss << "unlock tables;";
1161    
1162      string msg = oss.str();
1163      mainLogUtil->logAll(msg);
1164    
1165      res = sqlServer->Query(oss.str().c_str());
1166    
1167      stringstream oss1;
1168      oss1.str() = "";
1169      string msg1;
1170    
1171      if (!res) {
1172        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1173        msg1 = oss1.str();
1174        mainLogUtil->logError(msg1);
1175        return 1;
1176      }
1177    
1178      if (res) {
1179        delete res;
1180        res = NULL;
1181      }
1182      mainLogUtil->logAll("TABLES UNLOCKED");
1183    
1184      string msg = oss.str();    return 0;
         mainLogUtil->logAll(msg);        
           
         res= sqlServer->Query(oss.str().c_str());  
                   
         stringstream oss1;  
         oss1.str()="";  
         string msg1;  
           
         if(!res)  
         {        
            oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;    
                 msg1=oss1.str();  
                 mainLogUtil->logError(msg1);    
                 return 1;  
         }  
                   
         if(res){delete res; res = NULL;}          
         mainLogUtil->logAll("######################### TABLES UNLOCKED ############################");    
   
         return 0;        
1185  }  }
1186    
1187  /*********************************************************/  /*********************************************************/
1188  //marco_new_31  //marco_new_31
1189  void PacketUser::OpenDBConnection(char* tableTobeLocked){  void PacketUser::OpenDBConnection(const char* tableTobeLocked) {
1190          mainLogUtil->logAll("######################### OpenDBConnection ############################");    if (do_cont_check) {
1191          if(do_cont_check){      //controllo che non sia gia' aperta
1192                  //controllo che non sia gi� aperta      if (!sqlServer) {
1193                  if(!sqlServer){        sqlServer = TSQLServer::Connect(connection, db_user, db_pwd);
1194                          sqlServer = TSQLServer::Connect(connection,db_user,db_pwd);        if ((!sqlServer) || (!(sqlServer->IsConnected()))) {
1195                          if ((!sqlServer)||(!(sqlServer->IsConnected()))){cout<<"Can not connect with MYSQL sever"<<endl;}                cout << "Can not connect with MYSQL sever" << endl;
1196          }
1197                          //marco_new: blocca tutte le tabelle        mainLogUtil->logAll("Connected to DB");
1198                          LockTables(tableTobeLocked);        stringstream myquery;
1199                          mainLogUtil->logAll("######################### OpenDBConnection OK ############################");              myquery.str("");
1200                  }        myquery << "SET time_zone='+0:00'";
1201          }        sqlServer->Query(myquery.str().c_str());
1202          //blocca le tabelle
1203          LockTables(tableTobeLocked);
1204        }
1205      }
1206    
1207  }  }
1208    
1209  //marco_new_31  //marco_new_31
1210  void PacketUser::CloseDBConnection(){  void PacketUser::CloseDBConnection() {
1211          mainLogUtil->logAll("######################### CloseDBConnection ############################");            if (do_cont_check) {
1212          if(do_cont_check){                                            //controllo che ce ne sia una aperta
1213                  //controllo che ce ne sia una aperta      if (sqlServer && sqlServer->IsConnected()) {
1214                  if(sqlServer && sqlServer->IsConnected()){        //marco_new: sblocca tutte le tabelle
1215                          //marco_new: sblocca tutte le tabelle        UnLockTables();
1216                          UnLockTables();                sqlServer->Close();
1217                          sqlServer->Close();        delete sqlServer;
1218          sqlServer = NULL;
1219                          //marco_new_01: ??        mainLogUtil->logAll("Closed Connection to DB");
1220                          delete sqlServer;      }
1221                              }
                         sqlServer=NULL;  
                         mainLogUtil->logAll("######################### CloseDBConnection OK ############################");      
                 }  
         }  
1222  }  }
1223    
   
   
1224  /***********************************************************************************************************************/  /***********************************************************************************************************************/
1225  /*#################################################### HIC SUNT LEONES ################################################*/  /*#################################################### HIC SUNT LEONES ################################################*/
1226  /***********************************************************************************************************************/  /***********************************************************************************************************************/
1227  //UNUSED: dbg functions...  //UNUSED: dbg functions...
1228    
1229  //Return the system time in ms  //Return the system time in ms
1230  unsigned long long PacketUser::Record_Time(){  unsigned long long PacketUser::Record_Time() {
1231          timeval tv;    timeval tv;
1232          gettimeofday(&tv,NULL);    gettimeofday(&tv, NULL);
1233          unsigned long long timems =  (unsigned long long)tv.tv_sec * (unsigned long long)1000 + tv.tv_usec / 1000;    unsigned long long timems = (unsigned long long) tv.tv_sec * (unsigned long long) 1000 + tv.tv_usec / 1000;
1234          return timems;      return timems;
1235  }  }
1236    
1237  //dbg_functions:  //dbg_functions:
1238    
1239  //UNUSED. save a packet in a file  //UNUSED. save a packet in a file
1240  void PacketUser::savePKT_file(char* headerPkt,  void PacketUser::savePKT_file(char* headerPkt, char* pamPkt, long int length, bool append, char* nomefile) {
1241                                                           char* pamPkt,    char fno[80] = "";
1242                                                           long int length,    ofstream fout;
1243                                                           bool append,    sprintf(fno, "%s/pkt%d_of_%s.pkt", gSystem->ExpandPathName(outDir), numPKTSaved, nomefile); // EMI
1244                                                           char* nomefile)  
1245  {    if (append == true)
1246          char fno[80]="";      fout.open(fno, ios::binary | ios::app);
1247          ofstream fout;    else
1248          sprintf(fno,"%s/pkt%d_of_%s.pkt", outDir, numPKTSaved, nomefile);      fout.open(fno, ios::binary);
1249    
1250          if(append==true)    if (!fout) {
1251                  fout.open(fno, ios::binary | ios::app);      cout << "can not open output file " << fno << endl;
1252          else      return;
1253                  fout.open(fno, ios::binary);                        }
1254                      fout.write(headerPkt, LENGTH_HEADER_PKT);
1255          if (!fout) {cout<<"can not open output file "<<fno<<endl; return;}                      fout.write(pamPkt, length);
1256          fout.write(headerPkt,LENGTH_HEADER_PKT);    fout.close();
         fout.write(pamPkt,length);  
         fout.close();      
1257  }  }
1258    
1259  //UNUSED  //UNUSED
1260  void PacketUser::saveALL_PKT(char* headerPkt, char* pamPkt, long int length, bool append)  void PacketUser::saveALL_PKT(char* headerPkt, char* pamPkt, long int length, bool append) {
1261  {    char fno[80] = "";
1262          char fno[80]="";    ofstream fout;
1263          ofstream fout;    if (append == true) {
1264          if(append==true)      sprintf(fno, "%s/packets.pkt", gSystem->ExpandPathName(outDir)); // EMI
1265          {                    fout.open(fno, ios::binary | ios::app);
1266                  sprintf(fno,"%s/packets.pkt", outDir);    }
1267                  fout.open(fno, ios::binary | ios::app);    else {
1268          }      sprintf(fno, "%s/packet%d.pkt", gSystem->ExpandPathName(outDir), numPKT); // EMI
1269          else{      fout.open(fno, ios::binary);
1270                  sprintf(fno,"%s/packet%d.pkt", outDir, numPKT );    }
1271                  fout.open(fno, ios::binary);                      
1272          }    if (!fout) {
1273                        cout << "can not open output file " << fno << endl;
1274          if (!fout) {cout<<"can not open output file "<<fno<<endl; return;}                        return;
1275          fout.write(headerPkt,LENGTH_HEADER_PKT);    }
1276          fout.write(pamPkt,length);    fout.write(headerPkt, LENGTH_HEADER_PKT);
1277          fout.close();        fout.write(pamPkt, length);
1278      fout.close();
1279  }  }
1280    
   
1281  }  }

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.9

  ViewVC Help
Powered by ViewVC 1.1.23