/[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.3 by mocchiut, Thu Dec 18 12:58:37 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.69 2008-10-27 10:41:27 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  //per tenere conto reset obt
35  extern unsigned long int  max_pkt_obt;  extern unsigned long int max_pkt_obt;
36    
37  #define TAGVALUELEN 4  #define TAGVALUELEN 4
38  extern  char tag_value[TAGVALUELEN];  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;  
   
         //(tassa)  
         obt_time_sync_prevvalue=0;  
         last_time_sync_info_prevvalue=0;  
         time_is_estimated=false;  
           
   
         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;  
         //(tassa)        
         boot_number_prevvalue=0;  
   
         //(tassa)  
         id_to_recover[1000];  
         id_to_recover_index=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;  
         obt_time_sync_prevvalue=0;  
         last_time_sync_info_prevvalue=0;  
         time_is_estimated=false;  
   
         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;  
         boot_number_prevvalue=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;}  
                   
         //in order to start ...  
         if(numPKT==0)  
         {                
                 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);                
                   
                 //se gia' e' cambiato download non 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 also know if the packet comes from one or more corrupted cadres  
         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);//here I retrieve also the boot_number if packet type is vardump  
         }  
   
         //just to be sure ...  
         if(pamPkt){delete[] pamPkt; pamPkt = NULL;}      
         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    
255          obt_time_sync_prevvalue=obt_time_sync;    obt_time_sync_prevvalue = obt_time_sync;
256          last_time_sync_info_prevvalue=last_time_sync_info;    last_time_sync_info_prevvalue = last_time_sync_info;
257          time_is_estimated=false;    time_is_estimated = false;
258          obt_time_sync=0; last_time_sync_info=0;    obt_time_sync = 0;
259          boot_number_prevvalue=boot_number;    last_time_sync_info = 0;
260          boot_number=0;    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    //    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          strcat(rootfilename,".root");    reader->Init(pRun);
272          reader->Init(pRun);                        stringstream oss;
273          stringstream oss;    oss.str() = "";
274          oss.str()="";    oss << "######################### Start a new group in file: " << rootfilename << " ############################";
275          oss<<"######################### Start a new group in file: "<< rootfilename <<" ############################";    string msg = oss.str();
276          string msg = oss.str();    mainLogUtil->logInfo(msg);
         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;
         obt_last=obt;  
283  }  }
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      if (!do_cont_check) {
289        if (is_new_route)
290          is_new_route = false;
291        return;
292      }
293    
294      //TODO: usare anche MCMD ... NOTA: questo da sempre errore ret != 0
295      //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      if (is_new_route) {
299        //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        obt_time_sync_prevvalue = 0;//obt_time_sync;
303        last_time_sync_info_prevvalue = 0;//last_time_sync_info;
304    
305        obt_time_sync = 0;
306        last_time_sync_info = 0;
307        boot_number_prevvalue = 0;//boot_number;
308        boot_number = 0;
309        time_is_estimated = false;
310        if (time_Offset)
311          timeOffset = time_Offset;
312        else
313          timeOffset = retrieveTimeOffset(Table_GL_RESURS_OFFSET);
314      }
315    
316  //retrieve obt_time_sync and last_time_sync_info from packet if type has special values and BOOT_NUMBER    //retrieve boot number if possible
317  void PacketUser::setTimeSync(char* packet, long int pktLength, const PacketType* type)    setBootNumber(packet, pktLength, type);
318  {  
319      //do nothing    //Retrieve if possible obt_time_sync and last_time_sync_info
320          if(!do_cont_check) {    int offset = 0;
321                  if(is_new_route)    if (type == PacketType::RunHeader) {
322                          is_new_route=false;      offset = 0;
323                  return;    }
324          }    else if (type == PacketType::RunTrailer) {
325                offset = 3;
326  //TODO: usare anche MCMD ... NOTA: questo da sempre errore ret != 0    }
327  //In RunHeader e RunTrailer sono in secondi(?), controllare se aggiungo altri tipi di paccheti se invece sono in secondi                    else if (type == PacketType::Mcmd) {
328  // devo ricalcolare tutto non per ogni gruppetto (ROOT file) ma solo se cambia download      //          mainLogUtil->logAll("TODO: Packet Mcmd now is not used to retrieve Absolute time. This may cause problems somewhere.");
329  //When I found a new download I need to reset all values      return;
330          if(is_new_route)    }
331          {    else {
332                  //reset      return;
333                  is_new_route=false;    }
334                  //(tassa) ci ho ripensato se stiamo in un secondo download non prendiamo i bootnumber e timesync del precedente!    
335                  obt_time_sync_prevvalue=0;//obt_time_sync;    //I don't need to retrieve them again if they are good
336                  last_time_sync_info_prevvalue=0;//last_time_sync_info;    if ((obt_time_sync) || (last_time_sync_info))
337                return;
338                  obt_time_sync=0; last_time_sync_info=0;  
339                  boot_number_prevvalue=0;//boot_number;    obt_time_sync = (((UINT32) packet[5 + offset] << 24) & 0xFF000000) + (((UINT32) packet[6 + offset] << 16)
340                  boot_number=0;        & 0x00FF0000) + (((UINT32) packet[7 + offset] << 8) & 0x0000FF00) + (((UINT32) packet[8 + offset]) & 0x000000FF);
341                  time_is_estimated=false;    last_time_sync_info = (((UINT32) packet[9 + offset] << 24) & 0xFF000000) + (((UINT32) packet[10 + offset] << 16)
342                  if(time_Offset)        & 0x00FF0000) + (((UINT32) packet[11 + offset] << 8) & 0x0000FF00)
343                          timeOffset=time_Offset;        + (((UINT32) packet[12 + offset]) & 0x000000FF);
344                  else              
345                          timeOffset=retrieveTimeOffset(Table_GL_RESURS_OFFSET);    stringstream oss;
346          }    oss.str() = "";
347              oss << "In download: " << download << " timeOffset: " << timeOffset << " obt_time_sync: " << obt_time_sync
348          //retrieve boot number if possible        << " last_time_sync_info: " << last_time_sync_info << " using Packet Type: " << type->GetName();
349          setBootNumber(packet,pktLength,type);    //    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      string msg = oss.str();
351          //Retrieve if possible obt_time_sync and last_time_sync_info    mainLogUtil->logAll(msg);
         int offset=0;  
         if(type==PacketType::RunHeader)  
         {                
                 offset=0;  
         }  
         else if(type==PacketType::RunTrailer)  
         {        
                 offset=3;  
         }  
         else if(type==PacketType::Mcmd)  
         {        
 //              mainLogUtil->logAll("TODO: Packet Mcmd now is not used to retrieve Absolute time. This may cause problems somewhere.");  
                 return;  
         }  
         else  
         {        
                 return;  
         }                
           
         //I don't need to retrieve them again if they are good  
         if((obt_time_sync)||(last_time_sync_info)) return;  
   
         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);  
         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);                
   
         stringstream oss;  
         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();  
         string msg = oss.str();  
         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 continuita'        if (boot_number)
358          if(boot_number) return;      return;
359            
360          if(type==PacketType::VarDump)    if (type == PacketType::VarDump) {
361          {            int b_offset = 34;//4+5*6
362                  int b_offset = 34;//4+5*6      boot_number = (((UINT32) packet[1 + b_offset] << 24) & 0xFF000000) + (((UINT32) packet[2 + b_offset] << 16)
363                  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);          & 0x00FF0000) + (((UINT32) packet[3 + b_offset] << 8) & 0x0000FF00) + (((UINT32) packet[4 + b_offset])
364            & 0x000000FF);
365  /*  
366                  long int  dataLength = pktLength - 2; //the block of data      /*
367                  int b_offset = 4;                     long int  dataLength = pktLength - 2; //the block of data
368                  while (b_offset < dataLength){       int b_offset = 4;
369                   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);       while (b_offset < dataLength){
370                   b_offset = b_offset + 5;       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                  }       b_offset = b_offset + 5;
372  */                     }
373                  stringstream oss;       */
374                  oss.str()="";      stringstream oss;
375                  oss<<"In download: "<<download<<" boot_number: "<<boot_number<<" using Packet Type: "<<type->GetName().c_str();      oss.str() = "";
376                  string msg = oss.str();      //          oss<<"In download: "<<download<<" boot_number: "<<boot_number<<" using Packet Type: "<<type->GetName().c_str();
377                  mainLogUtil->logAll(msg);      oss << "In download: " << download << " boot_number: " << boot_number << " using Packet Type: " << type->GetName();
378                  return;      string msg = oss.str();
379          }      mainLogUtil->logAll(msg);
380          else      return;
381          {          }
382                  return;    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 && numPKTSaved > 1000 )    if (!obt_time_sync && !last_time_sync_info && numPKTSaved > 1000) {
391          {      time_is_estimated = true;
392            time_is_estimated=true;      obt_time_sync = obt_time_sync_prevvalue;
393            obt_time_sync=obt_time_sync_prevvalue;      last_time_sync_info = last_time_sync_info_prevvalue;
394            last_time_sync_info=last_time_sync_info_prevvalue;    }
395          }      if (obt_time_sync || last_time_sync_info) {
396          if(obt_time_sync  || last_time_sync_info)      real_time_init = (obt_init / 1000 - obt_time_sync) + last_time_sync_info;
397            {                                                                                      //se obt si e' resettato
398              real_time_init=(obt_init/1000-obt_time_sync)+last_time_sync_info;      if (obt_last < obt_init) {
399                  //se obt si e' resettato        real_time_last = (max_pkt_obt / 1000 + obt_last / 1000 - obt_time_sync) + last_time_sync_info;
400                  if(obt_last<obt_init)        stringstream oss;
401                  {        oss.str() = "";
402                          real_time_last=(max_pkt_obt/1000+ obt_last/1000-obt_time_sync)+last_time_sync_info;            oss << "obt_last(" << obt_last << ") < obt_init(" << obt_init
403                          stringstream oss;            << "). It is due to Pamela Reset. Adding max_pkt_obt(" << max_pkt_obt
404                          oss.str()="";            << ") to obt_last in order to compute real_time_last";
405                          oss<<"obt_last("<<obt_last<<") < obt_init("<<obt_init<<"). It is due to Pamela Reset. Adding max_pkt_obt("<<max_pkt_obt<<") to obt_last in order to compute real_time_last";        string msg = oss.str();
406                          string msg = oss.str();        mainLogUtil->logWarning(msg);
407                          mainLogUtil->logWarning(msg);      }
408                  }      else
409                  else        real_time_last = (obt_last / 1000 - obt_time_sync) + last_time_sync_info;
410                          real_time_last=(obt_last/1000-obt_time_sync)+last_time_sync_info;      real_time_init += timeOffset;
411                  real_time_init+=timeOffset;      real_time_last += timeOffset;
412                  real_time_last+=timeOffset;        }
         }  
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          if(!single_connection){    if (!single_connection) {
424                  OpenDBConnection(table);//Nota qui ho deciso di lockare solo questa tabella e non tutte      OpenDBConnection(table);//Nota qui ho deciso di lockare solo questa tabella e non tutte
425          }    }
426    
427          UInt_t t0 = 0;//toffset                                    UInt_t t0 = 0;//toffset
428          stringstream oss;    stringstream oss;
429          oss.str("");    oss.str("");
430          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='"    oss
431                << nnnn_mmm_ppp << "';";        << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "
432          << table << " WHERE SPECIAL_FILE='" << nnnn_mmm_ppp << "';";
433          string msg = oss.str();  
434          mainLogUtil->logAll(msg);          string msg = oss.str();
435      mainLogUtil->logAll(msg);
436          TSQLResult* res=NULL;                              
437          TSQLRow* row=NULL;          TSQLResult* res = NULL;
438          res= sqlServer->Query(oss.str().c_str());                            TSQLRow* row = NULL;
439          if(!res)    res = sqlServer->Query(oss.str().c_str());
440          {                  if (!res) {
441                  mainLogUtil->logError("DBError retrieveTimeOffset 1");      mainLogUtil->logError("DBError retrieveTimeOffset 1");
442                  return 0;      return 0;
443          }    }
444    
445      row=res->Next();    row = res->Next();
446      if (!row )    if (!row) {
447      {      if (res) {
448          if(res){delete res; res = NULL;}        delete res;
449          res = NULL;
450          oss.str("");      }
451          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 < "  
452          << orbit_number << " order by FROM_ORBIT desc limit 1;";      oss.str("");
453                oss
454                  string msg2 = oss.str();          << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "
455                  mainLogUtil->logAll(msg2);          << table << " WHERE FROM_ORBIT < " << orbit_number << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
456    
457                  res= sqlServer->Query(oss.str().c_str());                            string msg2 = oss.str();
458          if(!res)      mainLogUtil->logAll(msg2);
459          {    
460                  mainLogUtil->logError("DBError retrieveTimeOffset 2");      res = sqlServer->Query(oss.str().c_str());
461                  return 0;      if (!res) {
462          }        mainLogUtil->logError("DBError retrieveTimeOffset 2");
463          row=res->Next();        return 0;
464          if (!row)      }
465          {      row = res->Next();
466                  mainLogUtil->logError("DBError retrieveTimeOffset 3");      if (!row) {
467                  return 0;        mainLogUtil->logError("DBError retrieveTimeOffset 3");
468          }        return 0;
469                        }
470       }  
471          }
472        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);  
473        t0 = (UInt_t)tu.GetSec();    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          if(res){delete res; res = NULL;}        5)), 0, true, 0);
476          if(row){delete row; row = NULL;}            t0 = (UInt_t) tu.GetSec();
477    
478          if(!single_connection){    if (res) {
479                  CloseDBConnection();                  delete res;
480          }      res = NULL;
481   return t0;    }
482      if (row) {
483        delete row;
484        row = NULL;
485      }
486    
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          if(single_connection){      CloseDBConnection();
501                  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      // se non ho salvato nessun pacchetto
527                  if(numPKTSaved==0){                          if (numPKTSaved == 0) {
528                          stringstream err;        stringstream err;
529                          err.str()="";        err.str() = "";
530                          err<<"NO PACKET SAVED in file: "<< rootfilename <<" The group is empty: you can remove this file.";        err << "NO PACKET SAVED in file: " << rootfilename << " The group is empty: you can remove this file.";
531                          msg = err.str();        msg = err.str();
532                          mainLogUtil->logError(msg);        mainLogUtil->logError(msg);
533                          return;        return;
534                  }      }
535                            
536                  //se non ho salvato nessun pacchetto buono      //se non ho salvato nessun pacchetto buono
537                  if((numPKTSaved-bad_pkt_EventReader-bad_pkt_CalibReader-bad_pkt)==0){                        if ((numPKTSaved - bad_pkt_EventReader - bad_pkt_CalibReader - bad_pkt) == 0) {
538                          stringstream err;        stringstream err;
539                          err.str()="";        err.str() = "";
540                          err<<"NO GOOD PACKET SAVED in file: "<< rootfilename <<" The group is BAD: you may want to remove this file.";        err << "NO GOOD PACKET SAVED in file: " << rootfilename << " The group is BAD: you may want to remove this file.";
541                          msg = err.str();        msg = err.str();
542                          mainLogUtil->logInfo(msg);        mainLogUtil->logInfo(msg);
543  //                      mainLogUtil->logError(msg);        //                        mainLogUtil->logError(msg);
544  //                      return; //TODO: decidi se nn vuoi affatto usarlo o addirittura salvarlo tra i BAD???        //                        return; //TODO: decidi se nn vuoi affatto usarlo o addirittura salvarlo tra i BAD???
545                  }      }
546    
547                  if(!single_connection){      if (!single_connection) {
548                          OpenDBConnection(NULL);//Nota qui ho deciso di lockare tutte le tabelle        OpenDBConnection(NULL);//Nota qui ho deciso di lockare tutte le tabelle
549                  }      }
550                    
551                  //don't save in Table_ROOT_Good and don't search for ROOT files in the same temporal range      //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))      if ((!real_time_init) && (!real_time_last)) {
553                  {        //saved in another table for future study
554                          //saved in another table for future study        if (saveROOT_DB(
555                          if(saveROOT_DB(Table_ROOT_Bad, outDir,            Table_ROOT_Bad,
556                                                                  filename,            outDir,// here outDir is good, no expand EMI
557                                                             pkt_number_init, pkt_number_last,            filename, pkt_number_init, pkt_number_last, obt_init, obt_last, obt_time_sync, last_time_sync_info,
558                                                             obt_init, obt_last,            real_time_init, real_time_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
559                                                             obt_time_sync, last_time_sync_info,                numPKTSaved, fni, time_is_estimated) == true) {
560                                                             real_time_init, real_time_last,          oss.str() = "";
561                                                             boot_number,          oss << "Saved information regarding file: " << filename << " in table " << Table_ROOT_Bad;
562                                                             timeOffset,          msg = oss.str();
563                                                             bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader, numPKTSaved,          mainLogUtil->logInfo(msg);
564                                                             fni,time_is_estimated)==true)        }
565                                  {        else {
566                                          oss.str()="";          oss.str() = "";
567                                          oss<<"Saved information regarding file: "<<filename<<" in table "<<Table_ROOT_Bad;          oss << "Problem storing information in DB regarding file: " << filename;
568                                          msg = oss.str();          msg = oss.str();
569                                          mainLogUtil->logInfo(msg);                mainLogUtil->logError(msg);
570                                  }        }
571                                  else  
572                                  {              if (!single_connection) {
573                                          oss.str()="";          CloseDBConnection();
574                                          oss<<"Problem storing information in DB regarding file: "<<filename;        }
575                                          msg = oss.str();  
576                                          mainLogUtil->logError(msg);                    return;
577                                  }                            }
578    
579                          if(!single_connection){      //saves info in DB in table Table_ROOT_Good
580                                  CloseDBConnection();                  if (boot_number == 0)
581                          }        boot_number = boot_number_prevvalue;
582    
583                  return;      if (saveROOT_DB(
584                  }          Table_ROOT_Good,
585                                                    outDir, // here outDir is good, no expand EMI
586                  //saves info in DB in table Table_ROOT_Good          filename, pkt_number_init, pkt_number_last, obt_init, obt_last, obt_time_sync, last_time_sync_info,
587                  if(boot_number==0)          real_time_init, real_time_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
588                    boot_number=boot_number_prevvalue;          numPKTSaved, fni, time_is_estimated) == true) {
589          oss << "Saved information regarding file: " << filename << " in table " << Table_ROOT_Good << " id= " << my_id;
590                  if(saveROOT_DB(Table_ROOT_Good, outDir,        msg = oss.str();
591                                          filename,        mainLogUtil->logInfo(msg);
592                                     pkt_number_init, pkt_number_last,  
593                                     obt_init, obt_last,        if (tryMerge) {
594                                     obt_time_sync, last_time_sync_info,              merge_ROOTfiles();
595                                     real_time_init, real_time_last,        }
596                                     boot_number,      }
597                                     timeOffset,      else {
598                                     bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader, numPKTSaved,        oss << "Problem storing information in DB regarding file: " << filename;
599                                     fni,time_is_estimated)==true)        msg = oss.str();
600                  {                                                      mainLogUtil->logError(msg);
601                          oss<<"Saved information regarding file: "<<filename<<" in table "<<Table_ROOT_Good<< " id= "<<my_id;      }
602                          msg = oss.str();  
603                          mainLogUtil->logInfo(msg);            if (!single_connection) {
604                                  CloseDBConnection();
605                          if(tryMerge){                                }
                             merge_ROOTfiles();  
                         }  
                 }  
                 else  
                 {  
                         oss<<"Problem storing information in DB regarding file: "<<filename;  
                         msg = oss.str();  
                         mainLogUtil->logError(msg);      
                 }                                
   
                 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, bool _time_is_estimated){                        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,TIME_IS_ESTIMATED)"        << 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);
     << time_offset << "','"  
     << bad_pkt <<"','" << bad_pkt_read <<"','"<< bad_pkt_CalRead <<"','"<< num_PKT_Saved<<"','"  
     << nome_input <<"',"  
     <<"NULL,"<<_time_is_estimated<<    
     ")";              
         string msg = oss.str();  
         mainLogUtil->logAll(msg);        
           
         stringstream oss1;  
         oss1.str()="";  
         string msg1;  
         string query;  
     
    TSQLResult* res=NULL;  
   
    query=oss.str();  
    msg1="SaveROOT_DB query: ";  
    msg1 += query;        
    mainLogUtil->logInfo(msg1);    
             
    res= sqlServer->Query(query.c_str());  
    if(!res)  
    {      
            oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;    
            msg1=oss1.str();  
            mainLogUtil->logError(msg1);    
            return false;  
    }  
628    
629     //the ID of the current ROOT file in table Table_ROOT_Good    stringstream oss1;
630           my_id = select_maxIDN_DB(table_name);    oss1.str() = "";
631           if(!boot_number){    string msg1;
632             if(id_to_recover_index<1000)    string query;
633               id_to_recover[id_to_recover_index++]=my_id;  
634           }else if (boot_number && id_to_recover_index && !is_new_route){    TSQLResult* res = NULL;
            recover_boot_number();  
          }  
 //      cout<<"DBG: my_id = "<<my_id<<endl;  
    if(res){delete res; res = NULL;}  
    return true;  
 }  
635    
636      query = oss.str();
637      msg1 = "SaveROOT_DB query: ";
638      msg1 += query;
639      mainLogUtil->logInfo(msg1);
640    
641      res = sqlServer->Query(query.c_str());
642      if (!res) {
643        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
644        msg1 = oss1.str();
645        mainLogUtil->logError(msg1);
646        return false;
647      }
648    
649  void PacketUser::recover_boot_number(){    //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;    string msg1;
668    stringstream oss1;    stringstream oss1;
669    stringstream oss;    stringstream oss;
670    oss.str("");      oss.str("");
671    string query="";    string query = "";
672    TSQLResult* res=NULL;    TSQLResult* res = NULL;
673    if(!boot_number || !id_to_recover_index)    if (!boot_number || !id_to_recover_index)
674      return;      return;
675      
676    for (int i = 0; i<id_to_recover_index;i++){    for (int i = 0; i < id_to_recover_index; i++) {
677      oss << "UPDATE "<<  Table_ROOT_Good << " SET BOOT_NUMBER=" << boot_number << " WHERE ID_N=" << id_to_recover[i];        oss.str("");
678     query = oss.str();      oss << "UPDATE " << Table_ROOT_Good << " SET BOOT_NUMBER=" << boot_number << " WHERE ID_N=" << id_to_recover[i]
679     res= sqlServer->Query(query.c_str());          << ";";
680     if(!res)      query = oss.str();
681     {          res = sqlServer->Query(query.c_str());
682             oss1<<"DBError UNABLE to: "<<query.c_str()<<endl;        if (!res) {
683             msg1=oss1.str();        oss1 << "DBError UNABLE to: " << query.c_str() << endl;
684             mainLogUtil->logError(msg1);          msg1 = oss1.str();
685             return ;        mainLogUtil->logError(msg1);
686     }        return;
687        }
688    }    }
689    
690  for (int i = 0; i<id_to_recover_index;i++){    for (int i = 0; i < id_to_recover_index; i++) {
691    oss << "UPDATE " <<  Table_ROOT_Merging << " SET BOOT_NUMBER=" <<  boot_number << " WHERE ROOT_ID_N=" << id_to_recover[i];        oss.str("");
692    query=oss.str();      oss << "UPDATE " << Table_ROOT_Merging << " SET BOOT_NUMBER=" << boot_number << " WHERE ROOT_ID_N="
693     res= sqlServer->Query(query.c_str());          << id_to_recover[i] << ";";
694     if(!res)      query = oss.str();
695     {          res = sqlServer->Query(query.c_str());
696             oss1<<"DBError UNABLE to: "<<query.c_str()<<endl;        if (!res) {
697             msg1=oss1.str();        oss1 << "DBError UNABLE to: " << query.c_str() << endl;
698             mainLogUtil->logError(msg1);          msg1 = oss1.str();
699             return ;        mainLogUtil->logError(msg1);
700     }        return;
701        }
702    }    }
703    
704    id_to_recover_index=0;    id_to_recover_index = 0;
705  }  }
706    
   
   
707  /**********************************************************************************************/  /**********************************************************************************************/
708  /*###########################################################################################################*/  /*###########################################################################################################*/
709  /**********************************         MERGING          *************************************************/  /**********************************         MERGING          *************************************************/
# Line 702  for (int i = 0; i<id_to_recover_index;i+ Line 712  for (int i = 0; i<id_to_recover_index;i+
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     stringstream log;    log.str("");
718     log.str("");    string slog;
    string slog;  
719    
720    mainLogUtil->logInfo("Trying merging ROOT files");    mainLogUtil->logInfo("Trying merging ROOT files");
721    double percentage=(double)(bad_pkt+bad_pkt_EventReader+bad_pkt_CalibReader)/numPKTSaved;    double percentage = (double) (bad_pkt + bad_pkt_EventReader + bad_pkt_CalibReader) / numPKTSaved;
                   
   TSQLResult* res=NULL;    
   TSQLRow* row =NULL;  
 //numero di ROOT files trovati sul DB che hanno relaz di tipo dato  
   unsigned int num_rows=0;  
   
         //Record su DB:  
         unsigned int idN = 0;        
         unsigned int root_id_db=0;  
         unsigned long int pkt_num_in_db=0;  
         unsigned long int pkt_num_fin_db=0;  
         unsigned long int pkt_obt_in_db=0;  
         unsigned long int pkt_obt_fin_db=0;  
         unsigned long int time_in_db=0;  
         unsigned long int time_fin_db=0;  
         unsigned int boot_num_db=0;  
         double perc=0;                    
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: non considero mai caso di continuita'(mio finale=DB iniz o viceversa), non mi interessa    //marco_new: non considero mai caso di continuita'(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: esci se sono arrivato a zero      if (real_time_last == real_time_init) {
745          if(real_time_last==real_time_init)        log.str("");
746          {        log << "Current File Lenght=0; real_time_last=real_time_init= " << real_time_last;
747                  log.str("");        slog = log.str();
748                  log<<"Current File Lenght=0; real_time_last=real_time_init= "<<real_time_last;        mainLogUtil->logAll(slog);
749                  slog=log.str();        mainLogUtil->logInfo("Finish merging ROOT files");
750                  mainLogUtil->logAll(slog);        if (res) {
751                  mainLogUtil->logInfo("Finish merging ROOT files");                        delete res;
752                  if(res){delete res; res = NULL;}          res = NULL;
753                  if(row){delete row; row = NULL;}        }
754                  return true;                                    if (row) {
755          }          delete row;
756            row = NULL;
757          num_rows=0;        }
758          res = Select_merging(Table_ROOT_Merging, real_time_init, real_time_last, (type_Rel_ROOT)relaz);        return true;
759                }
760           if (!res)  
761           {      num_rows = 0;
762                  mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged RES=null");      res = Select_merging(Table_ROOT_Merging, real_time_init, real_time_last, (type_Rel_ROOT) relaz);
763                   return false;  
764           }      if (!res) {
765          mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged RES=null");
766           num_rows=res->GetRowCount();        return false;
767           log.str("");      }
768           log<<"Found "<<num_rows<<" ROOT file in DB with relation of kind = "<<relaz;  
769           slog=log.str();      num_rows = res->GetRowCount();
770           mainLogUtil->logAll(slog);      log.str("");
771        log << "Found " << num_rows << " ROOT file in DB with relation of kind = " << relaz;
772           if(num_rows>0)      slog = log.str();
773           {      mainLogUtil->logAll(slog);
774                  for(unsigned int i=0; i<num_rows; i++)  
775                   {      if (num_rows > 0) {
776                           row=res->Next();        for (unsigned int i = 0; i < num_rows; i++) {
777                           if (!row)          row = res->Next();
778                           {          if (!row) {
779                                  mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged. ROW=null");            mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged. ROW=null");
780                                  if(res){delete res; res = NULL;}            if (res) {
781                                  return false;              delete res;
782                           }              res = NULL;
783                                      }
784                          //Leggi Record dal DB:            return false;
785                          idN=atoll(row->GetField(0));              }
786                          root_id_db=atoll(row->GetField(1));  
787                          pkt_num_in_db=atoll(row->GetField(2));          //Leggi Record dal DB:
788                          pkt_num_fin_db=atoll(row->GetField(3));          idN = atoll(row->GetField(0));
789                          pkt_obt_in_db=atoll(row->GetField(4));          root_id_db = atoll(row->GetField(1));
790                          pkt_obt_fin_db=atoll(row->GetField(5));          pkt_num_in_db = atoll(row->GetField(2));
791                          time_in_db=atoll(row->GetField(6));          pkt_num_fin_db = atoll(row->GetField(3));
792                          time_fin_db=atoll(row->GetField(7));          pkt_obt_in_db = atoll(row->GetField(4));
793                          boot_num_db=atoll(row->GetField(8));                      pkt_obt_fin_db = atoll(row->GetField(5));
794                          perc=atof(row->GetField(9));          time_in_db = atoll(row->GetField(6));
795                                    time_fin_db = atoll(row->GetField(7));
796                          log.str("");          boot_num_db = atoll(row->GetField(8));
797                          log<<"*** ROOT file found in DB has idN= "<<idN<<"  root_id_db= "<<root_id_db;          perc = atof(row->GetField(9));
798                          log<<" pkt_num_in_db= "<<pkt_num_in_db<<"  pkt_num_fin_db= "<<pkt_num_fin_db<<"  pkt_obt_in_db= "<<pkt_obt_in_db<<"  pkt_obt_fin_db= "<<pkt_obt_fin_db;  
799                          log<<"  time_in_db= "<<time_in_db<<"  time_fin_db= "<<time_fin_db<<" boot_num_db= "<<boot_num_db<<"  perc= "<<perc<<"  ***";                              log.str("");
800                          log<<"\n*** Current ROOT file has pkt_number_init= "<<pkt_number_init<<"  obt_init= "<<obt_init<<"  real_time_init= "<<real_time_init;          log << "*** ROOT file found in DB has idN= " << idN << "  root_id_db= " << root_id_db;
801                          log<<" pkt_number_last= "<<pkt_number_last<<"  obt_last= "<<obt_last<<"  real_time_last= "<<real_time_last<<" ***";          log << " pkt_num_in_db= " << pkt_num_in_db << "  pkt_num_fin_db= " << pkt_num_fin_db << "  pkt_obt_in_db= "
802                          slog=log.str();              << pkt_obt_in_db << "  pkt_obt_fin_db= " << pkt_obt_fin_db;
803                          mainLogUtil->logAll(slog);          log << "  time_in_db= " << time_in_db << "  time_fin_db= " << time_fin_db << " boot_num_db= " << boot_num_db
804                          if(perc>percentage)              << "  perc= " << perc << "  ***";
805                          {          log << "\n*** Current ROOT file has pkt_number_init= " << pkt_number_init << "  obt_init= " << obt_init
806                                  mainLogUtil->logInfo("Current ROOT file is better than the one in DB");                              << "  real_time_init= " << real_time_init;
807                                  //modifica DB          log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
808                                  updateMergeROOT_DB(Table_ROOT_Merging,              << real_time_last << " ***";
809                                                                          root_id_db,          slog = log.str();
810                                                                          pkt_num_in_db, pkt_num_fin_db,          mainLogUtil->logAll(slog);
811                                                                          pkt_obt_in_db, pkt_obt_fin_db,          if (perc > percentage) {
812                                                                          time_in_db, time_fin_db,            mainLogUtil->logInfo("Current ROOT file is better than the one in DB");
813                                                                          boot_num_db,            //modifica DB
814                                                                          perc,            updateMergeROOT_DB(Table_ROOT_Merging, root_id_db, pkt_num_in_db, pkt_num_fin_db, pkt_obt_in_db,
815                                                                          idN,(type_Rel_ROOT)relaz);                pkt_obt_fin_db, time_in_db, time_fin_db, boot_num_db, perc, idN, (type_Rel_ROOT) relaz);
816                          }          }
817                          else          else {
818                          {            mainLogUtil->logInfo("Found ROOT file in DB is better than current ROOT file");
819                                  mainLogUtil->logInfo("Found ROOT file in DB is better than current ROOT file");                    if (relaz == AFTER) {
820                                  if(relaz == AFTER)              mainLogUtil->logInfo("Relaz:AFTER = Changing Init values of the Current ROOT file");
821                                  {              pkt_number_init = (pkt_num_fin_db + 1);
822                                          mainLogUtil->logInfo("Relaz:AFTER = Changing Init values of the Current ROOT file");              obt_init = pkt_obt_fin_db;
823                                          pkt_number_init =  (pkt_num_fin_db+1);              real_time_init = time_fin_db;
824                                          obt_init = pkt_obt_fin_db;              log.str("");
825                                          real_time_init = time_fin_db;                log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
826                                          log.str("");                  << obt_init << "  real_time_init= " << real_time_init;
827                                          log<<"\n*** Current ROOT file becomes: pkt_number_init= "<<pkt_number_init<<"  obt_init= "<<obt_init<<"  real_time_init= "<<real_time_init;              log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
828                                          log<<" pkt_number_last= "<<pkt_number_last<<"  obt_last= "<<obt_last<<"  real_time_last= "<<real_time_last<<" ***";                  << real_time_last << " ***";
829                                          slog=log.str();              slog = log.str();
830                                          mainLogUtil->logAll(slog);              mainLogUtil->logAll(slog);
831                                  }            }
832                                  else if(relaz == BEFORE)            else if (relaz == BEFORE) {
833                                  {              mainLogUtil->logInfo("Relaz:BEFORE = Changing Last values of the Current ROOT file");
834                                          mainLogUtil->logInfo("Relaz:BEFORE = Changing Last values of the Current ROOT file");                                                pkt_number_last = (pkt_num_in_db - 1);
835                                          pkt_number_last = (pkt_num_in_db-1);              obt_last = pkt_obt_in_db;
836                                          obt_last = pkt_obt_in_db;              real_time_last = time_in_db;
837                                          real_time_last = time_in_db;  
838                log.str("");
839                                          log.str("");              log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
840                                          log<<"\n*** Current ROOT file becomes: pkt_number_init= "<<pkt_number_init<<"  obt_init= "<<obt_init<<"  real_time_init= "<<real_time_init;                  << obt_init << "  real_time_init= " << real_time_init;
841                                          log<<" pkt_number_last= "<<pkt_number_last<<"  obt_last= "<<obt_last<<"  real_time_last= "<<real_time_last<<" ***";              log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
842                                          slog=log.str();                  << real_time_last << " ***";
843                                          mainLogUtil->logAll(slog);              slog = log.str();
844                                  }              mainLogUtil->logAll(slog);
845                                  else if(relaz == SMALLER)            }
846                                  {            else if (relaz == SMALLER) {
847                                          //non devo proprio salvarlo ed esco ...                                      //non devo proprio salvarlo ed esco ...
848                                          mainLogUtil->logInfo("Relaz:SMALLER = Nothing to save");              mainLogUtil->logInfo("Relaz:SMALLER = Nothing to save");
849                                          mainLogUtil->logInfo("\nFinish merging ROOT files");              mainLogUtil->logInfo("\nFinish merging ROOT files");
850                                          if(res){delete res; res = NULL;}              if (res) {
851                                          if(row){delete row; row = NULL;}                                        delete res;
852                                          return true;                res = NULL;
853                                  }              }
854                                  else if(relaz == BIGGER)//spezzettamento              if (row) {
855                                  {                      delete row;
856                                          mainLogUtil->logInfo("Relaz:BIGGER = (1st part) Saving the first part of the Current ROOT file");                                                                      row = NULL;
857                                          saveMergeROOT_DB(Table_ROOT_Merging, my_id,              }
858                                                  pkt_number_init, (pkt_num_in_db-1),              return true;
859                                                  obt_init, pkt_obt_in_db,            }
860                                                  real_time_init, time_in_db,            else if (relaz == BIGGER)//spezzettamento
861                                                  boot_number,            {
862                                                  percentage);              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                                          mainLogUtil->logInfo("Relaz:BIGGER = (2nd part)Changing Init values of the Current ROOT file");                  real_time_init, time_in_db, boot_number, percentage);
865                                          pkt_number_init = (pkt_num_fin_db+1);  
866                                          obt_init= pkt_obt_fin_db;              mainLogUtil->logInfo("Relaz:BIGGER = (2nd part)Changing Init values of the Current ROOT file");
867                                          real_time_init= time_fin_db;              pkt_number_init = (pkt_num_fin_db + 1);
868                                                        obt_init = pkt_obt_fin_db;
869                                          log.str("");              real_time_init = time_fin_db;
870                                          log<<"\n*** Current ROOT file becomes: pkt_number_init= "<<pkt_number_init<<"  obt_init= "<<obt_init<<"  real_time_init= "<<real_time_init;  
871                                          log<<" pkt_number_last= "<<pkt_number_last<<"  obt_last= "<<obt_last<<"  real_time_last= "<<real_time_last<<" ***";              log.str("");
872                                          slog=log.str();              log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
873                                          mainLogUtil->logAll(slog);                  << obt_init << "  real_time_init= " << real_time_init;
874                                  }//if relaz                                  log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
875                          }//if perc                  << real_time_last << " ***";
876                  }//for num_rows                  slog = log.str();
877           }//if num_rows              mainLogUtil->logAll(slog);
878              }//if relaz
879          if(res){delete res; res = NULL;}          }//if perc
880          if(row){delete row; row = NULL;}                }//for num_rows
881                }//if num_rows
882  }//for relaz  
883        if (res) {
884          mainLogUtil->logInfo("Saving Current ROOT file");              delete res;
885          saveMergeROOT_DB(Table_ROOT_Merging, my_id,        res = NULL;
886                           pkt_number_init, pkt_number_last,      }
887                           obt_init, obt_last,      if (row) {
888                           real_time_init, real_time_last,        delete row;
889                           boot_number,        row = NULL;
890                           percentage);      }
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              if (type_rel == AFTER) {
913                                  stringstream oss;      mainLogUtil->logInfo("Relaz:AFTER = Updating Last values of the DB ROOT file");
914                                  oss.str("");          //marco_new:tolti tutti gli apici che qui non devono essere
915        oss << "UPDATE " << table_name << " SET PKT_NUMBER_FINAL =" << (pkt_number_init - 1) << ", PKT_OBT_FINAL ="
916          if(type_rel == AFTER){          << obt_init << ", REAL_TIME_LAST =" << real_time_init << " WHERE ID_N =" << ID_record << ";";
917                  mainLogUtil->logInfo("Relaz:AFTER = Updating Last values of the DB ROOT file");  
918                  //marco_new:tolti tutti gli apici che qui non devono essere    }
919                  oss << "UPDATE "<< table_name    else if (type_rel == BEFORE) {
920                      << " SET PKT_NUMBER_FINAL ="<< (pkt_number_init - 1)              mainLogUtil->logInfo("Relaz:BEFORE = Updating Init values of the DB ROOT file");
921                          <<", PKT_OBT_FINAL ="<< obt_init      oss << "UPDATE " << table_name << " SET PKT_NUMBER_INIT =" << (pkt_number_last + 1) << ", PKT_OBT_INIT ="
922                      <<", REAL_TIME_LAST ="<< real_time_init<<" WHERE ID_N ="<< ID_record <<";";          << obt_last << ", REAL_TIME_INIT =" << real_time_last << " WHERE ID_N =" << ID_record << ";";
923      }
924          }    else if (type_rel == SMALLER) {
925          else if(type_rel == BEFORE){                  //spezzettamentento
926                  mainLogUtil->logInfo("Relaz:BEFORE = Updating Init values of the DB ROOT file");              mainLogUtil->logInfo("Relaz:SMALLER = (1st part) Updating Last values of the DB ROOT file");
927                  oss << "UPDATE "<< table_name  
928                      << " SET PKT_NUMBER_INIT ="<< (pkt_number_last+1)        oss << "UPDATE " << table_name << " SET PKT_NUMBER_FINAL=" << (pkt_number_init - 1) << ", PKT_OBT_FINAL ="
929                          <<", PKT_OBT_INIT ="<< obt_last          << obt_init << ", REAL_TIME_LAST =" << real_time_init << " WHERE ID_N =" << ID_record << ";";
930                      <<", REAL_TIME_INIT ="<< real_time_last<<" WHERE ID_N ="<< ID_record<<";";  
931          }      mainLogUtil->logInfo("Relaz:SMALLER = (2nd part) Saving the second part of the DB ROOT file");
932          else if(type_rel == SMALLER){            
933                  //spezzettamentento      saveMergeROOT_DB(table_name, root_id, (pkt_number_last + 1), pkt_number_fin, obt_last, obt_fin, real_time_last,
934                  mainLogUtil->logInfo("Relaz:SMALLER = (1st part) Updating Last values of the DB ROOT file");                                                              mtime_last, mboot_num, bad_perc);
935              }
936                  oss << "UPDATE "<< table_name    else if (type_rel == BIGGER) {
937                      << " SET PKT_NUMBER_FINAL="<< (pkt_number_init-1)        //marco_new: ok anche se coincidenti etc
938                          <<", PKT_OBT_FINAL ="<< obt_init      //    oss << "DELETE FROM "<< table_name <<" WHERE ID_N ="<< ID_record<<";"; // EMILIANO
939                              <<", REAL_TIME_LAST ="<< real_time_init<<" WHERE ID_N ="<< ID_record<<";";      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                  mainLogUtil->logInfo("Relaz:SMALLER = (2nd part) Saving the second part of the DB ROOT file");                                              }
942      else
943                  saveMergeROOT_DB(table_name, root_id,      return false;
944                   (pkt_number_last+1), pkt_number_fin,  
945                   obt_last, obt_fin,    string msg = oss.str();
946                   real_time_last, mtime_last,    mainLogUtil->logInfo(msg);
947                   mboot_num,  
948                   bad_perc);    stringstream oss1;
949          }    oss1.str() = "";
950          else if(type_rel == BIGGER){    string msg1;
951          //marco_new: ok anche se coincidenti etc  
952            oss << "DELETE FROM "<< table_name <<" WHERE ID_N ="<< ID_record<<";";    TSQLResult* res = NULL;
953            mainLogUtil->logInfo("Record deleted from merging table");        res = sqlServer->Query(oss.str().c_str());
954          }    if (!res) {
955          else      oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
956                  return false;      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  //cerca eventuali ROOT files in DB che possono venire mergiati  //cerca eventuali ROOT files in DB che possono venire mergiati
968  //marco_new bordi: messo in after a before casi in cui smaller con un bordo in comune  //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  //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  //marco_new bordi: smaller resta solo caso in cui DB e' piu largo sia a dx che a sx
971  TSQLResult* PacketUser::Select_merging(char* table_name, unsigned long int mtime_init, unsigned long int mtime_last, type_Rel_ROOT type_rel)  TSQLResult* PacketUser::Select_merging(const char* table_name, unsigned long int mtime_init, unsigned long int mtime_last,
972  {      type_Rel_ROOT type_rel) {
973          TSQLResult* res=NULL;    TSQLResult* res = NULL;
974          stringstream query;    stringstream query;
975          query.str("");    query.str("");
976    
977          if(type_rel == AFTER)    if (type_rel == AFTER)
978            query<<"select * from "<<table_name<<" where REAL_TIME_LAST > "<< mtime_init <<" and REAL_TIME_LAST <= "<< mtime_last <<" and REAL_TIME_INIT < "<< mtime_init;      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_LAST > " << mtime_init
979          else if(type_rel == BEFORE)          << " and REAL_TIME_LAST <= " << mtime_last << " and REAL_TIME_INIT < " << mtime_init; // EMI
980            query<<"select * from "<<table_name<<" where REAL_TIME_INIT >= "<< mtime_init <<" and REAL_TIME_INIT < "<< mtime_last <<" and REAL_TIME_LAST > "<< mtime_last;    else if (type_rel == BEFORE)
981          else if(type_rel == SMALLER)      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_LAST > "<< mtime_last;          << " and REAL_TIME_INIT < " << mtime_last << " and REAL_TIME_LAST > " << mtime_last; // EMI
983          else if(type_rel == BIGGER)    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          << " and REAL_TIME_LAST > " << mtime_last; // EMI
986                  return 0;    else if (type_rel == BIGGER)
987                query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT >= " << mtime_init
988          query<< " order by REAL_TIME_INIT ASC";//marco_new: inutile          << " and REAL_TIME_LAST <= " << mtime_last; // EMI
989          //se volessi mettere un filtro sulla qualita'    else
990          //      query<<" and NUM_PKT_SAVED - BAD_PKT_CALREAD - BAD_PKT_READ - BAD_PKT >= 2" ;      return 0;
991          string msg = query.str();  
992          mainLogUtil->logAll(msg);    query << " order by REAL_TIME_INIT ASC";//marco_new: inutile
993          res= sqlServer->Query(query.str().c_str());          //se volessi mettere un filtro sulla qualita'
994          stringstream oss1;    //    query<<" and NUM_PKT_SAVED - BAD_PKT_CALREAD - BAD_PKT_READ - BAD_PKT >= 2" ;
995          oss1.str()="";    string msg = query.str();
996          string msg1;    mainLogUtil->logAll(msg);
997        res = sqlServer->Query(query.str().c_str());
998           if (!res)    stringstream oss1;
999           {    oss1.str() = "";
1000                   oss1<<"DBError UNABLE to: "<<query.str().c_str()<<endl;      string msg1;
1001                   msg1=oss1.str();  
1002                   mainLogUtil->logError(msg1);      if (!res) {
1003           }            oss1 << "DBError UNABLE to: " << query.str().c_str() << endl;
1004        msg1 = oss1.str();
1005          return res;      mainLogUtil->logError(msg1);
1006  }    }
1007    
1008  bool PacketUser::saveMergeROOT_DB(char* table_name,  unsigned int root_id,    return res;
1009                          unsigned long int pkt_number_in, unsigned long int pkt_number_fin,  }
1010                          unsigned long int obt_in, unsigned long int obt_fin,  
1011                  unsigned long int mtime_init,   unsigned long int mtime_last,  bool PacketUser::saveMergeROOT_DB(const char* table_name, unsigned int root_id, unsigned long int pkt_number_in,
1012                          unsigned long int mboot_num,      unsigned long int pkt_number_fin, unsigned long int obt_in, unsigned long int obt_fin,
1013                          double percentage)      unsigned long int mtime_init, unsigned long int mtime_last, unsigned long int mboot_num, double percentage) {
1014  {  
1015      stringstream oss;
1016          stringstream oss;    oss.str("");
1017          oss.str("");        oss << "INSERT INTO " << table_name
1018          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, INSERTED_BY)"        << " (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 <<"','"<< obt_fin<< "','"        << " VALUES ('" << 0 << "','" << root_id << "','" << pkt_number_in << "','" << pkt_number_fin << "','" << obt_in
1020      << mtime_init << "','" << mtime_last << "','"        << "','" << obt_fin << "','" << mtime_init << "','" << mtime_last << "','" << mboot_num << "','" << percentage
1021          << mboot_num <<"','"        << "'," << "NULL" << ",'" << tag_value << "'" << ")";
1022          << percentage <<"',"        
1023              <<"NULL"<<",'"    string msg = oss.str();
1024              << tag_value<<"'"    mainLogUtil->logAll(msg);
1025              << ")";  
1026      //marco_new: controlla
1027          string msg = oss.str();    //marco_new: esci se sono arrivato a zero
1028          mainLogUtil->logAll(msg);          //    if(real_time_last==real_time_init){
1029              if (mtime_init == mtime_last) {
1030          //marco_new: controlla      mainLogUtil->logAll("Nothing to be saved");
1031          //marco_new: esci se sono arrivato a zero  
1032  //      if(real_time_last==real_time_init){          //          if(res){delete res; res = NULL;}
1033          if(mtime_init==mtime_last){      //          if(row){delete row; row = NULL;}
1034                  mainLogUtil->logAll("Nothing to be saved");          return true;
1035                              }
1036  //              if(res){delete res; res = NULL;}  
1037  //              if(row){delete row; row = NULL;}    stringstream oss1;
1038                  return true;                                oss1.str() = "";
1039          }    string msg1;
1040    
1041          stringstream oss1;    TSQLResult* res = NULL;
1042          oss1.str()="";    res = sqlServer->Query(oss.str().c_str());
1043          string msg1;    if (!res) {
1044        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1045     TSQLResult* res=NULL;              msg1 = oss1.str();
1046     res= sqlServer->Query(oss.str().c_str());      mainLogUtil->logError(msg1);
1047     if(!res)      return false;
1048     {        }
1049             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;      if (res) {
1050             msg1=oss1.str();      delete res;
1051             mainLogUtil->logError(msg1);        res = NULL;
1052             return false;    }
1053     }    return true;
    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();    }
                 mainLogUtil->logError(msg1);    
                 return 0;  
         }  
   
         idN=atoi(row->GetField(0));  
         if(row){delete row; row = NULL;}  
         if(res){delete res; res = NULL;}  
   
     oss<<". idN = "<<idN;  
         string msg = oss.str();  
         mainLogUtil->logAll(msg);        
1090    
1091          return idN;    idN = atoi(row->GetField(0));
1092      if (row) {
1093        delete row;
1094        row = NULL;
1095      }
1096      if (res) {
1097        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    
1157          TSQLResult* res=NULL;    TSQLResult* res = NULL;
1158          stringstream oss;    stringstream oss;
1159      oss.str("");    oss.str("");
1160          oss << "unlock tables;";    oss << "unlock tables;";
1161    
1162      string msg = oss.str();    string msg = oss.str();
1163          mainLogUtil->logAll(msg);          mainLogUtil->logAll(msg);
1164            
1165          res= sqlServer->Query(oss.str().c_str());    res = sqlServer->Query(oss.str().c_str());
1166                    
1167          stringstream oss1;    stringstream oss1;
1168          oss1.str()="";    oss1.str() = "";
1169          string msg1;    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");  
1170    
1171          return 0;          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      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          if(do_cont_check){    if (do_cont_check) {
1191                  //controllo che non sia gia' aperta      //controllo che non sia gia' aperta
1192                  if(!sqlServer){      if (!sqlServer) {
1193                          sqlServer = TSQLServer::Connect(connection,db_user,db_pwd);        sqlServer = TSQLServer::Connect(connection, db_user, db_pwd);
1194                          if ((!sqlServer)||(!(sqlServer->IsConnected()))){cout<<"Can not connect with MYSQL sever"<<endl;}              if ((!sqlServer) || (!(sqlServer->IsConnected()))) {
1195                          mainLogUtil->logAll("Connected to DB");          cout << "Can not connect with MYSQL sever" << endl;
1196                          //blocca le tabelle        }
1197                          LockTables(tableTobeLocked);                    mainLogUtil->logAll("Connected to DB");
1198                  }        stringstream myquery;
1199          }        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          if(do_cont_check){                                          if (do_cont_check) {
1212                  //controllo che ce ne sia una aperta      //controllo che ce ne sia una aperta
1213                  if(sqlServer && sqlServer->IsConnected()){      if (sqlServer && sqlServer->IsConnected()) {
1214                          //marco_new: sblocca tutte le tabelle        //marco_new: sblocca tutte le tabelle
1215                          UnLockTables();                UnLockTables();
1216                          sqlServer->Close();        sqlServer->Close();
1217                          delete sqlServer;                              delete sqlServer;
1218                          sqlServer=NULL;        sqlServer = NULL;
1219                          mainLogUtil->logAll("Closed Connection to DB");        mainLogUtil->logAll("Closed Connection to DB");
1220                  }      }
1221          }    }
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 );    }
                 fout.open(fno, ios::binary);                      
         }  
                   
         if (!fout) {cout<<"can not open output file "<<fno<<endl; return;}                    
         fout.write(headerPkt,LENGTH_HEADER_PKT);  
         fout.write(pamPkt,length);  
         fout.close();      
 }  
1271    
1272      if (!fout) {
1273        cout << "can not open output file " << fno << endl;
1274        return;
1275      }
1276      fout.write(headerPkt, LENGTH_HEADER_PKT);
1277      fout.write(pamPkt, length);
1278      fout.close();
1279    }
1280    
1281  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.23