Subversion Repositories f9daq

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
326 f9daq 1
//#include "tabela.h"
2
//#include "proba.h"
3
 
4
 
5
#include "vme.h"
6
 
7
//#define PTS_ADDR 0x025F0000
8
//#define PTS_ADDR 0x26000000
9
 
10
#include "PtsModule.h"
11
#define PTS_ADDR 0x61000000
12
#include <windows.h>
13
#include <formatio.h>
14
#include <analysis.h>
15
#include "toolbox.h"
16
#include <cvirte.h>
17
#include <stdlib.h>
18
#include <stdio.h>
19
 
20
#include <string.h>
21
#include <ctype.h>
22
#include <stdint.h>
23
 
24
#include <signal.h>
25
#include <utility.h>
26
#include <ansi_c.h>
27
#include <userint.h>
28
#include "toolbox.h"
29
 
30
#include "sa02lib.h"
31
#include "CAEN_V729.h"
32
#include "CAEN_V729_CVI.h"
33
#include "icfa.h"
34
 
35
#include "MIKRO.h"
36
const int dsize = 144*4;
37
 
38
#include "H1D.h"
39
#include "H2D.h"
40
#include "H3D.h"
41
#include "HDraw.h"
42
#include "dataio.h"
43
#include "sa02lib.h"
44
#include "sa02_CVI.h"
45
 
46
int ProcessUserEvent(int pID, int rID,int mode);
47
 
48
const char  palaser[0xFF]="\"C:\\home\\software\\daq\\LaserDriver-Ver2.0\\Particulars LASER control.exe\"";
49
 
50
#define MAX_THREADS 10
51
const char slowcname[20][20]= {"TMON0","TMON1","VDD","V2P","V2N","VSS","VTH1","VTH2", "VCC12", "VCC15" ,"VCC25", "V38P" };
52
const int chart_control[4]= {P1_CHART_1,P1_CHART_2,P1_CHART_3,P1_CHART_4};
53
const int hapd_serials [4]= { P1_SERIAL_1, P1_SERIAL_2, P1_SERIAL_3, P1_SERIAL_4 };
54
const int fpga_serials [4]= { P1_SERIAL_FPGA_1, P1_SERIAL_FPGA_2, P1_SERIAL_FPGA_3, P1_SERIAL_FPGA_4 };
55
const int hapd_onoff   [4]= { P1_ONOFF_1, P1_ONOFF_2, P1_ONOFF_3, P1_ONOFF_4 };
56
const int p2graph   [4]= { P2_GRAPH_1, P2_GRAPH_2, P2_GRAPH_3, P2_GRAPH_4 };
57
 
58
#define PTS_ADDR 0x61000000
59
 
60
#define MIKRO_COM 4
61
#define MIKRO_X 1
62
#define MIKRO_Y 2
63
#define MIKRO_Z 3
64
 
65
#define TRUE 1
66
#define FALSE 0
67
#define TIMEOUT 3
68
 
69
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
70
uint32_t gVME_CONTROLLER=WIENER_VMEMM;
71
uint32_t gCAEN_V288=0;
72
uint32_t gBELLEPTS=PTS_ADDR;
73
uint32_t gMIKRO_PORT=MIKRO_COM;
74
uint32_t gMIKRO_X=MIKRO_X, gMIKRO_Y=MIKRO_Y, gMIKRO_Z=MIKRO_Y;
75
uint32_t gCENTER_X=176000, gCENTER_Y=170000;
76
double gCENTER_KX=6./300, gCENTER_KY=3./300;
77
uint32_t gCAEN_V729=0;
78
uint32_t gCAEN_V1495=0;
79
uint32_t gFEBParamRead=0;
80
uint32_t gFEBMask=0xF;
81
uint32_t gTriggerType=2;
82
char gFEBParam[0xFF]="";
83
 
84
uint32_t uInterf = 0;
85
 
86
RUNINFO runinfo;
87
RUNREC runrec;
88
ENDREC endrec;
89
POSREC posrec;
90
EVTREC evtrec;
91
EVTREC evtrec1;
92
DATREC datrec;
93
MONREC monrec;
94
ITERATORREC iteratorrec;
95
 
96
 
97
typedef struct {
98
  int chip;
99
  int ch;
100
  int chx;
101
  int chy;
102
} EID2HAPDY;
103
 
104
EID2HAPDY eid2hapdxy[144];
105
 
106
// Variables
107
static int p1h, pID, rID, tfID;
108
static int p2h;
109
static int p3h;
110
static int p4h;
111
static int p5h;
112
static int pm1;
113
static int daq_on,loop_on;
114
static CmtThreadPoolHandle poolHandle = 0;
115
static CmtTSQHandle  pTSQ = 0;
116
static int pTSQData[2];
117
 
118
double datay[10000];
119
double datax[10000];
120
double datayfit[10000];
121
 
122
//const int mux_map[4]={ 1,3,0,2};
123
 
124
int ctrl_c=0;
125
int integer_val=0;
126
FILE *gFp=NULL;
127
 
128
//***********************VARIABLE ZA BRANJE NAPETOSTI***********************//
129
 
130
#include "CAENV288.h"
131
 
132
#define ReadOperationalParam  0x02 //N470
133
#define TurnChanelOn          0x0a //N470  
134
#define TurnChanelOff         0x0b //N470  
135
#define ReadStatus            0x01 //SYS403
136
#define ReadParameters        0x02 //SYS403
137
 
138
int hvmon=0;
139
int hvmonFirst=0;
140
int32_t vset[24], iset[24];
141
 
142
 
143
// reads the run number from the first line in the file
144
int GetRunNumberFromFile(char *fname) {
145
  char line[MAX_PATHNAME_LEN];
146
  int ndim= MAX_PATHNAME_LEN;
147
  int current_run = -1;
148
  FILE *fp = NULL;
149
  ssize_t size;
150
 
151
  if ( GetFileInfo(fname,&size) ) fp = fopen(fname,"r");
152
 
153
  if (fp) {
154
    if (fgets(line,ndim,fp)!= NULL) current_run = atoi(line);
155
    fclose(fp);
156
  }
157
  return current_run;
158
 
159
}
160
 
161
int IncreaseRunNumberInFile(char *fname) {
162
 
163
  int current_run = GetRunNumberFromFile(fname);
164
  FILE *fp = fopen(fname,"w");
165
 
166
  if (fp) {
167
    fprintf(fp,"%d", current_run+1 );
168
    fclose(fp);
169
  }
170
  return current_run+1;
171
}
172
 
173
 
174
//**************************** get station parameters from ini file
175
int readIni(char *fname) {
176
 
177
  FILE *fp = NULL;
178
  char cmd[0xFF],val[0xFF];
179
  int ndim=400;
180
  char line[ndim];
181
  ssize_t size;
182
 
183
  if ( GetFileInfo(fname,&size) ) fp = fopen(fname,"r");
184
  if (!fp) {
185
    sprintf(line, "%s not found. Using default values.\n",fname);
186
    MessagePopup ("Info", line);
187
    return -1;
188
  }
189
  while (fgets(line,ndim,fp)!=NULL) {
190
    sscanf(line,"%s%s",cmd, val);
191
    if (cmd[0]=='#') continue;
192
    if ( strstr(cmd,"VME_CONTROLLER")!= NULL ) {
193
      if ( strstr(val,"WIENER_VMUSB")!= NULL ) gVME_CONTROLLER=WIENER_VMUSB;
194
      if ( strstr(val,"WIENER_VMEMM")!= NULL ) gVME_CONTROLLER=WIENER_VMEMM;
195
      if ( strstr(val,"CAEN_V1718")  != NULL ) gVME_CONTROLLER=CAEN_V1718;
196
      if ( strstr(val,"SIS3153_USB")  != NULL ) gVME_CONTROLLER=SIS3153_USB;
197
    }
198
    if ( strstr(cmd,"CAEN_V288" )!= NULL ) gCAEN_V288 =strtoul(val,NULL,0);
199
    if ( strstr(cmd,"BELLEPTS")  != NULL ) gBELLEPTS  =strtoul(val,NULL,0);
200
    if ( strstr(cmd,"CAEN_V1495")  != NULL ) gCAEN_V1495  =strtoul(val,NULL,0);
201
    if ( strstr(cmd,"MIKRO_PORT")!= NULL ) gMIKRO_PORT=strtoul(val,NULL,0);
202
    if ( strstr(cmd,"MIKRO_X")   != NULL ) gMIKRO_X   =strtoul(val,NULL,0);
203
    if ( strstr(cmd,"MIKRO_Y")   != NULL ) gMIKRO_Y   =strtoul(val,NULL,0);
204
    if ( strstr(cmd,"MIKRO_Z")   != NULL ) gMIKRO_Z   =strtoul(val,NULL,0);
205
    if ( strstr(cmd,"CENTER_X")   != NULL ) gCENTER_X   =strtoul(val,NULL,0);
206
    if ( strstr(cmd,"CENTER_Y")   != NULL ) gCENTER_Y   =strtoul(val,NULL,0);
207
    if ( strstr(cmd,"CENTER_KX")   != NULL ) gCENTER_KX   =strtod(val,NULL);
208
    if ( strstr(cmd,"CENTER_KY")   != NULL ) gCENTER_KY   =strtod(val,NULL);
209
    if ( strstr(cmd,"CAEN_V729") != NULL ) gCAEN_V729 =strtoul(val,NULL,0);
210
    if ( strstr(cmd,"FEBParam") != NULL ) sprintf(gFEBParam,"%s", val);
211
    if ( strstr(cmd,"UI") != NULL ) uInterf =strtoul(val,NULL,0);
212
    if ( strstr(cmd,"FEBMask") != NULL ) gFEBMask =strtoul(val,NULL,0);
213
    if ( strstr(cmd,"TriggerType") != NULL ) gTriggerType =strtoul(val,NULL,0);
214
  }
215
  fclose(fp);
216
  return 0;
217
}
218
//**************************** missing declarations in the library
219
char strbuf[0xFF];
220
 
221
int gLog=0;
222
int sa02Printf(const char *format, ...) {
223
  va_list aptr;
224
  int ret;
225
  FILE *flog;
226
 
227
  va_start(aptr, format);
228
  ret = vsprintf(strbuf, format, aptr);
229
  va_end(aptr);
230
  SetCtrlVal(p1h,P1_STDIO,strbuf);
231
 
232
  if (gLog) {
233
    flog = fopen ("stdio.log", "a");
234
    fprintf (flog, "%s", strbuf);
235
    fclose (flog);
236
  }
237
  return(ret);
238
}
239
 
240
 
241
int CVICALLBACK sa02timeout (int panel, int control, int event,
242
                             void *callbackData, int eventData1, int eventData2) {
243
  switch (event) {
244
    case EVENT_TIMER_TICK:
245
      sa02TimerOut = TRUE;
246
      sa02Printf("sa02timeout\n");
247
      //sa02Printf("TIMEOUT %s in line %d\n", __FILE__ , __LINE__);
248
      break;
249
  }
250
  return 0;
251
}
252
void sa02Timerast (int signumber) {
253
  sa02TimerOut = TRUE;
254
  sa02Printf("TIMEOUT !!!\n");
255
  SetCtrlAttribute (p1h, P1_DAQ_TIMEOUT, ATTR_ENABLED, 0);
256
}
257
 
258
void sa02Tmlnk (int tout) {
259
  sa02TimerOut = FALSE;
260
  SetCtrlAttribute (p1h, P1_DAQ_TIMEOUT, ATTR_INTERVAL,
261
                    (float)tout/100.);
262
  SetCtrlAttribute (p1h, P1_DAQ_TIMEOUT, ATTR_ENABLED, 1);
263
  //  ResetTimer (p1h, P1_DAQ_TIMEOUT);
264
}
265
 
266
void sa02Tmulk ( void ) {
267
  SetCtrlAttribute (p1h, P1_DAQ_TIMEOUT, ATTR_ENABLED, 0);
268
}
269
//****************************
270
 
271
 
272
int EscapeString(const char *i, char *o) {
273
  unsigned int iptr=0, optr = 0;
274
  // walk though the input string
275
  for (iptr = 0; iptr < strlen(i); iptr++, optr++) {
276
    // search for
277
    if ( (i[iptr]=='\\') ) {
278
      sa02Printf("Escape String %d %d \n",i[iptr] , i[iptr]==92 ) ;
279
      //sa02Printf("Escape String %d %d \n",i[iptr] , ( (i[iptr] == 92) || (i[iptr] == 42) )) ;
280
      o[optr] = i[iptr];
281
      optr++;
282
    }
283
 
284
    o[optr] = i[iptr];
285
  }
286
 
287
  o[optr] = '\0';
288
 
289
 
290
  return 0;
291
}
292
 
293
 
294
 
295
int p1plothandle=0;
296
int p2plothandle[4]= {0,0,0,0};
297
int p3plothandle=0;
298
 
299
int plothandle=0;
300
 
301
int phandle[4]= {0,0,0,0};
302
 
303
 
304
int plothandle2dfit=0;
305
int plothandleslix=0;
306
int plothandlesliy=0;
307
int plothandlefit=0;
308
 
309
void SigInt (int sig) {
310
  ctrl_c = 1;
311
  sa02TimerOut=1;
312
}
313
 
314
//int sa02Verbose=0;
315
int module_header(int recid,uint32_t *data,int len) {
316
  data[0] = recid;
317
  data[1] = (len >0)? len : 0 ;
318
  return data[1]+2;
319
}
320
 
321
int PrintData(uint32_t *rdata, int count) {
322
  int j;
323
  uint32_t i;
324
  for (j=0; j<count; j++) {
325
    uint32_t recid   = rdata[j++];
326
    uint32_t len     = rdata[j++];
327
    sa02Printf(" recid=0x%0x len=%d pos=%d(maxpos %d) val=",recid, len, j, count);
328
    if (len>2) {
329
      sa02Printf("\n");
330
    }
331
    for (i=0; i<len; i++) {
332
      if (j< count) {
333
        sa02Printf("0x%0x\t", rdata[j]);
334
      }
335
      if (i%4==3) {
336
        sa02Printf("\n");
337
      }
338
      j++;
339
    }
340
    sa02Printf("\n");
341
    if (len) {
342
      j--;
343
    }
344
  }
345
  return 0;
346
}
347
 
348
//-------------------------------------------------------------------------
349
int CVICALLBACK PlotSliceY (int panel, int control, int event,
350
                            void *callbackData, int eventData1, int eventData2) {
351
  int nslice,i;
352
  int h2=(int) callbackData;
353
 
354
  switch (event) {
355
    case EVENT_COMMIT: {
356
      int ny       =  H2DGetNbinsY(h2);
357
      double miny  =  H2DGetMinY(h2);
358
      double stepy =  H2DGetStepY(h2);
359
      GetCtrlVal(panel,P1_NSLIX,&nslice);
360
 
361
      for (i=0; i < ny; i++ ) {
362
        datax[i]=H2DGetBinContent(h2,nslice,i);
363
      }
364
      if (ny>0) {
365
        if (plothandleslix) {
366
          DeleteGraphPlot (p1h, P1_GRAPHY, plothandleslix, VAL_IMMEDIATE_DRAW);
367
        }
368
 
369
        plothandleslix = PlotWaveform (p1h, P1_GRAPHY, datax, ny,
370
                                       VAL_DOUBLE, 1.0, 0.0, miny,
371
                                       stepy, VAL_FAT_LINE,
372
                                       VAL_EMPTY_SQUARE, VAL_SOLID, 1,
373
                                       VAL_BLUE);
374
      }
375
 
376
    }
377
    break;
378
  }
379
  return 0;
380
}
381
 
382
 
383
int CVICALLBACK PlotSliceX (int panel, int control, int event,
384
                            void *callbackData, int eventData1, int eventData2) {
385
  int nslice,i;
386
  int h2=(int) callbackData;
387
 
388
  switch (event) {
389
    case EVENT_COMMIT: {
390
      int nx       =  H2DGetNbinsX(h2);
391
      double minx  =  H2DGetMinX(h2);
392
      double stepx =  H2DGetStepX(h2);
393
      GetCtrlVal(panel,P1_NSLIY,&nslice);
394
      for (i=0; i < nx; i++ ) {
395
        datax[i]=H2DGetBinContent(h2,i,nslice);
396
      }
397
      if (nx>0) {
398
        if (plothandlesliy) {
399
          DeleteGraphPlot (p1h, P1_GRAPHX, plothandlesliy, VAL_IMMEDIATE_DRAW);
400
        }
401
 
402
        plothandlesliy = PlotWaveform (p1h, P1_GRAPHX, datax, nx,
403
                                       VAL_DOUBLE, 1.0, 0.0, minx,
404
                                       stepx, VAL_FAT_LINE,
405
                                       VAL_EMPTY_SQUARE, VAL_SOLID, 1,
406
                                       VAL_BLUE);
407
      }
408
 
409
    }
410
    break;
411
  }
412
  return 0;
413
}
414
 
415
 
416
 
417
void plot1d(int npoints, double x0, double dx) {
418
  sa02Printf("TEST %d\n", npoints);
419
  if (npoints>0) {
420
    if (plothandle) {
421
      DeleteGraphPlot (p1h, P1_GRAPH, plothandle, VAL_IMMEDIATE_DRAW);
422
    }
423
    plothandle = PlotWaveform (p1h, P1_GRAPH, datay, npoints, VAL_DOUBLE,
424
                               1.0, 0.0, x0, dx, VAL_CONNECTED_POINTS,
425
                               VAL_EMPTY_SQUARE, VAL_SOLID, 1, VAL_BLUE);
426
  }
427
}
428
 
429
/*
430
void plotxy(int h2d){
431
  if (plothandlexy > 0 ) DeleteGraphPlot (p2h, P2_GRAPHXY, plothandlexy, VAL_IMMEDIATE_DRAW);
432
  RangeColors(H2DGetMin(h2d),H2DGetMax(h2d));
433
  plothandlexy = PlotScaledIntensity (p2h, P2_GRAPHXY, H2DGetData(h2d),
434
                   H2DGetNbinsX(h2d), H2DGetNbinsY(h2d), VAL_DOUBLE,
435
                   H2DGetStepY(h2d),H2DGetMinY(h2d),H2DGetStepX(h2d),H2DGetMinX(h2d),
436
                   colormap->array,
437
                   colormap->HiColor,
438
                   colormap->numberofColors, 1, 0);
439
  ProcessSystemEvents ();
440
}
441
*/
442
 
443
int CVICALLBACK ZoomToFebCB (int panel, int control, int event,
444
                             void *callbackData, int eventData1, int eventData2) {
445
  int feb=-1;
446
  float xmin=0, xmax=0;
447
  switch (event) {
448
    case EVENT_COMMIT:
449
      GetCtrlVal(panel,control,&feb);
450
      switch (feb) {
451
        case -1:
452
          xmin=0;
453
          xmax=144*4-1;
454
          break;
455
        default:
456
          xmin =  feb *144;
457
          xmax =xmin+144 -1;
458
          break;
459
      }
460
      SetAxisRange (p1h, P1_GRAPH2D, VAL_MANUAL, xmin, xmax, VAL_NO_CHANGE, 0.0, 1.0);
461
      break;
462
  }
463
  return 0;
464
}
465
 
466
 
467
 
468
 
469
void plot2d(int h2d, int nslice) {
470
  if  (nslice < 0 ) {
471
    nslice=0;
472
  }
473
  if (plothandle2dfit > 0 ) {
474
    DeleteGraphPlot (p1h, P1_GRAPH2D, plothandle2dfit, VAL_IMMEDIATE_DRAW);
475
    plothandle2dfit=0;
476
  }
477
  H2DDraw(h2d,p1h, P1_GRAPH2D, &p1plothandle);
478
 
479
  if (sa02Verbose > 2) {
480
    sa02Printf("min %f max %f  x:min %f step%f y:min %f step%f\n",
481
               H2DGetMin(h2d),H2DGetMax(h2d), H2DGetMinX(h2d),
482
               H2DGetStepX(h2d),H2DGetMinY(h2d), H2DGetStepY(h2d));
483
  }
484
  SetCtrlVal(p1h, P1_NSLIY, nslice);
485
  PlotSliceX(p1h,P1_GRAPHY,EVENT_COMMIT, NULL,0,0);
486
  PlotSliceY(p1h,P1_GRAPHY,EVENT_COMMIT, NULL,0,0);
487
  ProcessSystemEvents ();
488
}
489
 
490
void SetDimming(int state) {
491
  SetCtrlAttribute (p1h, P1_MULTIFPGAWRITE, ATTR_DIMMED, state);
492
  SetCtrlAttribute (p1h, P1_DAQ, ATTR_DIMMED, state);
493
  SetCtrlAttribute (p1h, P1_READOUT, ATTR_DIMMED, state);
494
  SetCtrlAttribute (p1h, P1_FPGAWRITE, ATTR_DIMMED, state);
495
  SetCtrlVal (p1h, P1_LED, state);
496
  SetCtrlAttribute (p2h, P2_DAQ, ATTR_DIMMED, state);
497
  SetCtrlAttribute (p2h, P2_RUNSCRIPT, ATTR_DIMMED, state);
498
  SetCtrlAttribute (p3h, P3_DAQ, ATTR_DIMMED, state);
499
  SetCtrlAttribute (p4h, P4_DAQ, ATTR_DIMMED, state);
500
  SetCtrlAttribute (p1h, P1_STOP, ATTR_DIMMED, !state);
501
  SetCtrlAttribute (p2h, P2_STOP, ATTR_DIMMED, !state);
502
  SetCtrlAttribute (p3h, P3_STOP, ATTR_DIMMED, !state);
503
  SetCtrlAttribute (p4h, P4_STOP, ATTR_DIMMED, !state);
504
}
505
 
506
 
507
uint16_t GetConnectedFebMask(void) {
508
 
509
  uint16_t mask=0;
510
  int ison;
511
  for (int i=0; i<4; i++) {
512
    GetCtrlVal(p1h,hapd_onoff[i], &ison);
513
    mask |= (ison << i);
514
  }
515
  sa02Printf("Connected FEBs mask, 0x%0x\n",mask);
516
  return mask;
517
}
518
 
519
int CVICALLBACK daq(void *functionData) {
520
 
521
  char title[256], serial[64];
522
  int daqmode=1;
523
#define MAXSIZE 10000
524
  int h2=0;
525
  int maxsize = MAXSIZE;
526
  uint32_t *rdata;
527
  uint32_t response[2]= {0,0};
528
 
529
  uint32_t fixeddata =0;
530
  int testfixeddata =0;
531
  uint32_t data    =0;
532
  uint32_t data0    =0;
533
  uint32_t dataoff =0;
534
  uint32_t dataon =0;
535
 
536
  uint32_t cmd     =0;
537
  uint32_t chip    =0;
538
  uint32_t asicpar =0;
539
  uint32_t asicshft=0;
540
  uint32_t dstep   =0;
541
  uint32_t sendswtrg  =0;
542
  uint32_t tpenb   =0;
543
 
544
  uint32_t trglen;
545
  uint16_t mask;
546
  //uint32_t boardnumber_current=0;
547
  // uint32_t hdr[10];
548
 
549
  unsigned int aborttimeout =0;
550
  int append   =0;
551
  int remap    =0;
552
  int neve     =0;
553
  int towrite  =0;
554
  int toread   =0;
555
  int ch       =0;
556
  int output   =0;
557
  int externalcmd   =0;
558
  int i=0,j=0, ir;
559
  int ich;
560
  //int ison;
561
 
562
  char sfixeddata[0xFF]="";
563
  char scmd[0xFF]="";
564
 
565
  char filename[0xFF]="";
566
 
567
  char externalcommand[0xFF]="";
568
 
569
  FILE *fp=NULL;
570
  int nbtotal=0;
571
  time_t t,told, tstart;
572
  int ncount=0;
573
  int nerrors=0;
574
  int readerror=0;
575
  //int writeevents=0;
576
  double fraction=0;
577
  int board;
578
  double t0;
579
 
580
  rdata = malloc(sizeof(uint32_t)*maxsize);
581
 
582
  // intercept routine
583
  if (signal (SIGINT, SigInt) == SIG_ERR) {
584
    perror ("sigignore");
585
  }
586
 
587
 
588
  mask=GetConnectedFebMask();
589
  GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
590
  GetCtrlVal(p1h,P1_APPEND,&append);    // append the data to the file filename
591
  GetCtrlVal(p1h,P1_FRACTION, &fraction);
592
 
593
  GetCtrlVal(p1h,P1_ABORTTOUT, &aborttimeout);
594
 
595
  GetCtrlVal( p1h,P1_EXTERNALCMD, externalcommand);
596
  GetCtrlVal( p1h,P1_EXTCMD, &externalcmd);
597
 
598
  GetCtrlVal(p1h,P1_FIXEDDATA, sfixeddata);
599
  fixeddata =  strtoul (sfixeddata,NULL,0);
600
  GetCtrlVal(p1h,P1_TESTFIXEDDATA, &testfixeddata);
601
 
602
 
603
  GetCtrlVal(p1h,P1_TOREAD, &toread);
604
 
605
 
606
  GetCtrlVal(p1h,P1_NEVE, &neve);
607
  GetCtrlVal(p1h,P1_DSTEP, &dstep );
608
 
609
 
610
  GetCtrlVal(p1h,P1_SENDSWTRIG,&sendswtrg);
611
  GetCtrlVal(p1h,P1_INTTRGLEN, &trglen);
612
  GetCtrlVal(p1h,P1_DAQMODE, &daqmode);
613
  Sa02DaqMode (daqmode);
614
  Sa02SelectTriggerWithMaskAndLength (sendswtrg, mask, trglen);
615
 
616
 
617
  GetCtrlVal(p1h,P1_CHIP,&chip);
618
  GetCtrlVal(p1h,P1_CHANNEL,&ch);
619
  GetCtrlVal(p1h,P1_DATA,&data);
620
  data0=data;
621
  GetCtrlVal(p1h,P1_SCANTYPE,&towrite);
622
  switch (towrite) {
623
    case 1:
624
      GetCtrlVal(p1h,P1_WRITECMD,scmd);
625
      if (strcmp(scmd,"MUXASIC")==0) {
626
        remap=1;
627
      }
628
      cmd =sa02GetCmdCode(scmd);
629
      break;
630
    case 3:
631
      GetCtrlVal(p1h,P1_CHANNELOFF,scmd);
632
      dataoff  = strtoul (scmd,NULL,0);
633
      GetCtrlVal(p1h,P1_CHANNELON,scmd);
634
      dataon  = strtoul (scmd,NULL,0);
635
      chip    =data/36;
636
      ch      =data%36;
637
      sprintf(scmd,"channel");
638
    case 2:
639
      GetCtrlVal(p1h,P1_ASICPAR,scmd);
640
      if (strlen(scmd))  cmd = sa02GetAsicCode(scmd,&asicpar, &asicshft);
641
 
642
      break;
643
  }
644
 
645
 
646
  if (remap) {
647
    data = sa02MuxMap(data);
648
    sa02Printf("MUX %d\n",data);
649
  }
650
 
651
  GetCtrlVal(p1h,P1_TPENB,&tpenb);
652
  //ReplaceAxisItem (p1h, P1_GRAPH2D, VAL_LEFT_YAXIS, 0, scmd, data0);
653
 
654
  if (strlen(filename)>0) {
655
    if (sa02Verbose) {
656
      sa02Printf("Data in the file:%s\n", filename);
657
    }
658
    if (gFp) {
659
      fp=gFp;
660
    } else {
661
      if (append) {
662
        fp=fopen(filename,"ab");
663
      } else {
664
        fp=fopen(filename,"wb");
665
      }
666
    }
667
    output=1;
668
    // run header
669
    runinfo.id= RUNINFO_ID; // run record ID
670
    runinfo.len= sizeof(runinfo);
671
    runinfo.cmd= cmd;
672
    runinfo.x0 = data;
673
    runinfo.dx = dstep;
674
    runinfo.nx = neve;
675
    runinfo.chip= chip;
676
    runinfo.ch  = ch;
677
    runinfo.neve= toread;
678
    runinfo.writemode= towrite;
679
    sa02Printf("RUNINFO x0=%d nx=%d dx=%d\n", runinfo.x0,runinfo.dx,runinfo.nx);
680
    nbtotal+=fwrite(&runinfo, 1,sizeof(runinfo),fp); //gzip
681
  } else {
682
    if (sa02Verbose) {
683
      sa02Printf("Data are not written to the file!\n");
684
    }
685
  }
686
 
687
  if (!neve & (towrite || toread) ) {
688
    neve=1;
689
  }
690
 
691
 
692
  time(&t);
693
  tstart=t;
694
  told=t;
695
  t0 = Timer();
696
 
697
 
698
  title[0] = 0;
699
  for (i=0; i<4; i++) {
700
    int febon=0;
701
    Sa02TestPulseEnable(i, tpenb); // Enable/disable test pulse
702
    sa02GetSerial(i, serial);
703
    GetCtrlVal(p1h,hapd_onoff[i], &febon);
704
    if (strstr(serial,"0x00000000000000")!=NULL && febon) {
705
      char txt[0xFF];
706
      sprintf(txt, "FEB %d not connected or firmware not loaded? Serial number error! Switch Off FEB!",i);
707
      MessagePopup ("Error", txt);
708
      return -1;
709
    }
710
    sprintf(title,"%s FEB%d=%s", title, i, serial);
711
  }
712
 
713
  ///////////////////////////////////////////////////////////////
714
  int icfa_visible=0;
715
  int icfa_add=0;
716
  GetPanelAttribute (p6h, ATTR_VISIBLE, &icfa_visible);
717
  GetCtrlVal (p6h, MINIRICH_ADD, &icfa_add);
718
  if (icfa_visible) {
719
    icfa_Init();
720
    icfa_Histo();
721
  }  
722
  ///////////////////////////////////////////////////////////////
723
  SetCtrlAttribute  (p1h, P1_GRAPH2D, ATTR_LABEL_TEXT , title);
724
  H2DInit(h2, "h2d",title, 144*4, 0,1,neve,data0, dstep);
725
  H2DSetTitleY(h2,scmd);
726
 
727
  sa02Printf("H2D nx=%d ny=%d  i=%d neve=%d\n", H2DGetNbinsX(h2),H2DGetNbinsY(h2), i, neve);
728
 
729
 
730
  plot2d(h2,1);
731
  for (i=0; i<neve; i++) {
732
    int nb = sizeof(uint32_t);
733
    int count=0;
734
 
735
 
736
    for (board=0; board<4; board++) {
737
 
738
      switch (towrite) {
739
        case 1: {
740
          rdata[count+2]= data;
741
          rdata[count+3]= sa02Cmd(board, cmd, data, chip, ch,1,response);
742
          count+=module_header(cmd,&rdata[count],2 );
743
          break;
744
        }
745
        case 2: {
746
          uint32_t datal = asicpar & (data << asicshft);
747
          rdata[count+2] =  data;
748
          rdata[count+3] =  sa02AsicWrite(board, cmd, datal, chip, ch, asicpar,asicshft);
749
          count+=module_header(cmd ,&rdata[count],2); // recid cmd
750
          break;
751
        }
752
        case 3: {
753
          rdata[count+2] =  chip*36+ch;
754
          rdata[count+3] =  sa02AsicWrite(board, cmd, dataon, chip, ch, asicpar,asicshft);  // switch on the channel
755
          count+=module_header(cmd ,&rdata[count],2); // recid cmd
756
          break;
757
        }
758
      }
759
      if (towrite==3) {
760
        SetCtrlVal(p1h,P1_SETVALUE, chip*36+ch );
761
      } else {
762
        SetCtrlVal(p1h,P1_SETVALUE, data);
763
      }
764
 
765
 
766
 
767
    }
768
 
769
    Sa02SetNeve(toread);
770
    sa02Reset();
771
 
772
//    for ( j=0; j< toread; j++)
773
    {
774
      int eventerror =  0;
775
 
776
      if ( (count +2 +dsize)  >= maxsize) {
777
 
778
        maxsize*=2;
779
        sa02Printf("Increasing data buffer to %d elements\n", maxsize);
780
        rdata=realloc(rdata ,sizeof(uint32_t)*maxsize);
781
      }
782
 
783
      do {
784
        if (sendswtrg == 1) Sa02SoftwareTrigger();
785
        nb  = sa02Read(mask, &rdata[count+2] );
786
      } while  ( nb==0 && !ctrl_c);
787
      if (nb==0)  sa02Printf("nb==0 LINE=%d\n",__LINE__);
788
 
789
      if (testfixeddata && nb>0) {
790
        int len = nb / sizeof(uint32_t);
791
        for (ir=0; ir<len; ir++) {
792
          if ( rdata[count+2+ir]!=fixeddata ) {
793
            time(&t);
794
            sa02Printf("INSERT INTO fixederror VALUES ( '%d', '%d','%d','%d','0x%08x','0x%08x' ) \n", t, t-tstart, i*toread+j, ir, rdata[count+2+ir], fixeddata );
795
            eventerror++;
796
          }
797
        }
798
      }
799
      if (eventerror) {
800
        readerror++;
801
        if (readerror==3) {
802
          ctrl_c = 1;
803
          system("date >> firmware.lock");
804
        }
805
      } else {
806
        readerror= 0;
807
      }
808
 
809
      for (ich=0; ich<144*4; ich++) {
810
        int xch = (143 - ich%144) + ich/144*144;
811
        H2DFillBin(h2, xch,i,rdata[count+2+ich]);
812
      }
813
 
814
      if (icfa_visible) icfa_Event(&rdata[count+2], icfa_add );
815
 
816
      /*
817
      for (ich=0; ich<144; ich++) {
818
      //        id=(35-ich/4)+gBoardNumber*36;
819
      //        shft=(ich%4)*8;
820
        id=(17-ich/8)+sa02BoardNumber*18;
821
        shft=(ich%8)*4;
822
 
823
      //        if ( rdata[count+2+id]  & (0xFF <<shft)  ) {
824
        if ( rdata[count+2+id]  & (0xF <<shft)  ) {
825
          H2DFillBin(h2, ich,i,1);
826
        }
827
        if (sa02Verbose>2) {
828
          sa02Printf("%02X ",(rdata[count+2+id]>> shft)& 0xF );
829
      //        sa02Printf("%02X ",(rdata[count+2+id]>> shft)& 0xFF );
830
        }
831
      }
832
      */
833
 
834
      if (sa02Verbose>2) sa02Printf("\n" );
835
      if (nb>=0) count+=module_header(0x3,&rdata[count],nb/sizeof(uint32_t));  // recid 0x3
836
 
837
      if (ctrl_c) {
838
        sa02Printf("ctrl_c detected ....\n");
839
        break;
840
      }
841
 
842
      time(&t);
843
      if (t!=told ) {
844
        double done= (double) (i)/neve;
845
        EstimatedFinish(p1h, P1_PROGRESS, P1_ETA, tstart, done);
846
        plot2d(h2,i-1);
847
        GetPanelAttribute (p6h, ATTR_VISIBLE, &icfa_visible);
848
        if (icfa_visible) icfa_Draw();
849
        SetCtrlVal(p1h,P1_CUREVE, j);
850
        sa02Printf("%d events in %2.2f min (%d s)  TIMEOUTS=%d %s",ncount, (double)(t-tstart)/60.,t-tstart,  nerrors, ctime(&t));
851
      }
852
      if (aborttimeout && (t-tstart)>aborttimeout) {
853
        sa02Printf("Abort timeout reached ....\n");
854
        ctrl_c=1;
855
        break;
856
      }
857
      told=t;
858
      if (nb==0) {
859
        nerrors++;
860
        //j--;    /// kako potem pride cez zeljeno stevil ozadetkov?
861
      } else {
862
        ncount++;
863
      }
864
    }
865
    if (externalcmd) {
866
      char ecmd[256];
867
      sprintf(ecmd,"%s %u %u %u %u",externalcommand,(unsigned int)  tstart,data, rdata[2], rdata[3]);
868
      if (sa02Verbose) {
869
        sa02Printf("Executing external command %s\n",ecmd);
870
      }
871
      system(ecmd);
872
    }
873
 
874
    if (output && Random(0,1)<fraction) {
875
      evtrec.id = EVTREC_ID;
876
      evtrec.len=count*sizeof(uint32_t)+ sizeof(evtrec);
877
      evtrec.time= (uint32_t) time(NULL);
878
      evtrec.nev=i;
879
      nb = (int) fwrite( &evtrec,  1,  sizeof(evtrec),fp); //gzip
880
      if (count) {
881
        nb+= (int) fwrite(&rdata[0],1,count*sizeof(uint32_t),fp);  //gzip
882
      }
883
      if (nb!= (int) evtrec.len) {
884
        sa02Printf("Error writing! %d!=%d\n",nb,evtrec.len);
885
      }
886
      nbtotal+= nb;
887
    }
888
 
889
    if (sa02Verbose==1)  {
890
      sa02Printf("[%d/%d] %u \t", i,count, (unsigned int) time(NULL));
891
      PrintData(rdata,count);
892
    }
893
    if (towrite ==3) {
894
      sa02AsicWrite(board, cmd, dataoff, chip, ch, asicpar, asicshft);
895
      ch += dstep;
896
      if (ch>35) {
897
        ch-=36;
898
        chip++;
899
      }
900
    } else {
901
      data += dstep;
902
    }
903
    if (ctrl_c ) {
904
      if (!testfixeddata) {
905
        sa02Printf("Ctrl+C Program interrupted ....\n");
906
      }
907
      break;
908
    }
909
  }
910
  plot2d(h2, i-1);
911
  if (icfa_visible) icfa_Draw();
912
 
913
  if (output) {
914
    sprintf(scmd,"channel;daqtime=%f", Timer()-t0 );
915
    H2DSetTitleX(h2,scmd);
916
    H2DWrite2File(h2,fp);
917
    if (!gFp) {
918
      fclose(fp);
919
    }
920
  }
921
  if (sa02Verbose>1) sa02Printf("%d bytes written to file %s\n", nbtotal, filename);
922
  time(&t);
923
  if (toread && !testfixeddata) sa02Printf("%d events in %2.2f min  (%f s)  TIMEOUTS=%d  %s",ncount, (double)(Timer()-t0)/60.,Timer()-t0, nerrors, ctime(&t));
924
  free(rdata);
925
 
926
  return 0;
927
}
928
 
929
int CVICALLBACK quit (int panel, int event, void *callbackData,
930
                      int eventData1, int eventData2) {
931
  switch (event) {
932
    case EVENT_CLOSE:
933
      // Stop timer callbacks
934
      SuspendTimerCallbacks();
935
      QuitUserInterface (0);
936
      break;
937
  }
938
  return 0;
939
}
940
 
941
int CVICALLBACK Exit (int panel, int control, int event,
942
                      void *callbackData, int eventData1, int eventData2) {
943
  switch (event) {
944
    case EVENT_COMMIT:
945
      quit(0,0,NULL,0,0);
946
      exit(0);
947
  }
948
  return 0;
949
}
950
 
951
int SetParametersFromFile( const char *fname) {
952
  uint32_t gdata;
953
  uint32_t cdata;
954
 
955
  sa02AsicGlobalRegister  *greg = (sa02AsicGlobalRegister *) &gdata ;
956
  sa02AsicChannelRegister *creg = (sa02AsicChannelRegister *) &cdata ;
957
  unsigned short cregdata[8*144*4];
958
  unsigned short gregdata[7*4*4];
959
#define NDIM 400
960
  int ndim=NDIM;
961
  char line[NDIM];
962
  char cmd[NDIM];
963
  char sasic[NDIM];
964
  char v0[NDIM];
965
  char v1[NDIM];
966
  int asic=0, ch=0;
967
  int gval=0, cval=0;
968
  int board=0;
969
  int row=0;
970
  uint32_t sa02code;
971
  int i;
972
  ssize_t size;
973
  FILE *fp = NULL;
974
  if ( GetFileInfo(fname,&size) ) fp = fopen(fname,"r");
975
  if (!fp) {
976
    sa02Printf("Error! Cannot open file %s\n",fname);
977
    return -1;
978
  }
979
  for (i=0; i<8*144*4; i++) {
980
    cregdata[i]=0;
981
  }
982
  for (i=0; i<7*4*4; i++) {
983
    gregdata[i]=0;
984
  }
985
  gdata=0;
986
  cdata=0;
987
  ResetTextBox(p3h,P3_FPGAPAR,"");
988
  while (fgets(line,ndim,fp)!=NULL) {
989
    int nb = sscanf(line,"%s%s%s%s",cmd,sasic,v0,v1);
990
    if (nb<1 || cmd[0]=='#') {
991
      continue;
992
    }
993
    asic =   strtoul (sasic,NULL,0);
994
    ch   =   strtoul (v0,NULL,0);
995
    gval =   strtoul (v0,NULL,0);
996
    cval =   strtoul (v1,NULL,0);
997
    if (sa02Verbose>2) {
998
      sa02Printf("%d %s",nb,line);
999
    }
1000
    sa02code = sa02GetCmdCode(cmd);
1001
    if (strcmp(cmd,"MUXASIC")==0) {
1002
      asic = sa02MuxMap(asic);
1003
    }
1004
    switch (nb) {
1005
      case 1: {
1006
        if ( sa02code ) {
1007
          SetCtrlVal(p3h,P3_FPGAPAR,line);
1008
 
1009
          break;
1010
        }
1011
        break;
1012
      }
1013
      case 2: {
1014
        if ( sa02code ) {
1015
          SetCtrlVal(p3h,P3_FPGAPAR,line);
1016
 
1017
          break;
1018
        }
1019
        if (strcmp(cmd,"param_board")==0) {
1020
          board= asic;
1021
        }
1022
        if (strcmp(cmd,"load_global")==0) {
1023
          row= asic+1;
1024
          greg->id=13;
1025
          /*
1026
          SetTableCellVal (p3h, P3_GREG, MakePoint (1,row), greg->phasecmps);
1027
          SetTableCellVal (p3h, P3_GREG, MakePoint (2,row), greg->gain);
1028
          SetTableCellVal (p3h, P3_GREG, MakePoint (3,row), greg->shapingtime);
1029
          SetTableCellVal (p3h, P3_GREG, MakePoint (4,row), greg->comparator);
1030
          SetTableCellVal (p3h, P3_GREG, MakePoint (5,row), greg->vrdrive);
1031
          SetTableCellVal (p3h, P3_GREG, MakePoint (6,row), greg->monitor);
1032
          SetTableCellVal (p3h, P3_GREG, MakePoint (7,row), greg->id);
1033
          */
1034
          gregdata[(board*4+asic)*7]   = greg->phasecmps;
1035
          gregdata[(board*4+asic)*7+1] = greg->gain;
1036
          gregdata[(board*4+asic)*7+2] = greg->shapingtime;
1037
          gregdata[(board*4+asic)*7+3] = greg->comparator;
1038
          gregdata[(board*4+asic)*7+4] = greg->vrdrive;
1039
          gregdata[(board*4+asic)*7+5] = greg->monitor;
1040
          gregdata[(board*4+asic)*7+6] = greg->id;
1041
 
1042
          break;
1043
        }
1044
        break;
1045
      }
1046
      case 3: {
1047
        if ( sa02code) {
1048
          SetCtrlVal(p3h,P3_FPGAPAR,line);
1049
          break;
1050
        }
1051
        if (strcmp(cmd,"param_global")==0)    {
1052
          gdata = 0;
1053
          break;
1054
        }
1055
        if (strcmp(cmd,"phasecmps")==0)   {
1056
          greg->phasecmps = gval;
1057
          break;
1058
        }
1059
        if (strcmp(cmd,"gain")     ==0)   {
1060
          greg->gain = gval;
1061
          break;
1062
        }
1063
        if (strcmp(cmd,"shapingtime")==0) {
1064
          greg->shapingtime = gval;
1065
          break;
1066
        }
1067
        if (strcmp(cmd,"comparator")==0)  {
1068
          greg->comparator = gval;
1069
          break;
1070
        }
1071
        if (strcmp(cmd,"vrdrive")==0)     {
1072
          greg->vrdrive = gval;
1073
          break;
1074
        }
1075
        if (strcmp(cmd,"monitor")==0)     {
1076
          greg->monitor = gval;
1077
          break;
1078
        }
1079
        if (strcmp(cmd,"load_ch")==0)   {
1080
          row = board*144+asic*36+ch+1;
1081
          /*
1082
          SetTableCellVal (p3h, P3_CREG, MakePoint (1,row), asic);
1083
          SetTableCellVal (p3h, P3_CREG, MakePoint (2,row), ch);
1084
          SetTableCellVal (p3h, P3_CREG, MakePoint (3,row), creg->decaytime);
1085
          SetTableCellVal (p3h, P3_CREG, MakePoint (4,row), creg->offset);
1086
          SetTableCellVal (p3h, P3_CREG, MakePoint (5,row), creg->fineadj_unipol);
1087
          SetTableCellVal (p3h, P3_CREG, MakePoint (6,row), creg->fineadj_diff);
1088
          SetTableCellVal (p3h, P3_CREG, MakePoint (7,row), creg->tpenb);
1089
          SetTableCellVal (p3h, P3_CREG, MakePoint (8,row), creg->kill);
1090
          */
1091
 
1092
          cregdata[(row -1)*8]   = (unsigned short) asic;
1093
          cregdata[(row -1)*8+1] = (unsigned short) ch;
1094
          cregdata[(row -1)*8+2] = creg->decaytime;
1095
          cregdata[(row -1)*8+3] = creg->offset;
1096
          cregdata[(row -1)*8+4] = creg->fineadj_unipol;
1097
          cregdata[(row -1)*8+5] = creg->fineadj_diff;
1098
          cregdata[(row -1)*8+6] = creg->tpenb;
1099
          cregdata[(row -1)*8+7] = creg->kill;
1100
          cdata=0;
1101
          break;
1102
        }
1103
        if (strcmp(cmd,"select")==0)    {
1104
          sa02Printf ("%s not implemeted yet\n", cmd);
1105
          break;
1106
        }
1107
        break;
1108
      }
1109
      case 4: {
1110
        if (strcmp(cmd,"param_ch")==0)    {
1111
          cdata = 0;
1112
          break;
1113
        }
1114
        if (strcmp(cmd,"decaytime")==0)  {
1115
          creg->decaytime = cval;
1116
          break;
1117
        }
1118
        if (strcmp(cmd,"offset")==0)     {
1119
          creg->offset = cval;
1120
          break;
1121
        }
1122
        if (strcmp(cmd,"fineadj_unipol")==0) {
1123
          creg->fineadj_unipol = cval;
1124
          break;
1125
        }
1126
        if (strcmp(cmd,"fineadj_diff")==0) {
1127
          creg->fineadj_diff   = cval;
1128
          break;
1129
        }
1130
        if (strcmp(cmd,"tpenb")==0)      {
1131
          creg->tpenb = cval;
1132
          break;
1133
        }
1134
        if (strcmp(cmd,"kill")==0)       {
1135
          creg->kill  = cval;
1136
          break;
1137
        }
1138
        break;
1139
      }
1140
    }
1141
 
1142
  }
1143
  fclose(fp);
1144
  SetTableCellRangeVals (p3h, P3_CREG, MakeRect (1, 1, 144*4, 8), cregdata, VAL_ROW_MAJOR);
1145
  SetTableCellRangeVals (p3h, P3_GREG, MakeRect (1, 1, 4*4, 7)  , gregdata, VAL_ROW_MAJOR);
1146
 
1147
  sa02Printf("Parameters loaded from file %s to Parameter Panel \n", fname);
1148
  return 0;
1149
}
1150
 
1151
void CVICALLBACK MenuCB(int menubar, int menuItem, void *callbackData, int panel) {
1152
  switch (menuItem) {
1153
    case MENU_OPERATIO_CAEN_V729:
1154
      DisplayPanel(p4h);
1155
      break;
1156
    case MENU_OPERATIO_SA02CFG :
1157
      DisplayPanel(p3h);
1158
      break;
1159
    case MENU_OPERATIO_2DSCAN:
1160
      DisplayPanel(p2h);
1161
      break;
1162
    case MENU_OPERATIO_LASER:
1163
      DisplayPanel(p5h);
1164
      break;
1165
    case MENU_MINIRICH:
1166
      DisplayPanel(p6h);
1167
      break;  
1168
    case MENU_OPERATIO_EXIT :
1169
      quit(0,0,NULL,0,0);
1170
      exit(0);
1171
      //loop_on=0;
1172
      break;
1173
    case MENU_HELP :
1174
      sa02Help();
1175
      break;
1176
  }
1177
}
1178
 
1179
int CVICALLBACK daq_readonly(void *functionData) {
1180
  int h2=0;
1181
  uint32_t trglen;
1182
  uint32_t data[10000];
1183
  uint16_t mask;
1184
  //int ison;
1185
  //int *fdata= (int *) functionData;
1186
  int nbit,neve,nb,ch,i,j,sendswtrg;
1187
 
1188
  time_t t,told, tstart;
1189
  //int gBoardNumber=0;
1190
  int ploteachevent =0;
1191
 
1192
  GetCtrlVal(p1h,P1_PLOTEACHEVENT, &ploteachevent);
1193
  GetCtrlVal(p1h,P1_TOREAD , &neve);
1194
  GetCtrlVal(p1h,P1_NSLIX , &nbit);
1195
  if (nbit>7) {
1196
    nbit=7;
1197
  }
1198
  GetCtrlVal(p1h,P1_SENDSWTRIG,&sendswtrg);
1199
  GetCtrlVal(p1h,P1_INTTRGLEN, &trglen);
1200
 
1201
  mask=GetConnectedFebMask();
1202
  Sa02SelectTriggerWithMaskAndLength (sendswtrg, mask, trglen);
1203
  Sa02SetNeve(2);
1204
 
1205
  H2DInit(h2,"hbit","Bit Occupancy", 144*4, 0,1,8,0, 1);
1206
  H2DSetTitleX(h2,"channel");
1207
  H2DSetTitleY(h2,"Data bit");
1208
  time(&t);
1209
  tstart=t;
1210
  told=t;
1211
  for ( j=0; j< neve; j++) {
1212
    do {
1213
      if (sendswtrg==1) Sa02SoftwareTrigger();
1214
      nb  = sa02Read(mask, data );
1215
    } while  ( nb==0 && !ctrl_c);
1216
    if (nb==0)  sa02Printf("nb==0 LINE=%d\n",__LINE__);
1217
 
1218
    if (ctrl_c==1) break;
1219
 
1220
    for (ch=0; ch<144*4; ch++) {
1221
      int board = ch/144;
1222
      int xch   = (143 - ch%144) + board *144;
1223
      for (i=0; i<8; i++) if (data[ch] & (1<<i) ) H2DFillBin(h2,xch,i,1);
1224
    }
1225
    /*
1226
    for (ch=0; ch<144*4; ch++)
1227
    {
1228
      id=(35-ch/4)+gBoardNumber*36;
1229
      shft=(ch%4)*8;
1230
      for (i=0; i<8; i++)
1231
      {
1232
        if (data[id] & (1<<(i+shft)) )
1233
        {
1234
          H2DFillBin(h2,ch,i,1);
1235
        }
1236
      }
1237
      if (sa02Verbose>2)
1238
      {
1239
        sa02Printf("%02X ",(data[id]>> shft)& 0xFF );
1240
      }
1241
    }
1242
    */
1243
 
1244
    if (sa02Verbose>2) {
1245
      sa02Printf("\n" );
1246
    }
1247
 
1248
    time(&t);
1249
    if (t!=told || ploteachevent) {
1250
      sa02Printf("%d events in %2.2f min (%d s) %s",j, (double)(t-tstart)/60.,t-tstart, ctime(&t));
1251
      GetCtrlVal(p1h,P1_NSLIY,&nbit);
1252
      plot2d(h2, nbit);
1253
      GetCtrlVal(p1h,P1_PLOTEACHEVENT, &ploteachevent);
1254
      SetCtrlVal(p1h,P1_CUREVE, j);
1255
      ProcessSystemEvents ();
1256
      ProcessSystemEvents ();
1257
    }
1258
 
1259
    told=t;
1260
 
1261
  }
1262
 
1263
  plot2d(h2, nbit);
1264
  SetCtrlVal(p1h,P1_CUREVE, j);
1265
 
1266
  return 0;
1267
}
1268
 
1269
int CVICALLBACK LoadParameters (int panel, int control, int event,
1270
                                void *callbackData, int eventData1, int eventData2) {
1271
  char fname[0xFF];
1272
  uint16_t mask;
1273
  switch (event) {
1274
    case EVENT_COMMIT:
1275
      mask=GetConnectedFebMask();
1276
      sa02Printf("LoadParameters 0x%0x\n", mask);
1277
      GetCtrlVal(p3h, P3_INPUTFILE, fname);
1278
      GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
1279
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 1);
1280
      sa02LoadParametersFromFile(fname, mask);
1281
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 0);
1282
 
1283
      break;
1284
  }
1285
  return 0;
1286
}
1287
 
1288
int SlowControl(uint32_t board, FILE *fp) {
1289
  uint32_t data;//,step,cmd;//,response[2]= {0,0};
1290
  int chip,channel,i;
1291
  //double doubleval;
1292
  char saddress[0xFF];
1293
  double sdata[20];
1294
 
1295
  chip=0;
1296
  channel=0;
1297
  data=0;
1298
 
1299
  GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
1300
  sa02Status(board,saddress,sdata);
1301
  SetCtrlVal(p1h,fpga_serials[board],saddress);
1302
  if (fp) {
1303
    fprintf(fp,"<slowc>\n<id>%d</id>\n", board );
1304
    fprintf(fp,"<dna>%s</dna>\n",saddress );
1305
    for (i=0; i<12; i++) fprintf(fp,"<%s>%f</%s>\n",slowcname[i],sdata[i],slowcname[i] );
1306
    fprintf(fp,"</slowc>\n" );
1307
  }
1308
  PlotStripChart (p1h, chart_control[board], sdata, 12, 0, 0, VAL_DOUBLE);
1309
  return 0;
1310
}
1311
 
1312
 
1313
int WriteChannelParameters ( int offset, int fine_offset, int tpenb) {
1314
 
1315
  uint32_t response[2]= {0,0};
1316
  uint32_t cdata;
1317
 
1318
  sa02AsicChannelRegister *creg = (sa02AsicChannelRegister *) &cdata ;
1319
  unsigned int i=0, j=0;
1320
  int row=0;
1321
  unsigned short val,asic,ch, board;
1322
  uint16_t mask=GetConnectedFebMask();
1323
  for (j=0; j<144*4; j++) {
1324
    i = j%144;
1325
    board = (unsigned short) j/144;
1326
    asic=(unsigned short )(i/36);
1327
    ch=(unsigned short )(i%36);
1328
    row=j+1;
1329
    GetTableCellVal (p3h, P3_CREG, MakePoint (1,row), &asic);
1330
    GetTableCellVal (p3h, P3_CREG, MakePoint (2,row), &ch);
1331
    GetTableCellVal (p3h, P3_CREG, MakePoint (3,row), &val);
1332
    creg->decaytime=val;
1333
    creg->offset = offset;
1334
    creg->fineadj_unipol = fine_offset;
1335
    GetTableCellVal (p3h, P3_CREG, MakePoint (6,row), &val);
1336
    creg->fineadj_diff = val;
1337
    creg->tpenb = tpenb;
1338
    //sa02Printf("===%d   %d\n",i, tpenb);
1339
    GetTableCellVal (p3h, P3_CREG, MakePoint (8,row), &val);
1340
    creg->kill = val;
1341
    creg->unused=0;
1342
    if ( mask &(1<<board)) sa02Cmd(board,SA0x_ASIC0_CREG, cdata, asic, ch,1,response);
1343
 
1344
    if (ctrl_c) {
1345
      break;
1346
    }
1347
  }
1348
  return 0;
1349
}
1350
 
1351
int FebTestAna(void) {
1352
  int current_run;
1353
  char cmdCommand[0xFF];
1354
  current_run = GetRunNumberFromFile("current_run.txt");
1355
  sprintf(cmdCommand ,"C:/root/bin/root.exe \"../macros/febreport.cxx(\\\"data\\\", %d )\"", current_run);
1356
  sa02Printf("%s\n",cmdCommand);
1357
  LaunchExecutable(cmdCommand);
1358
  return 0;
1359
}
1360
 
1361
int FebTest(void) {
1362
  int board=0, j=0, value, step;
1363
 
1364
  FILE *fp;
1365
  int ndim=400;
1366
  char line[ndim];
1367
  int current_run=1;
1368
  time_t t;
1369
  int start;
1370
  int addheader=1;
1371
  char filename[0xFF];
1372
  char cmdCommand[0xFF];
1373
 
1374
  uint32_t mask=GetConnectedFebMask();
1375
 
1376
  LoadParameters(p3h, P3_LOADPAR,EVENT_COMMIT,NULL,0,0);
1377
 
1378
 
1379
  fp = fopen ("current_run.txt","r");
1380
  if (fp) {
1381
    if (fgets(line,ndim,fp)!=NULL) current_run=atoi(line)+1;
1382
    fclose(fp);
1383
    fp= NULL;
1384
  }
1385
 
1386
  sprintf(line,"data\\febtest_%04d.dat",current_run );
1387
  SetCtrlVal(p1h,P1_OUTPUTFILE, line);
1388
 
1389
  SetCtrlVal(p1h,P1_SENDSWTRIG,3 ); // set internal trigger
1390
  SendTriggerTypeCB(p1h,P1_TEST, EVENT_COMMIT,NULL, 0,0);
1391
 
1392
  ThresholdLinearityCB (p1h, P1_THRVSADC, EVENT_COMMIT, NULL, 0, 0 );
1393
 
1394
  GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
1395
  fp = fopen(line, "ab");
1396
  if(fp) {
1397
    for (board=0; board<4; board++) if ( mask &(1<<board))  H1DWrite2File(board,fp);
1398
    fclose(fp);
1399
  }
1400
 
1401
 
1402
  sprintf(line,"data/febslowc_%04d.xml",current_run );
1403
//  SetCtrlVal(p1h, P1_RUNID, current_run);
1404
  fp = fopen (line,"w");
1405
  fprintf(fp,"<febtest>\n");
1406
  time(&t);
1407
  fprintf(fp,"<time>%s</time>\n", ctime(&t));
1408
 
1409
 
1410
 
1411
  if (!ctrl_c)  for (board=0; board<4; board++) {
1412
      if ( mask &(1<<board)) {
1413
        for (j=0; j<10; j++) {
1414
          SlowControl(board,fp);
1415
          ProcessSystemEvents ();
1416
          if (ctrl_c) break;
1417
        }
1418
      }
1419
      if (ctrl_c) break;
1420
    }
1421
 
1422
 
1423
  fprintf(fp,"</febtest>\n");
1424
  fclose(fp);
1425
 
1426
 
1427
  fp = fopen ("current_run.txt","w");
1428
  fprintf(fp,"%d\n", current_run);
1429
  fclose(fp);
1430
 
1431
 
1432
 
1433
 
1434
 
1435
  WriteChannelParameters ( 0,0,0);   // Test pulse on all channels
1436
  for (board=0; board<4; board++) if ( mask &(1<<board)) SlowControl(board,fp);
1437
  SetCtrlVal(p1h,P1_TPENB,1);    // enable test pulse
1438
 
1439
  SetCtrlVal(p1h,P1_DATA, 350);
1440
  SetCtrlVal(p1h,P1_NEVE, 150);
1441
 
1442
  GetCtrlVal(p1h,P1_DATA, &start);
1443
 
1444
  daq(NULL);
1445
  SetCtrlVal(p1h,P1_TPENB,0);    // disable test pulse
1446
 
1447
 
1448
  // coarse offset
1449
  step=1;
1450
  if (!ctrl_c)  for (value=0; value<16; value+=step) {
1451
      if (addheader) {
1452
        iteratorrec.id = ITERATORREC_ID;
1453
        iteratorrec.len = sizeof(iteratorrec);
1454
        iteratorrec.value = value;
1455
        iteratorrec.n     = 16;
1456
        iteratorrec.step  = step;
1457
        iteratorrec.level = 1;
1458
        GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
1459
        fp = fopen(filename, "ab");
1460
        if(fp) {
1461
          fwrite (&iteratorrec, 1, iteratorrec.len, fp);
1462
          fclose(fp);
1463
        }
1464
      }
1465
 
1466
      WriteChannelParameters ( value,0,1);
1467
 
1468
      SetCtrlVal(p1h,P1_DATA,start - (value%8) * 13 + (value/8)*13*8 );
1469
      sa02Printf("offset=>%d\n", value);
1470
      daq(NULL);
1471
      if (ctrl_c) break;
1472
    }
1473
 
1474
  // fine offset
1475
  if (!ctrl_c)  for (value=0; value<16; value+=step) {
1476
      if (addheader) {
1477
        iteratorrec.id = ITERATORREC_ID;
1478
        iteratorrec.len = sizeof(iteratorrec);
1479
        iteratorrec.value = value;
1480
        iteratorrec.n     = 16;
1481
        iteratorrec.step  = step;
1482
        iteratorrec.level = 1;
1483
        GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
1484
        fp = fopen(filename, "ab");
1485
        if(fp) {
1486
          fwrite (&iteratorrec, 1, iteratorrec.len, fp);
1487
          fclose(fp);
1488
        }
1489
      }
1490
 
1491
 
1492
      WriteChannelParameters (0, value,1);
1493
 
1494
      SetCtrlVal(p1h,P1_DATA, start - (value%8)  + (value/8)*8 );
1495
      sa02Printf("offset=>%d\n", value);
1496
      daq(NULL);
1497
      if (ctrl_c) break;
1498
    }
1499
 
1500
  SetCtrlVal(p1h,P1_DATA, start);
1501
 
1502
  GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
1503
 
1504
  sprintf(cmdCommand,"..\\sa02read -i %s -o data\\febtest_%04d.root", filename, current_run);
1505
  sa02Printf("%s\n",cmdCommand);
1506
  LaunchExecutable(cmdCommand);
1507
 
1508
  //sprintf(cmdCommand ,"C:/root/bin/root.exe ../macros/febreport.cxx(\\\"data/febtest_%04d.root\\\")", current_run);
1509
  sprintf(cmdCommand ,"C:/root/bin/root.exe \"../macros/febreport.cxx(\\\"data\\\", %d )\"", current_run);
1510
  sa02Printf("%s\n",cmdCommand);
1511
  LaunchExecutable(cmdCommand);
1512
 
1513
  sprintf(line,"%s", "test.dat");
1514
  SetCtrlVal(p1h,P1_OUTPUTFILE, line);
1515
  //daq(NULL);
1516
  return 0;
1517
}
1518
 
1519
 
1520
int CVICALLBACK ThresholdLinearityCB (int panel, int control, int event,
1521
                                      void *callbackData, int eventData1, int eventData2) {
1522
  const int kmax= 1024;
1523
  const int boardmax= 4;
1524
 
1525
  switch (event) {
1526
    case EVENT_COMMIT: {
1527
      uint32_t val,retval, board,data,response[2]= {0,0};
1528
      int k;
1529
      int chip,channel;
1530
      double doubleval;
1531
      time_t t,told;
1532
      char title[0xFF];
1533
      char name[0xFF];
1534
      int h1=0;
1535
      uint16_t mask=GetConnectedFebMask();
1536
      chip=0;
1537
      channel=0;
1538
      GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
1539
 
1540
      for (board=0; board<boardmax; board++) if ( mask &(1<<board)) {
1541
          char serial[0xFF];
1542
          GetCtrlVal(p1h,hapd_serials[board],serial );
1543
          sprintf(title,"VTH1 linearity, position  %d sn=%s", board, serial);
1544
          sprintf(name,"vth1_%d", board);
1545
          H1DInit(h1+board, name,title, kmax, 0 ,1);
1546
          H1DSetTitleX(h1+board,"VTH1");
1547
          H1DSetTitleY(h1+board,"ADC(VTH1)");
1548
          SetCtrlAttribute  (p1h, P1_GRAPH, ATTR_XNAME, H1DGetTitleX(h1+board) );
1549
          SetCtrlAttribute  (p1h, P1_GRAPH, ATTR_YNAME, H1DGetTitleY(h1+board) );
1550
          //SetCtrlAttribute  (p1h, P1_GRAPH, ATTR_LABEL_TEXT , H1DGetTitle(h1+board) );
1551
          if (phandle[board]> 0 ) DeleteGraphPlot (p1h, P1_GRAPH, phandle[board], VAL_IMMEDIATE_DRAW);
1552
          phandle[board] = 0;
1553
        }
1554
      for (board=0; board<boardmax; board++) if ( mask &(1<<board)) {
1555
          val=sa02Cmd(board, FEB_MUX, data=0x20, chip, channel ,1,response);  // set mux to  VTH1
1556
          time(&t);
1557
          told=t;
1558
          if (ctrl_c) break;
1559
          for (k=0; k<kmax; k++) {
1560
            if (ctrl_c) break;
1561
            SetCtrlVal(p1h,P1_SETSINGLEVALUE,k);
1562
            SetCtrlVal(p1h,P1_CUREVE,k);
1563
            retval=sa02Cmd(board, FEB_VTH1 , k  , chip, channel ,1, response);
1564
            val=sa02Cmd(board, FEB_ADC_READ, data, chip, channel ,1,response);
1565
            if (sa02BoardType>2)
1566
              doubleval = (2*((val & 0xFFF) + 0.5)/0x1000 - 1.) * 3.3;
1567
            else
1568
              doubleval = ((val & 0xFFF) + 0.5)/0x1000 * 3.3;
1569
 
1570
 
1571
            H1DFillBin(h1+board, k, doubleval);
1572
            if (t!=told || k==kmax-1 ||k==0 ) {
1573
              H1DDraw(h1+board,p1h, P1_GRAPH, &phandle[board]);
1574
              sa02Printf("[%d] set VTH1=%d  ADC(VTH1)= %6.3f V\n",board, k,  doubleval);
1575
              SetCtrlVal(p1h,P1_CUREVE, k);
1576
              ProcessSystemEvents ();
1577
            }
1578
            told=t;
1579
            time(&t);
1580
          }
1581
        }
1582
      break;
1583
    }
1584
  }
1585
  return 0;
1586
}
1587
 
1588
 
1589
int CVICALLBACK MultiFpgaWrite (void *functionData) {
1590
  uint32_t val, board,data,step,cmd,response[2]= {0,0};
1591
  char  scmd[0xFF],sdata[0xFF];
1592
  int chip, channel;
1593
  char filename[0xFF];
1594
  double delay, doubleval=0, x0, dx;
1595
  int neve,i,daqexe,addheader;
1596
  time_t t,told, tstart;
1597
  FILE *fp;
1598
  //int h2=0;
1599
  int *fdata= (int *) functionData;
1600
 
1601
  datrec.id = DATREC_ID;
1602
  datrec.len = sizeof(datrec);
1603
  GetCtrlVal(p1h,P1_MULTINEVE , &neve);
1604
  GetCtrlVal(p1h,P1_WAIT , &delay);
1605
  GetCtrlVal(p1h, P1_SINGLEWRITECMD, scmd);
1606
  cmd=sa02GetCmdCode(scmd);
1607
  GetCtrlVal(p1h,P1_BOARDNUMBER, &board);
1608
  GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
1609
  GetCtrlVal(p1h, P1_SINGLEDATA, sdata);
1610
  data =  strtoul (sdata,NULL,0);
1611
//        if (strcmp(scmd,"MUXASIC")==0) {
1612
//               data = sa02MuxMap(data);
1613
//               sa02Printf("MUX %d\n",data);
1614
//        }
1615
  GetCtrlVal(p1h, P1_SINGLEDATA, sdata);
1616
  data =  strtoul (sdata,NULL,0);
1617
  x0=(double)data;
1618
  GetCtrlVal(p1h, P1_DSTEP0, &step);
1619
  dx=(double)step;
1620
  GetCtrlVal(p1h,P1_SINGLECHIP,&chip);
1621
  GetCtrlVal(p1h,P1_SINGLECHANNEL,&channel);
1622
  if (fdata[0]==P1_FPGAWRITE) {
1623
    neve=1;
1624
  }
1625
  GetCtrlVal(p1h,P1_DAQEXE,&daqexe);
1626
  GetCtrlVal(p1h,P1_ADDHEADER,&addheader);
1627
  time(&t);
1628
  tstart=t;
1629
  told=t;
1630
  if (addheader) {
1631
    iteratorrec.id = ITERATORREC_ID;
1632
    iteratorrec.len = sizeof(iteratorrec);
1633
    iteratorrec.value = data;
1634
    iteratorrec.n     = neve;
1635
    iteratorrec.step  = step;
1636
    iteratorrec.level = 2;
1637
    GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
1638
    fp = fopen(filename, "ab");
1639
    if(fp) {
1640
      fwrite (&iteratorrec, 1, iteratorrec.len, fp);
1641
      fclose(fp);
1642
    }
1643
  }
1644
  for (i=0; i<neve; i++) {
1645
    SetCtrlVal(p1h,P1_SETSINGLEVALUE,data);
1646
    SetCtrlVal(p1h,P1_CUREVE,i);
1647
    val=sa02Cmd(board, cmd, data, chip, channel ,1, response);
1648
    if (addheader) {
1649
      datrec.cmd    =cmd;
1650
      datrec.data   =data;
1651
      datrec.chip   =chip;
1652
      datrec.channel=channel;
1653
      datrec.retval =val;
1654
      GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
1655
      fp = fopen(filename, "ab");
1656
      if(fp) {
1657
        fwrite (&datrec, 1, datrec.len, fp);
1658
        fclose(fp);
1659
      }
1660
    }
1661
    switch (cmd & (~ FEB_RO)) {
1662
      case FEB_ADC_READ:
1663
      case FEB_ADC_RESET:
1664
        doubleval = ((val & 0xFFF) + 0.5)/0x1000 * 3.3;
1665
        sa02Printf("ADC %f, 0x%08x\n", doubleval, val ) ;
1666
        break;
1667
      case FEB_TMON1:
1668
      case FEB_TMON0:
1669
        doubleval = ( (val >>2 ) & 0xFFF ) * 0.0625;
1670
        if (val&0x4000) {
1671
          doubleval=-doubleval;
1672
        }
1673
        sa02Printf("TMON %f 0x%x\n",doubleval, val ) ;
1674
        break;
1675
      case FEB_VTH1:
1676
      case FEB_VTH2:
1677
        doubleval = (val & 0xFFFF );
1678
        if (cmd & 1)
1679
          val=0x20;
1680
        else
1681
          val=0x30;
1682
        val=sa02Cmd(board, FEB_MUX, val, 0, 0 ,1,response);
1683
        val=sa02Cmd(board, FEB_ADC_READ, 0, 0, 0, 1,response);
1684
        if (sa02BoardType>2)
1685
          doubleval = (2*((val & 0xFFF) + 0.5)/0x1000 - 1.) * 3.3;
1686
        else
1687
          doubleval = ((val & 0xFFF) + 0.5)/0x1000 * 3.3;
1688
        sa02Printf("%5d %6.3f\n",data, doubleval);
1689
        break;
1690
      case SA0x_ASIC0_GREG:
1691
        if (cmd & FEB_RO) {
1692
          sa02PrintGREG(&val,"Returned GREG data->");
1693
        }
1694
        break;
1695
      case SA0x_ASIC0_CREG:
1696
        if (cmd & FEB_RO) {
1697
          sa02PrintCREG(&val,"Returned CREG data->");
1698
        }
1699
        break;
1700
      default:
1701
        sa02Printf("0x%08X\n",val);
1702
//        break;
1703
    }
1704
    datay[i]=doubleval;
1705
    if (delay>0 && fdata[0]==P1_MULTIFPGAWRITE) {
1706
      Delay(delay);
1707
    }
1708
    if  (daqexe) {
1709
      daq(NULL);
1710
    }
1711
    if (ctrl_c) {
1712
      break;
1713
    }
1714
    if (t!=told  ) {
1715
      plot1d(i,x0,dx);
1716
      SetCtrlVal(p1h,P1_CUREVE, i);
1717
      ProcessSystemEvents ();
1718
    }
1719
    data+=step;
1720
    told=t;
1721
    time(&t);
1722
  }
1723
  plot1d(i,x0,dx);
1724
  SetCtrlVal(p1h,P1_CUREVE, i);
1725
  return 0;
1726
}
1727
 
1728
int CVICALLBACK SendSEUTRigger (int panel, int control, int event,
1729
                                void *callbackData, int eventData1, int eventData2) {
1730
 
1731
  switch (event) {
1732
    case EVENT_COMMIT:
1733
      Sa02SEUTrigger();
1734
      break;
1735
  }
1736
  return 0;
1737
}
1738
 
1739
int CVICALLBACK FSelect (int panel, int control, int event,
1740
                         void *callbackData, int eventData1, int eventData2) {
1741
  int status,fcontrol = 0;
1742
  char pathName[MAX_PATHNAME_LEN];
1743
  char defName[MAX_PATHNAME_LEN];
1744
  char fileMessage[100] = "";
1745
  switch (event) {
1746
    case EVENT_COMMIT:
1747
      switch (control) {
1748
        case P3_FSELECT:
1749
          fcontrol=P3_INPUTFILE;
1750
          strcpy(fileMessage,"Select Parameter file");
1751
          break;
1752
        case P3_PTSFSELECT:
1753
          fcontrol=P3_PTSFIRMWARE;
1754
          strcpy(fileMessage,"Select PTS Firmware file");
1755
          break;
1756
      }
1757
      sa02Printf("MAX_PATHNAME_LEN %d\n",MAX_PATHNAME_LEN);
1758
      GetCtrlVal(panel,fcontrol,defName);
1759
      status = FileSelectPopup ("",defName,"",
1760
                                fileMessage, VAL_LOAD_BUTTON, 0,
1761
                                0, 1, 0, pathName);
1762
      if (status>0)
1763
        SetCtrlVal(panel,fcontrol,pathName);
1764
      break;
1765
  }
1766
  return 0;
1767
}
1768
 
1769
int CVICALLBACK Verbose (int panel, int control, int event,
1770
                         void *callbackData, int eventData1, int eventData2) {
1771
  //int * data;
1772
  switch (event) {
1773
    case EVENT_COMMIT:
1774
      GetCtrlVal(panel,control,&sa02Verbose);
1775
      break;
1776
  }
1777
  return 0;
1778
}
1779
 
1780
int CVICALLBACK Print (int panel, int control, int event,
1781
                       void *callbackData, int eventData1, int eventData2) {
1782
  char dfile[MAX_PATHNAME_LEN];
1783
  char name[MAX_PATHNAME_LEN];
1784
  int h2=0;
1785
  switch (event) {
1786
    case EVENT_COMMIT: {
1787
      int hours, minutes, seconds;
1788
      int month, day, year;
1789
      int   id=-1;
1790
      //int   bitmap = 0;
1791
      if (panel == p1h) {
1792
        switch (control) {
1793
          case P1_PRINT:
1794
            id= P1_GRAPH;
1795
            sprintf(name,"G");
1796
            break;
1797
          case P1_PRINT2D:
1798
            id= P1_GRAPH2D;
1799
            sprintf(name,"2D");
1800
            break;
1801
          case P1_PRINTX:
1802
            id= P1_GRAPHX;
1803
            sprintf(name,"X");
1804
            break;
1805
          case P1_PRINTY:
1806
            id= P1_GRAPHY;
1807
            sprintf(name,"Y");
1808
            break;
1809
        }
1810
        h2=0;
1811
      } else {
1812
        switch (control) {
1813
          case P2_PRINTXY:
1814
            id= P2_GRAPH_1;
1815
            sprintf(name,"XY");
1816
            break;
1817
        }
1818
        h2=1;
1819
      }
1820
      GetSystemDate (&month,&day ,&year );
1821
      GetSystemTime(&hours, &minutes, &seconds);
1822
      if (id>=0) {
1823
        if( ( (panel == p1h)&&(control ==  P1_PRINT2D) ) || ((panel == p2h)&&(control ==  P2_GRAPH_1))) {
1824
          sprintf(dfile ,"data/%d_%d_%d_%d_%d_%s.th2d",year,month,day,hours,minutes, name );
1825
          H2DWrite(h2,dfile,"wb");
1826
          sa02Printf("sizeof H2D %d \n",sizeof(H2D));
1827
          sa02Printf("H2D image saved as %s\n", dfile);
1828
          sprintf(name ,"C:\\root\\bin\\root.exe ..\\macros\\H2Dload.cxx(\\\"%s\\\")", dfile);
1829
          LaunchExecutable(name);
1830
        } else {
1831
          sprintf(dfile ,"data/%d_%d_%d_%d_%d_%s.bmp",year,month,day,hours,minutes, name );
1832
          SaveCtrlDisplayToFile (panel,id, 0, -1, -1, dfile);
1833
          sa02Printf("bmp image saved as %s\n", dfile);
1834
        }
1835
      }
1836
      //PrintCtrl (p1h, P1_GRAPH2D, "sa02_CVI", 1, 1);
1837
    }
1838
    break;
1839
  }
1840
  return 0;
1841
}
1842
 
1843
int CVICALLBACK CursorCB (int panel, int control, int event,
1844
                          void *callbackData, int eventData1, int eventData2) {
1845
  double x=0,y=0;
1846
  int ix=0,iy=0;
1847
  int h2=(int) callbackData;
1848
 
1849
  switch (event) {
1850
    case EVENT_COMMIT:
1851
      GetGraphCursor (p1h, P1_GRAPH2D, 1, &x, &y);
1852
      if(H2DGetStepX(h2)>0) {
1853
        ix=(int)((x-H2DGetMinX(h2))/H2DGetStepX(h2));
1854
      }
1855
      if(H2DGetStepY(h2)>0) {
1856
        iy=(int)((y-H2DGetMinY(h2))/H2DGetStepY(h2));
1857
      }
1858
      SetCtrlVal(panel,P1_NSLIX,ix);
1859
      SetCtrlVal(panel,P1_NSLIY,iy);
1860
      sa02Printf("Cursor %f %f h2=%d val=%f min=%f max=%f\n",
1861
                 x,y,h2,H2DGetBinContent(h2,ix,iy),H2DGetMin(h2),
1862
                 H2DGetMax(h2) );
1863
      break;
1864
  }
1865
  return 0;
1866
}
1867
 
1868
 
1869
int CVICALLBACK HistoInfoCB (int panel, int control, int event,
1870
                             void *callbackData, int eventData1, int eventData2) {
1871
  double x=0,y=0;
1872
  int ix=0,iy=0;
1873
  int h2=(int) callbackData;
1874
  int b=0;
1875
  switch (event) {
1876
    case EVENT_COMMIT:
1877
 
1878
      GetGraphCursor (panel, control, 1, &x, &y);
1879
      if (panel == p2h ) {
1880
        for (b=0; b<4; b++) {
1881
          if (control==p2graph[b]) break;
1882
        }
1883
        h2=100+b;
1884
        if(H2DGetStepX(h2)>0) {
1885
          ix=(int)((x-H2DGetMinX(h2))/H2DGetStepX(h2));
1886
        }
1887
        if(H2DGetStepY(h2)>0) {
1888
          iy=(int)((y-H2DGetMinY(h2))/H2DGetStepY(h2));
1889
        }
1890
 
1891
        sa02Printf("Cursor %f %f h2=%d val=%f min=%f max=%f\n",
1892
                   x,y,h2,H2DGetBinContent(h2,ix,iy),H2DGetMin(h2),
1893
                   H2DGetMax(h2) );
1894
      }
1895
      break;
1896
  }
1897
  return 0;
1898
}
1899
 
1900
 
1901
int GetElectronicChannel(int x, int y, int *chip, int *ch) {
1902
  int i=0;
1903
  for (i=0; i<144; i++) {
1904
    if (eid2hapdxy[i].chx == x && eid2hapdxy[i].chy == y) {
1905
      *chip = eid2hapdxy[i].chip;
1906
      *ch   = eid2hapdxy[i].ch  ;
1907
      return 0;
1908
    }
1909
  }
1910
  return -1;
1911
}
1912
 
1913
int SetCMon(int chx,int chy) {
1914
  int chip,ch,asic;
1915
  uint32_t response[2]= {0,0};
1916
  uint32_t board;
1917
  uint16_t mask=GetConnectedFebMask();
1918
 
1919
//  GetCtrlVal(p1h,P1_BOARDNUMBER, &board);
1920
  GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
1921
  GetElectronicChannel(chx,chy,&chip,&ch);
1922
  asic = sa02MuxMap(chip);
1923
  sa02Printf("CHX %d CHY %d ",chx, chy);
1924
  sa02Printf("MUX %d ",asic);
1925
  sa02Printf("CMON ASIC: %d  ch: %d\n",chip, ch);
1926
  for (board=0; board<4; board++) {
1927
    if (mask & (1<<board)) {
1928
      sa02Cmd(board,FEB_MUX , asic, 0, 0 ,2,response);
1929
      sa02Cmd(board,SA0x_ASIC0_CMON,0,chip,ch,2,response);
1930
    }
1931
  }
1932
 
1933
  return 0;
1934
}
1935
 
1936
int CVICALLBACK HDraw2DCB (int panel, int control, int event,
1937
                           void *callbackData, int eventData1, int eventData2) {
1938
  int ch=0;
1939
  int ctrlID=0;
1940
  int *plot=0;
1941
  int graph=0;
1942
  int board=0;
1943
  switch (event) {
1944
 
1945
    case EVENT_COMMIT:
1946
      for (board=0; board<4; board++) {
1947
//        if (panel == p1h){ rID = P1_CH; graph = P1_GRAPH; plot =&p1plothandle;}
1948
        if (panel == p2h) {
1949
          ctrlID = P2_CH;
1950
          graph = p2graph[board];
1951
          plot =&p2plothandle[board];
1952
        }
1953
//        if (panel == p3h){ rID = P3_CH; graph = P3_GRAPH; plot =&p3plothandle;}
1954
//        if (panel == p4h){ rID = P4_CH; graph = P4_GRAPH; plot =&p4plothandle;}
1955
 
1956
 
1957
        GetCtrlVal(panel,ctrlID, &ch);
1958
        if (ch) {
1959
          H3DDrawSliceXY(100+board,ch-1,panel,graph, plot);
1960
        } else {
1961
          H2DDraw(100+board,panel,graph, plot);
1962
        }
1963
      }
1964
      break;
1965
  }
1966
  return 0;
1967
}
1968
 
1969
int GetHvMonitor( void ) {
1970
  int N470mid   = 4;
1971
  int SYS403mid = 2;
1972
  unsigned short buf[256]= {0};
1973
  int retval;
1974
  int ii;
1975
//                 G0,A0,B0,C0,D0,H0,G1,A1,B1,C1,D1,H1,G2,A2,B2,C2,D2,H2,G3,A3,B3,C3,D3,H3
1976
  int channels[]= {24, 0, 1, 2, 3, 0,25, 4, 5, 6, 7, 1,26, 8, 9,10,11, 2,27,12,13,14,15, 3}; //channel for  SYS403 , then for  N470
1977
//  int channels[]= {0,1,2,3,4,0,5,6,7,8,9,1,10,11,12,13,14,2,15,16,17,18,19,3}; //channel for  SYS403 , then for  N470
1978
 
1979
  for (ii=0; ii<256; ii++) buf[ii]=0;
1980
  monrec.time = (uint32_t) time(NULL);
1981
  for (ii=0; ii<=23; ii++) {
1982
    if ((ii+1)%6==0 && ii!=0) {
1983
      buf[0]=(unsigned short) (channels[ii]<<8) | ReadOperationalParam;
1984
      if (gCAEN_V288) {
1985
        V288_Send(0,N470mid,1,buf);
1986
        retval=V288_Receive(0,255, buf);
1987
      }
1988
      monrec.status[ii] = buf[0];   //status
1989
      monrec.vmon[ii] = buf[1]*1000;//zapisano v mV
1990
      monrec.imon[ii] = buf[2]*1000;//zapisano v nA
1991
      monrec.vset[ii] = buf[3]*1000;//zapisano v mV
1992
      monrec.iset[ii] = buf[4]*1000;//zapisano v nA
1993
    } else {
1994
      buf[0]=(unsigned short) (channels[ii]<<8) | ReadStatus;
1995
      if (gCAEN_V288) {
1996
        V288_Send(0,SYS403mid,1,buf);
1997
        retval=V288_Receive(0,255,buf);
1998
      }
1999
      monrec.vmon[ii] = buf[1]*10;//zapisano v mV
2000
      monrec.imon[ii] = buf[2]*10;//zapisano v nA
2001
      monrec.status[ii] = buf[3]; //status
2002
 
2003
      if (!hvmonFirst) {
2004
        buf[0]=(unsigned short) (channels[ii]<<8) | ReadParameters;
2005
        if (gCAEN_V288) {
2006
          V288_Send(0,SYS403mid,1,buf);
2007
          retval=V288_Receive(0,255,buf);
2008
        }
2009
        vset[ii] = monrec.vset[ii] = buf[7]*10;//zapisano v mV
2010
        iset[ii] = monrec.iset[ii] = buf[10]*10;//zapisano v nA
2011
      }
2012
      monrec.vset[ii] = vset[ii];//zapisano v mV
2013
      monrec.iset[ii] = iset[ii];//zapisano v nA
2014
    }
2015
    //sa02Printf("%04x \t %d \t %d \t %d \t %d *\n",monrec.status[ii],monrec.vmon[ii],monrec.vset[ii],monrec.imon[ii],monrec.iset[ii]);
2016
  }
2017
  hvmonFirst=1;
2018
  return 0;
2019
}
2020
 
2021
int CVICALLBACK daq_scan(void *functionData) {
2022
  int ich,count=0, xyval[4]= {0,0,0,0};
2023
  //int c[4]= {0,0,0,0};
2024
  //int e[4]= {0,0,0,0};
2025
  uint32_t daqmode=1;
2026
  uint32_t trglen;
2027
  int nb,dsave,fcount=0,fmax=0,status,ch;
2028
  unsigned int i;
2029
  int hxy=100;
2030
  //int h2=0;
2031
  time_t t,told, tstart, t0;
2032
 
2033
  uint32_t board;
2034
  uint32_t tpenb   =0;
2035
  uint32_t response[2]= {0,0};
2036
  char title[0xFF];
2037
  char dfile[MAX_PATHNAME_LEN],dfile0[MAX_PATHNAME_LEN];
2038
#define MAXSIZE 10000
2039
  int maxsize = MAXSIZE;
2040
  uint32_t sendswtrg=0;
2041
  int ncount=0;
2042
  uint32_t *rdata;
2043
  float dx,dy,gapx,gapy,addgap;
2044
  int ix,iy,nx,ny;
2045
  int scanunitsx=0,scanunitsy=0;
2046
  int x0,y0;
2047
  const float fx= (float)(1000 / 0.3595); // 4M scaling factor steps/mm
2048
  int daqexe;
2049
  int writeevents=0;
2050
  double fraction=0;
2051
  uint32_t *data;
2052
  char serial[4][0xFF];
2053
  char hname[0xFF];
2054
  time_t cas;
2055
 
2056
  uint16_t mask=GetConnectedFebMask();
2057
  runrec.id = RUNREC_ID;
2058
  runrec.len = sizeof(runrec);
2059
  endrec.id = ENDREC_ID;
2060
  endrec.len = sizeof(endrec);
2061
  posrec.id = POSREC_ID;
2062
  posrec.len = sizeof(posrec);
2063
  evtrec.id = EVTREC_ID;
2064
  evtrec.len = sizeof(evtrec);
2065
  datrec.id = DATREC_ID;
2066
  datrec.len = sizeof(datrec);
2067
  monrec.id = MONREC_ID;
2068
  monrec.len = sizeof(monrec);
2069
 
2070
  SetCtrlAttribute (p2h, P2_DAQ, ATTR_DIMMED, 1);
2071
  ctrl_c=0;
2072
 
2073
  GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
2074
 
2075
  GetCtrlVal (p1h, P1_SERIAL_1, serial[0]);
2076
  GetCtrlVal (p1h, P1_SERIAL_2, serial[1]);
2077
  GetCtrlVal (p1h, P1_SERIAL_3, serial[2]);
2078
  GetCtrlVal (p1h, P1_SERIAL_4, serial[3]);
2079
 
2080
  sprintf(runrec.serial,"HAPD=%s,%s,%s,%s", serial[0],serial[1],serial[2],serial[3]);
2081
 
2082
  GetCtrlVal (p2h, P2_NEVE, &runrec.nev);
2083
  GetCtrlVal (p2h, P2_PEDESTAL, &runrec.ped);
2084
  GetCtrlVal (p2h, P2_NX, &runrec.nx);
2085
  GetCtrlVal (p2h, P2_XSTEP, &runrec.dx);
2086
  GetCtrlVal (p2h, P2_XMIN, &runrec.x0);
2087
  GetCtrlVal (p2h, P2_NY, &runrec.ny);
2088
  GetCtrlVal (p2h, P2_YSTEP, &runrec.dy);
2089
  GetCtrlVal (p2h, P2_YMIN, &runrec.y0);
2090
  GetCtrlVal ( p1h, P2_TPENB,&tpenb);
2091
  GetCtrlVal ( p2h,P2_DAQEXE,&daqexe);
2092
  GetCtrlVal(p2h,P2_FRACTION, &fraction);
2093
  GetCtrlVal (p2h, P2_SCANUNITSX,  &scanunitsx);
2094
  GetCtrlVal (p2h, P2_SCANUNITSY,  &scanunitsy);
2095
  GetCtrlVal (p2h, P2_GAPX,  &gapx);
2096
  GetCtrlVal (p2h, P2_GAPX,  &gapy);
2097
  GetCtrlVal (p2h, P2_DX, &dx);
2098
  GetCtrlVal (p2h, P2_DX, &dy);
2099
 
2100
  GetCtrlVal (p2h, P2_XC,  &x0);
2101
  GetCtrlVal (p2h, P2_YC,  &y0);
2102
 
2103
  GetCtrlVal (p2h, P2_DIRECTION,  &runrec.direction);
2104
 
2105
 
2106
  SetCtrlAttribute(p1h,P1_TRGHVMON,ATTR_ENABLED,1);
2107
  hvmonFirst = 0;
2108
 
2109
 
2110
  GetCtrlVal(p1h,P1_SENDSWTRIG,&sendswtrg);
2111
  GetCtrlVal(p1h,P1_INTTRGLEN, &trglen);
2112
  GetCtrlVal(p1h,P1_DAQMODE, &daqmode);
2113
 
2114
 
2115
 
2116
 
2117
  runrec.fver = scanunitsx + scanunitsy*2 ;
2118
  if (scanunitsx) {
2119
    x0 = (int)(x0 - 5.5 * fx * dx  - gapx * fx * 0.5);
2120
  }
2121
  if (scanunitsy) {
2122
    y0 = (int)(y0 - 5.5 * fx * dy  - gapy * fx * 0.5);
2123
  }
2124
 
2125
  GetCtrlVal(p2h, P2_DSAVE, &dsave);
2126
  if (dsave) {
2127
    GetCtrlVal (p2h, P2_DFILE, dfile0);
2128
    fcount=1;
2129
    GetCtrlVal (p2h, P2_NEWF, &fmax);
2130
    fmax*=1000000;//fmax in Mega Bytes
2131
  }
2132
  time (&t0);
2133
  sa02Printf("---->daq_scan\n");
2134
 
2135
  if (dsave) {
2136
    sprintf(dfile,"%s_file%02d.dat",dfile0,fcount);
2137
    //gFp = fopen (dfile, "ab");
2138
    gFp = fopen (dfile, "ab");
2139
    if (gFp==NULL) sa02Printf("----> !!! gFp==NULL !!!\n");
2140
    if (ferror (gFp)) sa02Printf("----> !!! ferror (gFp) after fopen !!!\n");    
2141
    //time ((time_t *) &runrec.time);
2142
    time (&cas);
2143
    runrec.time = (uint32_t) cas;
2144
    status = (int) fwrite (&runrec, 1, runrec.len, gFp);
2145
    if(status != runrec.len) sa02Printf("----> !!! status != runrec.len (= %d) !!!\n", status);    
2146
    if (ferror (gFp)) sa02Printf("----> !!! ferror (gFp) = %d !!!\n", ferror (gFp));  
2147
 
2148
  }
2149
 
2150
 
2151
  for (i=0; i<4; i++) {
2152
    sprintf(title,"HAPD%d Surface Scan single channels", i);
2153
    sprintf(hname,"hxy%d", i);
2154
    H3DInit(hxy+i,hname,title, runrec.nx,runrec.x0, runrec.dx,runrec.ny,runrec.y0, runrec.dy, 144, -0.5, 1);
2155
    H3DSetTitleZ(hxy+i,"channel");
2156
    sprintf(hname,"hxy%d_sum", i);
2157
    H2DInit(hxy+i,hname,runrec.serial, runrec.nx,runrec.x0, runrec.dx,runrec.ny,runrec.y0, runrec.dy);
2158
    if (scanunitsx) {
2159
      H2DSetTitleX(hxy+i,"x (channels)");
2160
      H3DSetTitleX(hxy+i,"x (channels)");
2161
    } else {
2162
      H2DSetTitleX(hxy+i,"x (stage steps)");
2163
      H3DSetTitleX(hxy+i,"x (stage steps)");
2164
    }
2165
    if (scanunitsy) {
2166
      H2DSetTitleY(hxy+i,"y (channels)");
2167
      H3DSetTitleY(hxy+i,"y (channels)");
2168
    } else {
2169
      H2DSetTitleY(hxy+i,"y (stage steps)");
2170
      H3DSetTitleY(hxy+i,"y (stage steps)");
2171
    }
2172
 
2173
  }
2174
  if (runrec.direction) {
2175
    ny = runrec.ny;
2176
    nx = runrec.nx;
2177
  } else {
2178
    ny = runrec.nx;
2179
    nx = runrec.ny;
2180
  }
2181
  rdata = malloc(sizeof(uint32_t)*maxsize);
2182
 
2183
  time(&t);
2184
  tstart=t;
2185
  told=t-1;
2186
 
2187
  for (iy=0; iy<ny; iy++) {
2188
 
2189
    if (ctrl_c) break;
2190
 
2191
    if (runrec.direction) {
2192
      posrec.iy = iy;
2193
      posrec.yset=runrec.y0+posrec.iy*runrec.dy;
2194
      if (scanunitsy) {
2195
        if (posrec.yset>5) {
2196
          addgap=gapy * fx;
2197
        } else {
2198
          addgap=0;
2199
        }
2200
        posrec.yset = (int32_t)(y0+dy *fx * posrec.yset + addgap);
2201
      }
2202
      if (gMIKRO_Y) {
2203
        //sa02Printf("MIKRO_MoveTo (2, y);%d\n",y);
2204
        MIKRO_MoveTo (MIKRO_Y, posrec.yset);
2205
        sa02Printf("->MIKRO_MoveTo (2, y);%d\n",posrec.yset);
2206
      }
2207
 
2208
      SetCtrlVal (p2h, P2_Y, posrec.yset);
2209
      SetCtrlVal (p2h, P2_IY, posrec.iy);
2210
    } else {
2211
      posrec.ix = iy;
2212
      posrec.xset=runrec.x0+posrec.ix*runrec.dx;
2213
      if (scanunitsx) {
2214
        if (posrec.xset>5) {
2215
          addgap=gapx * fx;
2216
        } else {
2217
          addgap=0;
2218
        }
2219
        posrec.xset =  (int32_t)(x0+dx *fx * posrec.xset + addgap);
2220
      }
2221
      if (gMIKRO_Y) {
2222
        //sa02Printf("MIKRO_MoveTo (2, y);%d\n",y);
2223
        MIKRO_MoveTo (MIKRO_X, posrec.xset);
2224
        sa02Printf("->MIKRO_MoveTo (1, x);%d\n",posrec.xset);
2225
      }
2226
      SetCtrlVal (p2h, P2_X, posrec.xset);
2227
      SetCtrlVal (p2h, P2_IX, posrec.ix);
2228
    }
2229
    for (ix=0; ix<nx; ix++) {
2230
      if (ctrl_c) break;
2231
 
2232
      if (runrec.direction) {
2233
        posrec.ix = ix;
2234
        posrec.xset=runrec.x0+posrec.ix*runrec.dx;
2235
        if (scanunitsx) {
2236
          if (posrec.xset>5) {
2237
            addgap=gapx * fx;
2238
          } else {
2239
            addgap=0;
2240
          }
2241
          posrec.xset =  (int32_t)(x0+dx *fx * posrec.xset + addgap);
2242
        }
2243
        if (gMIKRO_X) {
2244
          //sa02Printf("MIKRO_MoveTo (1, x);%d\n",posrec.x);
2245
          MIKRO_MoveTo (MIKRO_X, posrec.xset);
2246
          sa02Printf("->MIKRO_MoveTo (1, x);%d\n",posrec.xset);
2247
        }
2248
        SetCtrlVal (p2h, P2_X, posrec.xset);
2249
        SetCtrlVal (p2h, P2_IX, posrec.ix);
2250
      } else {
2251
        posrec.iy = ix;
2252
        posrec.yset=runrec.y0+posrec.iy*runrec.dy;
2253
        if (scanunitsy) {
2254
          if (posrec.yset>5) {
2255
            addgap=gapy * fx;
2256
          } else {
2257
            addgap=0;
2258
          }
2259
          posrec.yset =  (int32_t)(y0+dy *fx * posrec.yset + addgap);
2260
        }
2261
        if (gMIKRO_X) {
2262
          //sa02Printf("MIKRO_MoveTo (1, x);%d\n",posrec.y);
2263
          MIKRO_MoveTo (MIKRO_Y, posrec.yset);
2264
          sa02Printf("->MIKRO_MoveTo (2, y);%d\n",posrec.yset);
2265
        }
2266
        SetCtrlVal (p2h, P2_Y, posrec.yset);
2267
        SetCtrlVal (p2h, P2_IY, posrec.iy);
2268
      }
2269
      if (scanunitsx && scanunitsy) {
2270
        SetCMon(runrec.x0+posrec.ix*runrec.dx,runrec.y0+posrec.iy*runrec.dy);
2271
      }
2272
      if (dsave) {
2273
        if (fmax && (ftell(gFp) > fmax)) {
2274
          fcount+=1;
2275
          sprintf(dfile,"%s_file%02d.dat",dfile0,fcount);
2276
          fclose(gFp);
2277
          gFp = fopen (dfile, "ab");
2278
        }
2279
        time (&cas);
2280
        posrec.time = (uint32_t) cas;
2281
        status = (int) fwrite (&posrec, 1, posrec.len, gFp);
2282
      }
2283
 
2284
      Sa02DaqMode (daqmode);
2285
      Sa02SelectTriggerWithMaskAndLength (sendswtrg, mask, trglen);
2286
 
2287
      for (board=0; board<4; board++) {
2288
        if (mask & (1<<board)) {
2289
          sa02Cmd( board, FEB_VTH1, runrec.ped, 0,0,1,response);
2290
          Sa02TestPulseEnable(board,tpenb); // Enable/disable test pulse
2291
        }
2292
      }
2293
 
2294
      Sa02SetNeve(runrec.nev);
2295
 
2296
      evtrec.nev=1;
2297
 
2298
 
2299
      sa02Reset();
2300
 
2301
      if (ctrl_c) break;
2302
 
2303
      if ( (count+2+dsize)  >= maxsize) {
2304
        maxsize*=2;
2305
        sa02Printf("Increasing data buffer to %d elements\n", maxsize);
2306
        rdata=realloc(rdata ,sizeof(uint32_t)*maxsize);
2307
      }
2308
 
2309
      data = &rdata[count+2];
2310
      do {
2311
        //int k;
2312
        //uint32_t inputtriggers;
2313
        if (sendswtrg == 1) Sa02SoftwareTrigger();
2314
        nb  = sa02Read(mask, &rdata[count+2] );
2315
        /*
2316
        for (k=0; k<4; k++)  c[k] = Sa02GetCounter ( k ,&e[k]);
2317
        for (k=0; k<4; k++)  sa02Printf(" CNTR%d=%d (ERR=%d)\t",k,c[k],e[k]);
2318
        sa02Printf("\nsa02Read bytes =  %d mask=%d neve=%d (%d # %d)\n", nb, mask, runrec.nev, Sa02GetNeve( &inputtriggers ) , inputtriggers);
2319
        */
2320
      } while  ( nb==0 && !ctrl_c);
2321
 
2322
 
2323
 
2324
      if (sa02TimerOut || nb==0) sa02Printf("sa02TimerOut || nb==0\n");
2325
 
2326
      for (ich=0; ich<144*4; ich++) {
2327
        int brd = ich/144;
2328
        int xch   = 143 - ich%144;
2329
        //sa02Printf("[%d] = %d \n", ich, data[ich]);
2330
        if (data[ich]> xyval[brd])   xyval[brd] = data[ich];
2331
        if (mask & (1<<brd)) {
2332
          H3DFillBin(hxy+ brd, posrec.ix,posrec.iy,xch,data[ich]);
2333
          H2DFillBin(hxy+ brd, posrec.ix,posrec.iy,data[ich]);
2334
        }
2335
      }
2336
      sa02Printf("max couts = %d %d %d %d\n", xyval[0],xyval[1],xyval[2],xyval[3]);
2337
      if (nb>=0) {
2338
        count+=module_header(0x3,&rdata[count],nb/sizeof(uint32_t));
2339
      }
2340
 
2341
 
2342
      /*
2343
      for (ich=0; ich<144; ich++) {
2344
 
2345
      //          uint32_t mask=0xFF;
2346
      //          id=(35-ich/4);
2347
      //          shft=(ich%4)*8;
2348
        uint32_t mask=0xF;
2349
            id=(17-ich/8)+board*18;
2350
        shft=(ich%8)*4;
2351
        if ( data[id]  & (mask <<shft)  )  {
2352
          H3DFillBin(hxy, posrec.ix,posrec.iy,ich,1);
2353
          H2DFillBin(hxy, posrec.ix,posrec.iy,1);
2354
        }
2355
      }
2356
      */
2357
      if (dsave) {
2358
        if (Random(0,1)<fraction) {
2359
          writeevents=1;
2360
        } else {
2361
          writeevents=0;
2362
        }
2363
        if (writeevents) {
2364
          evtrec.id = EVTREC_ID;
2365
          evtrec.len=count*sizeof(uint32_t)+ sizeof(evtrec);
2366
 
2367
          evtrec.time= (uint32_t) time(NULL);
2368
          evtrec.nev=i;
2369
          status = (int) fwrite( &evtrec,  1,  sizeof(evtrec),gFp);
2370
          if (count) {
2371
            status = (int) fwrite(rdata,1,count*sizeof(uint32_t),gFp);  //gzip
2372
          }
2373
        }
2374
        if (hvmon) {
2375
          time_t thv0,thv1;
2376
          time(&thv0);
2377
          GetHvMonitor();
2378
          time(&thv1);
2379
          status = (int) fwrite( &monrec,  1,  sizeof(monrec),gFp);
2380
          sa02Printf("HvMonitor dt= %d s\n", thv1-thv0 );
2381
          hvmon =0;
2382
        }
2383
 
2384
        ncount++;
2385
      }
2386
 
2387
      time(&t);
2388
      if (t!=told ) {
2389
        double done= (double) (posrec.ix+posrec.iy*runrec.nx)/(runrec.nx*runrec.ny);
2390
        EstimatedFinish(p2h, P2_PROGRESS, P2_ETA, t0, done);
2391
        GetCtrlVal(p2h,P2_CH, &ch);
2392
        for (board=0; board<4; board++) {
2393
          if (ch) {
2394
            H3DDrawSliceXY(hxy+board,ch,p2h, p2graph[board], &p2plothandle[board]);
2395
          } else {
2396
            H2DDraw(hxy+board,p2h, p2graph[board], &p2plothandle[board]);
2397
          }
2398
        }
2399
        ProcessSystemEvents ();
2400
        SetCtrlVal(p2h,P2_CEVE, i);
2401
        sa02Printf("%d events in %2.2f min (%d s) %s",ncount, (double)(t-tstart)/60.,t-tstart, ctime(&t));
2402
 
2403
      }
2404
      told=t;
2405
 
2406
 
2407
 
2408
      if (ctrl_c) break;
2409
 
2410
      if (daqexe &0x1) {
2411
        daq(NULL);
2412
        sa02Cmd( board, FEB_VTH1, runrec.ped, 0,0,1,response);
2413
      }
2414
      if (daqexe &0x2) {
2415
        V729_SetFilePointer(gFp);
2416
        V729_daq(NULL);
2417
      }
2418
 
2419
    }
2420
  }
2421
 
2422
  if (gFp) {
2423
    int ii=0, ison=0;
2424
    for (ii=0; ii<4; ii++) {
2425
      GetCtrlVal(p1h,hapd_onoff[ii], &ison);
2426
      if (ison ) {
2427
        H3DWrite2File(hxy+ii, gFp);
2428
        H2DWrite2File(hxy+ii, gFp);
2429
      }
2430
    }
2431
    fclose(gFp);
2432
  }
2433
  gFp=NULL;
2434
  free(rdata);
2435
 
2436
  SetCtrlAttribute(p1h,P1_TRGHVMON,ATTR_ENABLED,0);
2437
 
2438
  return 0;
2439
}
2440
 
2441
int CVICALLBACK Testing(void *functionData) {
2442
  int i;
2443
  int N470mid   = 4;
2444
  int SYS403mid = 2;
2445
  unsigned short buf[256]= {0};
2446
  int odg;
2447
  int channels[]= {0,1,2,3,4,0,5,6,7,8,9,1,10,11,12,13,14,2,15,16,17,18,19,3}; //channel for  SYS403 , then for  N470
2448
  time_t t0,t1;
2449
  time(&t0);
2450
 
2451
  hvmonFirst=0;
2452
 
2453
  for (i=0; i<256; i++) buf[i]=0;
2454
  for (i=0; i<=23; i++) {
2455
    if (((i+1)%6)==0&&i!=0) {
2456
      buf[0]=(unsigned short) (channels[i]<<8) | ReadOperationalParam;
2457
      if (gCAEN_V288) {
2458
        V288_Send(0,N470mid,1,buf);
2459
        odg=V288_Receive(0,255,buf);
2460
      }
2461
      monrec.status[i] = buf[0];   //status
2462
      monrec.vmon[i] = buf[1]*1000;//zapisano v mV
2463
      monrec.imon[i] = buf[2]*1000;//zapisano v nA
2464
      monrec.vset[i] = buf[3]*1000;//zapisano v mV
2465
      monrec.iset[i] = buf[4]*1000;//zapisano v nA
2466
    } else {
2467
      buf[0]=(unsigned short) (channels[i]<<8) | ReadStatus;
2468
      if (gCAEN_V288) {
2469
        V288_Send(0,SYS403mid,1,buf);
2470
        odg=V288_Receive(0,255,buf);
2471
      }
2472
      monrec.vmon[i] = buf[1]*10;//zapisano v mV
2473
      monrec.imon[i] = buf[2]*10;//zapisano v nA
2474
      monrec.status[i] = buf[3]; //status
2475
      if(!hvmonFirst) {
2476
        buf[0]=(unsigned short) (channels[i]<<8) | ReadParameters;
2477
        if (gCAEN_V288) {
2478
          V288_Send(0,SYS403mid,1,buf);
2479
          odg=V288_Receive(0,255,buf);
2480
        }
2481
        vset[i] = monrec.vset[i] = buf[7]*10;//zapisano v mV
2482
        iset[i] = monrec.iset[i] = buf[10]*10;//zapisano v nA
2483
      }
2484
      monrec.vset[i] = vset[i];//zapisano v mV
2485
      monrec.iset[i] = iset[i];//zapisano v nA
2486
    }
2487
    sa02Printf("%04x \t %.02f V \t %d V \t\t %.02f muA \t %d muA *\n",monrec.status[i],(float)monrec.vmon[i]/1000,monrec.vset[i]/1000,(float)monrec.imon[i]/1000,monrec.iset[i]/1000);
2488
  }
2489
  time (&t1);
2490
  sa02Printf("Cas izvedbe:%g s.\n",difftime(t1,t0));
2491
 
2492
  return 0;
2493
}
2494
 
2495
int CVICALLBACK set_dac(int OnOff) {
2496
  int val;
2497
  char name[MAX_PATHNAME_LEN];
2498
  if (OnOff) {
2499
    GetCtrlVal (p5h, P5_DAC_ON, &val);
2500
    sprintf(name ,"%s -p %d",palaser, val);
2501
    sa02Printf("%s\n", name);
2502
    system(name);
2503
    GetCtrlVal (p5h, P5_FREQUENCY_ON, &val);
2504
    sprintf(name ,"%s -f %d",palaser, val);
2505
    sa02Printf("%s\n", name);
2506
    system(name);
2507
  } else {
2508
    GetCtrlVal (p5h, P5_DAC_OFF, &val);
2509
    sprintf(name ,"%s -p %d",palaser, val);
2510
    sa02Printf("%s\n", name);
2511
    system(name);
2512
    GetCtrlVal (p5h, P5_FREQUENCY_OFF, &val);
2513
    sprintf(name ,"%s -f %d",palaser, val);
2514
    sa02Printf("%s\n", name);
2515
    system(name);
2516
  }
2517
  return 0;
2518
}
2519
 
2520
int CVICALLBACK set_hv(int OnOff) {
2521
  int N470mid = 4;
2522
  int channel = 0;
2523
  int ret;
2524
 
2525
  unsigned short buf[256];
2526
 
2527
  buf[0]=(unsigned short) (channel<<8) | TurnChanelOff;
2528
  if (OnOff) buf[0]=(unsigned short) (channel<<8) | TurnChanelOn;
2529
  V288_Send(0,N470mid,1,buf);
2530
  ret=V288_Receive(0,255,buf);
2531
 
2532
  buf[0]=(unsigned short) (channel<<8) | ReadOperationalParam;
2533
  V288_Send(0,N470mid,1,buf);
2534
  ret=V288_Receive(0,255,buf);
2535
 
2536
  while (((buf[0]&0x20)&&(buf[0]&0x1))||(buf[0]&0x40)) {
2537
    if((buf[0]&0x20)&&(buf[0]&0x20)) sa02Printf("Channel is ramping up \t Vmon: %d V \t Vset: %d \t status: 0x%x\n",buf[1],buf[3],buf[0]);
2538
    else if(buf[0]&0x40) sa02Printf("Channel is ramping down \t Vmon: %d V \t Vset: %d \t status: 0x%x\n",buf[1],buf[3],buf[0]);
2539
    else if(buf[0]&0x1E) {
2540
      sa02Printf("status: 0x%x\n",buf[0]);
2541
      return -1;
2542
    } else  sa02Printf("status: 0x%x\n",buf[0]);
2543
    Delay(2);
2544
    buf[0]=(unsigned short) (channel<<8) | ReadOperationalParam;
2545
    V288_Send(0,N470mid,1,buf);
2546
    ret=V288_Receive(0,255,buf);
2547
  }
2548
 
2549
  buf[0]=(unsigned short) (channel<<8) | ReadOperationalParam;
2550
  V288_Send(0,N470mid,1,buf);
2551
  ret=V288_Receive(0,255,buf);
2552
  if(buf[0]&0x1) sa02Printf("HV is ON \t status: 0x%x\n",buf[0]);
2553
  else sa02Printf("HV is OFF \t status: 0x%x\n",buf[0]);
2554
 
2555
  return 0;
2556
}
2557
 
2558
int CVICALLBACK changeGlobalParam(int paramID, int paramValue) {
2559
  int state;
2560
  int cid = P3_GREG;
2561
  int scanpar = paramID; //ID of the parameter you are about to change
2562
  int nch = 4; //4 ASIC chips
2563
  int spar = scanpar-10;
2564
  Rect save_range,trange;
2565
  const int maxrange[20]= {0,0,8,16,16,16,2,2,2,0,4,4,4,2,256,4,512};
2566
 
2567
  trange.top=0;
2568
  trange.left=0;
2569
 
2570
  state = GetTableSelection (p3h, cid, &save_range);
2571
  trange = MakeRect (1, spar, nch, 1);
2572
  state = SetTableSelection (p3h, cid, trange);
2573
  if ((trange.top!=0)&&(trange.left!=0)) {
2574
    if (scanpar!=1) {
2575
      state = FillTableCellRange (p3h, cid, MakeRect (1, spar, nch, 1), paramValue%maxrange[scanpar-1]);
2576
      if (maxrange[scanpar-1] && paramValue/maxrange[scanpar-1]) {
2577
        state = FillTableCellRange (p3h, cid, MakeRect (1, spar-1, nch, 1), paramValue/maxrange[scanpar-1]);
2578
      }
2579
    }
2580
    UploadGlobalParameters (p3h,cid,EVENT_COMMIT,NULL,0,0);
2581
  }
2582
  state = SetTableSelection (p3h, cid, save_range);
2583
 
2584
  return 0;
2585
}
2586
 
2587
int CreateParamFile(char *filename) {
2588
  int n,i,row,asic,ch;
2589
  unsigned short val;
2590
  time_t t;
2591
  char buf[MAX_PATHNAME_LEN];
2592
  FILE   *fp;
2593
 
2594
  sprintf(buf,"..//parameters//%s",filename);
2595
  fp = fopen(buf, "w");
2596
  if (fp) {
2597
    //--------------------------------------------------- Parameters header
2598
    time(&t);
2599
    fprintf(fp, "#Parameter exported from CVI %s\n",ctime(&t) );
2600
    //--------------------------------------------------- FPGA parameters
2601
    GetNumTextBoxLines(p3h, P3_FPGAPAR,&n);
2602
    for (i=0; i<n; i++) {
2603
      GetTextBoxLine(p3h, P3_FPGAPAR, i, buf);
2604
      fprintf(fp, "%s\n",buf);
2605
    }
2606
    //--------------------------------------------------- Global parameters
2607
    for (row=1; row<1+16; row++) {
2608
      int irow = (row-1)%4;
2609
      int iboard = (row-1)/4;
2610
      fprintf(fp, "param_board %d\n",iboard);
2611
      fprintf(fp, "## global parameter for chip %d\n",(row-1)%4);
2612
      fprintf(fp, "param_global %d 0x1ffff\n",irow);
2613
      GetTableCellVal (p3h, P3_GREG, MakePoint (1,row), &val);
2614
      fprintf(fp, "phasecmps %d 0x%x\n",irow,val);
2615
      GetTableCellVal (p3h, P3_GREG, MakePoint (2,row), &val);
2616
      fprintf(fp, "gain %d 0x%x\n",irow,val);
2617
      GetTableCellVal (p3h, P3_GREG, MakePoint (3,row), &val);
2618
      fprintf(fp, "shapingtime %d 0x%x\n",irow,val);
2619
      GetTableCellVal (p3h, P3_GREG, MakePoint (4,row), &val);
2620
      fprintf(fp, "comparator %d 0x%x\n",irow,val);
2621
      GetTableCellVal (p3h, P3_GREG, MakePoint (5,row), &val);
2622
      fprintf(fp, "vrdrive %d 0x%x\n",irow,val);
2623
      GetTableCellVal (p3h, P3_GREG, MakePoint (6,row), &val);
2624
      fprintf(fp, "monitor %d 0x%x\n",irow,val);
2625
      GetTableCellVal (p3h, P3_GREG, MakePoint (7,row), &val);
2626
      fprintf(fp, "id %d 0x%x\n",irow,val);
2627
 
2628
      fprintf(fp, "load_global  %d\n\n\n",irow);
2629
    }
2630
 
2631
    //--------------------------------------------------- Channel parameters
2632
    for (i=0; i<144*4; i++) {
2633
      int board = i/144;
2634
      int j= i%144;
2635
      asic=(j/36);
2636
      ch=j%36;
2637
      row=(i+1);
2638
      if (i%36==0) {
2639
        fprintf(fp, "# channel parameter for chip %d\n\n",asic);
2640
      }
2641
 
2642
      fprintf(fp, "param_board %d\n",board);
2643
      fprintf(fp, "param_ch       %d %d 0x0000\n",asic,ch);
2644
 
2645
      GetTableCellVal (p3h, P3_CREG, MakePoint (3,row), &val);
2646
      fprintf(fp, "decaytime %d %d 0x%x\n",asic,ch,val);
2647
      GetTableCellVal (p3h, P3_CREG, MakePoint (4,row), &val);
2648
      fprintf(fp, "offset %d %d 0x%x\n",asic,ch,val);
2649
      GetTableCellVal (p3h, P3_CREG, MakePoint (5,row), &val);
2650
      fprintf(fp, "fineadj_unipol %d %d 0x%x\n",asic,ch,val);
2651
      GetTableCellVal (p3h, P3_CREG, MakePoint (6,row), &val);
2652
      fprintf(fp, "fineadj_diff %d %d 0x%x\n",asic,ch,val);
2653
      GetTableCellVal (p3h, P3_CREG, MakePoint (7,row), &val);
2654
      fprintf(fp, "tpenb %d %d 0x%x\n",asic,ch,val);
2655
      GetTableCellVal (p3h, P3_CREG, MakePoint (8,row), &val);
2656
      fprintf(fp, "kill %d %d 0x%x\n",asic,ch,val);
2657
      fprintf(fp, "load_ch  %d %d\n\n\n",asic,ch);
2658
    }
2659
    fclose(fp);
2660
  }
2661
  sprintf(buf,"Created file '..//parameters//%s'\n",filename);
2662
  sa02Printf("%s",buf);
2663
  return 0;
2664
}
2665
 
2666
 
2667
int StepOne(void) {
2668
  char defaulParamFile[0xFF] = "..\\parameters\\default.param";            // path to default.param file
2669
 
2670
  char HAPDnum[0xFF];
2671
  int HAPDnumberOnOff;
2672
  int ActiveHAPDNo=0;
2673
  int HAPDid[]= {P1_SERIAL_1,P1_SERIAL_2,P1_SERIAL_3,P1_SERIAL_4};
2674
  int HAPDstatus[]= {P1_ONOFF_1,P1_ONOFF_2,P1_ONOFF_3,P1_ONOFF_4};
2675
  char HAPDnumber[4][0xFF];
2676
 
2677
  FILE *fp;
2678
  int ndim=400;
2679
  char line[ndim];
2680
  time_t t;
2681
  uint32_t mask = GetConnectedFebMask();
2682
  int current_run=1;
2683
 
2684
  char cmdCommand[ndim];
2685
 
2686
  int numberOfIterations = 1;  //change this when everything will be working...
2687
 
2688
  /****** Check if Serial numbers are filled in ******/
2689
  for (int i=0; i<4; i++) {
2690
    GetCtrlVal(p1h, HAPDid[i], HAPDnum);
2691
    GetCtrlVal(p1h, HAPDstatus[i], &HAPDnumberOnOff);
2692
    if(!strcmp(HAPDnum, "noserial") && HAPDnumberOnOff) {
2693
      printf("Fill in 'HAPD%d number' or disable 'HAPD%d'\n",i,i);
2694
      return -1;
2695
    }
2696
    strcpy(HAPDnumber[i],HAPDnum);
2697
    ActiveHAPDNo+=HAPDnumberOnOff;
2698
  }
2699
  if(!ActiveHAPDNo) {
2700
    sa02Printf("Turn on at least 1 HAPD.");
2701
    return -1;
2702
  }
2703
  sa02Printf("HAPD0 serial: %s \nHAPD1 serial: %s \nHAPD2 serial: %s \nHAPD3 serial: %s \n",HAPDnumber[0],HAPDnumber[1],HAPDnumber[2],HAPDnumber[3]);
2704
 
2705
  /****** Loads param file and uploads it to FEB ******/
2706
  SetCtrlVal(p3h, P3_INPUTFILE, defaulParamFile);               // write path to P3_INPUTFILE
2707
  SetParametersFromFile(defaulParamFile);                       // write default.param to P3_CREG table
2708
 
2709
  LoadParameters(p3h, P3_LOADPAR, EVENT_COMMIT, NULL, 0, 0);    // load parameters from defaul.param to FEB
2710
  ProcessSystemEvents ();
2711
  LoadParameters(p3h, P3_LOADPAR, EVENT_COMMIT, NULL, 0, 0);    // load parameters from defaul.param to FEB
2712
  ProcessSystemEvents ();
2713
  LoadParameters(p3h, P3_LOADPAR, EVENT_COMMIT, NULL, 0, 0);    // load parameters from defaul.param to FEB
2714
  ProcessSystemEvents ();
2715
 
2716
  /****** MicroMini calibration ******/
2717
  sa02Printf("Calibration *\n\n");
2718
  SetHome(p2h, P2_HO,EVENT_COMMIT,NULL, 0, 0);
2719
  SetCtrlVal(p2h,P2_XC,gCENTER_X);
2720
  SetCtrlVal(p2h,P2_YC,gCENTER_Y);
2721
 
2722
  /****** Reads run number ******/
2723
  fp = fopen ("CompleteScan_RunNumber.txt","r");
2724
  if (fp) {
2725
    if (fgets(line,ndim,fp)!= NULL) current_run = atoi(line)+1;
2726
    fclose(fp);
2727
    fp = NULL;
2728
  }
2729
  ProcessSystemEvents ();
2730
 
2731
  /****** Slow Control ******/
2732
  sprintf(line,"%04d_SlowControl.xml",current_run);
2733
  fp = fopen (line,"w");
2734
  fprintf(fp,"<febtest>\n");
2735
  time(&t);
2736
  fprintf(fp,"<time>%s</time>\n", ctime(&t));
2737
 
2738
  for (int board=0; board<4; board++) {
2739
    if (mask &(1<<board)) {
2740
      for (int k=0; k<10; k++) {
2741
        Delay(0.1);
2742
        SlowControl(board,fp);
2743
        ProcessSystemEvents ();
2744
        if (ctrl_c) break;
2745
      }
2746
    }
2747
    if (ctrl_c) break;
2748
  }
2749
 
2750
  fprintf(fp,"</febtest>\n");
2751
  fclose(fp);
2752
  fp = NULL;
2753
 
2754
  /****** Treshold scan, Calibration & Channel Param Upload (iterations) ******/
2755
  for(int j=0; j<=numberOfIterations; j++) {
2756
    if(!j) {
2757
      //Treshold settings
2758
      SetCtrlVal(p1h,P1_DATA, 400);
2759
      SetCtrlVal(p1h,P1_DSTEP, 1);
2760
      SetCtrlVal(p1h,P1_NEVE, 300);
2761
      SetCtrlVal(p1h,P1_TOREAD, 1000);
2762
      //Calibration settings
2763
      SetCtrlVal (p3h, P3_FITMODE, 2);
2764
      SetCtrlVal (p3h, P3_TARGETOFFSET, 550.);
2765
      SetCtrlVal (p3h, P3_TARGETRMS, 3.);
2766
    }
2767
    sprintf(line,"%04d_0_Treshold_%d.dat", current_run, j);
2768
    SetCtrlVal(p1h,P1_OUTPUTFILE, line);
2769
    if(j==numberOfIterations) continue; //when everything will be working remove this one and uncoment the next one
2770
 
2771
    daq(NULL);
2772
 
2773
    sprintf(cmdCommand,"cmd.exe /c ..\\sa02read -i .\\%s -o .\\%04d_0_Treshold_%d.root", line, current_run, j);
2774
    LaunchExecutable(cmdCommand);
2775
 
2776
 
2777
    ProcessSystemEvents ();
2778
 
2779
    //if(j==numberOfIterations) continue;
2780
 
2781
    sprintf(line,"Coarse fit parameters, iteration %d *\n\n", j);
2782
    sa02Printf(line);
2783
 
2784
    FitH2DCoarse(p3h, P3_CALIBRATION_2,EVENT_COMMIT,NULL,0,0);
2785
    ProcessSystemEvents ();
2786
 
2787
    sprintf(line,"%04d_Iteration_%d.param", current_run, j);
2788
    CreateParamFile(line);
2789
 
2790
    sa02Printf("Loading channel parameters *\n\n");
2791
 
2792
    sprintf(defaulParamFile,"..\\parameters\\%s",line);
2793
    SetCtrlVal(p3h, P3_INPUTFILE, defaulParamFile);                    // write path to P3_INPUTFILE
2794
    SetParametersFromFile(defaulParamFile);                            // write default.param to P3_CREG table
2795
 
2796
    LoadParameters(p3h, P3_LOADPAR, EVENT_COMMIT, NULL, 0, 0);         // load parameters to FEB
2797
    ProcessSystemEvents ();
2798
    LoadParameters(p3h, P3_LOADPAR, EVENT_COMMIT, NULL, 0, 0);         // load parameters to FEB
2799
    ProcessSystemEvents ();
2800
    LoadParameters(p3h, P3_LOADPAR, EVENT_COMMIT, NULL, 0, 0);         // load parameters to FEB
2801
    ProcessSystemEvents ();
2802
 
2803
 
2804
  }
2805
 
2806
  /****** Increases run number in file for 1 ******/
2807
  /*  fp = fopen ("CompleteScan_RunNumber.txt","w");
2808
    fprintf(fp,"%d\n", current_run);
2809
    fclose(fp);
2810
  */
2811
 
2812
  return 0;
2813
}
2814
 
2815
int ModuleTest(void) {
2816
  int HAPDnumberOnOff;
2817
  int ActiveHAPDNo=0;
2818
  int HAPDid[]= {P1_SERIAL_1,P1_SERIAL_2,P1_SERIAL_3,P1_SERIAL_4};
2819
  int HAPDstatus[]= {P1_ONOFF_1,P1_ONOFF_2,P1_ONOFF_3,P1_ONOFF_4};
2820
  int ndim=400;
2821
  int current_run=1;
2822
  int ithr;
2823
  double targetoffset;
2824
  char line[ndim];
2825
  char buf[0xFF];
2826
  char cmdCommand[ndim];
2827
  char HAPDnumber[4][0xFF];
2828
  char HAPDnum[0xFF];
2829
 
2830
  FILE *fp;
2831
 
2832
 
2833
  /****** Check if Serial numbers are filled in ******/
2834
  for (int i=0; i<4; i++) {
2835
    GetCtrlVal(p1h, HAPDid[i], HAPDnum);
2836
    GetCtrlVal(p1h, HAPDstatus[i], &HAPDnumberOnOff);
2837
    if(!strcmp(HAPDnum, "noserial") && HAPDnumberOnOff) {
2838
      printf("Fill in 'HAPD%d number' or disable 'HAPD%d'\n",i,i);
2839
      return -1;
2840
    }
2841
    strcpy(HAPDnumber[i],HAPDnum);
2842
    ActiveHAPDNo+=HAPDnumberOnOff;
2843
  }
2844
  if(!ActiveHAPDNo) {
2845
    sa02Printf("Turn on at least 1 HAPD.");
2846
    return -1;
2847
  }
2848
  sa02Printf("HAPD0 serial: %s \nHAPD1 serial: %s \nHAPD2 serial: %s \nHAPD3 serial: %s \n",HAPDnumber[0],HAPDnumber[1],HAPDnumber[2],HAPDnumber[3]);
2849
 
2850
  /****** MicroMini calibration ******/
2851
  sa02Printf("Calibration *\n\n");
2852
  SetHome(p2h, P2_HO,EVENT_COMMIT,NULL, 0, 0);
2853
  SetCtrlVal(p2h,P2_XC,gCENTER_X);
2854
  SetCtrlVal(p2h,P2_YC,gCENTER_Y);
2855
 
2856
  /****** Reads run number ******/
2857
  fp = fopen ("CompleteScan_RunNumber.txt","r");
2858
  if (fp) {
2859
    if (fgets(line,ndim,fp)!= NULL) current_run = atoi(line)+1;
2860
    fclose(fp);
2861
    fp = NULL;
2862
  }
2863
  ProcessSystemEvents ();
2864
 
2865
  fp = fopen ("CompleteScan_RunNumber.txt","w");
2866
  fprintf(fp,"%d\n", current_run);
2867
  fclose(fp);
2868
 
2869
  GetCtrlVal (p3h, P3_TARGETOFFSET, &targetoffset);   // Treshold
2870
  ithr=(int)targetoffset+20;
2871
  /****** Treshold + Waveform scan over 144x center ******/
2872
  SetCtrlVal (p2h, P2_ZSET, 0);
2873
  SetCtrlVal (p2h, P2_XC, (uint32_t)(gCENTER_KX*0+gCENTER_X));
2874
  SetCtrlVal (p2h, P2_YC, (uint32_t)(gCENTER_KY*0+gCENTER_Y));
2875
  Zset(p2h,P2_ZSET,EVENT_COMMIT,NULL,0,0);
2876
  // Panel 1 setting
2877
  SetCtrlVal (p1h, P1_TPENB, 0);                                    // disable test pulz
2878
  SetCtrlVal (p1h, P1_SENDSWTRIG, 2);                               // set external trigger
2879
  SendTriggerTypeCB (p1h, P1_SENDSWTRIG, EVENT_COMMIT,NULL,0,0);    // commit external trigger
2880
 
2881
  SetCtrlVal(p1h,P1_DATA, 500);    // Inital value
2882
  SetCtrlVal(p1h,P1_DSTEP, 2);     // Step size
2883
  SetCtrlVal(p1h,P1_NEVE, 101);    // Number of steps
2884
  SetCtrlVal(p1h,P1_TOREAD, 1000);  // Number of events
2885
 
2886
  // Panel 4 setting
2887
  //SetCtrlVal(p4h,P4_FRACTION, 0.);  // Fraction of waveforms to store (If you want to create charge accumulation graphs with sa02read set to 1.)
2888
  SetCtrlVal(p4h,P4_NEVE, 4000);  // Number of events
2889
 
2890
  // Panel 2 settings
2891
  SetCtrlVal (p2h, P2_SCANUNITSX, 1);   // Only over the channel centers   (1 Ch, 0 Step)
2892
  SetCtrlVal (p2h, P2_NX, 12);          // Noumber of steps = 12
2893
  SetCtrlVal (p2h, P2_XSTEP, 1);        // Step size = 1
2894
  SetCtrlVal (p2h, P2_XMIN, 0);         // Start position = 0
2895
  SetCtrlVal (p2h, P2_SCANUNITSY, 1);   // Only over the channel centers   (1 Ch, 0 Step)
2896
  SetCtrlVal (p2h, P2_NY, 12);          // Noumber of steps = 12
2897
  SetCtrlVal (p2h, P2_YSTEP, 1);        // Step size = 1
2898
  SetCtrlVal (p2h, P2_YMIN, 0);         // Start position = 0
2899
  SetCtrlVal (p2h, P2_DIRECTION, 1);    // Set Y then scan X = 1 (0 = Set X then scan X)
2900
 
2901
  SetCtrlVal (p2h, P2_NEVE, 100);        // Number of events for position scan (keep low so the scan is faster ... this is not the point of interest for this scan)
2902
  SetCtrlVal (p2h, P2_PEDESTAL, ithr);   // Treshold
2903
 
2904
  SetCtrlVal (p2h, P2_DAQEXE, 3);       // Execute at each position: SA02 scan and CAEN V729a
2905
 
2906
  sprintf(buf,"%04d_1_Treshold_Waveform",current_run);
2907
  sprintf(line,"..\\modules\\%s",buf);
2908
  SetCtrlVal (p2h, P2_DFILE, line);
2909
 
2910
 
2911
  daq_scan(NULL);
2912
 
2913
  sprintf(cmdCommand,"cmd.exe /c mkdir ..\\modules\\%04d & ..\\sa02read -i %s_file01.dat -o ..\\modules\\%04d\\%s.root",
2914
          current_run, line, current_run, buf);
2915
  LaunchExecutable(cmdCommand);
2916
 
2917
 
2918
 
2919
  /****** 2D v X ******/
2920
  // Panel 2 settings
2921
  SetCtrlVal (p2h, P2_SCANUNITSX, 0);   // Continuous scan over X  (1 Ch, 0 Step)
2922
  SetCtrlVal (p2h, P2_NX, 380/2);         // Noumber of steps = 380
2923
  SetCtrlVal (p2h, P2_XSTEP, 2*500);      // Step size = 500
2924
  SetCtrlVal (p2h, P2_XMIN, 83000);     // Start position = 8500
2925
  SetCtrlVal (p2h, P2_SCANUNITSY, 1);   // Only over the channel centers   (1 Ch, 0 Step)
2926
  SetCtrlVal (p2h, P2_NY, 12);          // Noumber of steps = 12
2927
  SetCtrlVal (p2h, P2_YSTEP, 1);        // Step size = 1
2928
  SetCtrlVal (p2h, P2_YMIN, 0);         // Start position = 0
2929
  SetCtrlVal (p2h, P2_DIRECTION, 1);    // Set Y then scan X = 1
2930
 
2931
  SetCtrlVal (p2h, P2_NEVE, 1000);       // Number of events for position scan
2932
  SetCtrlVal (p2h, P2_PEDESTAL, ithr);   // Treshold
2933
 
2934
  SetCtrlVal (p2h, P2_DAQEXE, 0);       // Execute at each position: nothing
2935
 
2936
  sprintf(buf,"%04d_2_2DX",current_run);
2937
  sprintf(line,"..\\modules\\%s", buf);
2938
  SetCtrlVal (p2h, P2_DFILE, line);
2939
 
2940
 
2941
  daq_scan(NULL);
2942
 
2943
  sprintf(cmdCommand,"cmd.exe /c mkdir ..\\modules\\%04d & ..\\sa02read -i %s_file01.dat -o ..\\modules\\%04d\\%s.root ", current_run, line, current_run, buf);
2944
  LaunchExecutable(cmdCommand);
2945
 
2946
 
2947
  /****** 2D v Y ******/
2948
  // Panel 2 settings
2949
  SetCtrlVal (p2h, P2_SCANUNITSX, 1);   // Only over the channel centers   (1 Ch, 0 Step)
2950
  SetCtrlVal (p2h, P2_NX, 12);          // Noumber of steps = 12
2951
  SetCtrlVal (p2h, P2_XSTEP, 1);        // Step size = 1
2952
  SetCtrlVal (p2h, P2_XMIN, 0);         // Start position = 0
2953
  SetCtrlVal (p2h, P2_SCANUNITSY, 0);   // Continuous scan over Y  (1 Ch, 0 Step)
2954
  SetCtrlVal (p2h, P2_NY, 380/2);          // Noumber of steps = 380
2955
  SetCtrlVal (p2h, P2_YSTEP, 2*500);        // Step size = 500
2956
  SetCtrlVal (p2h, P2_YMIN, 75000);         // Start position = 7500
2957
  SetCtrlVal (p2h, P2_DIRECTION, 0);    // Set X then scan Y = 0
2958
 
2959
  SetCtrlVal (p2h, P2_NEVE, 1000);        // Number of events for position scan
2960
  SetCtrlVal (p2h, P2_PEDESTAL, ithr);   // Treshold
2961
 
2962
  SetCtrlVal (p2h, P2_DAQEXE, 0);       // Execute at each position: nothing
2963
 
2964
  sprintf(buf,"%04d_3_2DY",current_run);
2965
  sprintf(line,"..\\modules\\%s", buf);
2966
  SetCtrlVal (p2h, P2_DFILE, line);
2967
 
2968
 
2969
  daq_scan(NULL);
2970
 
2971
  sprintf(cmdCommand,"cmd.exe /c mkdir ..\\modules\\%04d & ..\\sa02read -i %s_file01.dat -o ..\\modules\\%04d\\%s.root ", current_run, line, current_run, buf);
2972
  system(cmdCommand); // wait here to finish to proceed to next step    
2973
 
2974
  sprintf(cmdCommand,"cmd.exe /c ..\\thisroot.bat & cd analysis & root script.c(%d)",current_run);
2975
  LaunchExecutable(cmdCommand);
2976
 
2977
  SetCtrlVal (p2h, P2_ZSET, 300000);
2978
  SetCtrlVal (p2h, P2_XC, (uint32_t)(gCENTER_KX*0+gCENTER_X));
2979
  SetCtrlVal (p2h, P2_YC, (uint32_t)(gCENTER_KY*0+gCENTER_Y));
2980
  Zset(p2h,P2_ZSET,EVENT_COMMIT,NULL,0,0);
2981
 
2982
  return 0;
2983
}
2984
 
2985
int StepThree(void) {
2986
  //char cmdCommand[0xFF];
2987
  //char line[0xFF];
2988
  //char buf[0xFF];
2989
  //int current_run = 11;
2990
 
2991
  return 0;
2992
}
2993
 
2994
 
2995
// map uir controls ....
2996
#define MAX_UIRCTRLMAP_SIZE 1000
2997
typedef struct {
2998
  char name[32];
2999
  int id;
3000
  int handle;
3001
} UirCtrlMap;
3002
UirCtrlMap gUirCtrlMap[MAX_UIRCTRLMAP_SIZE];
3003
int gNUirCtrlMap=0;
3004
 
3005
int GetControlID(const char *ctrl) {
3006
  for (int i=0; i<gNUirCtrlMap; i++) {
3007
    if (strcmp(ctrl,gUirCtrlMap[i].name)==0) return ctrl,gUirCtrlMap[i].id;
3008
  }
3009
  return -1;
3010
}
3011
int GetPanelHandle(const char *ctrl) {
3012
 
3013
  if ( strstr(ctrl, "P1_")!= NULL ) return p1h;
3014
  if ( strstr(ctrl, "P2_")!= NULL ) return p2h;
3015
  if ( strstr(ctrl, "P3_")!= NULL ) return p3h;
3016
  if ( strstr(ctrl, "P4_")!= NULL ) return p4h;
3017
  if ( strstr(ctrl, "P5_")!= NULL ) return p5h;
3018
 
3019
  return -1;
3020
}
3021
 
3022
int LoadUirHeader(const char *fname) {
3023
  int ndim=MAX_PATHNAME_LEN;
3024
  char line[MAX_PATHNAME_LEN];
3025
  char cmd[MAX_PATHNAME_LEN];
3026
  FILE *fp = NULL;
3027
  ssize_t size;
3028
  int n0= gNUirCtrlMap;
3029
  if ( GetFileInfo(fname,&size) ) fp = fopen(fname,"r");
3030
  if (!fp) {
3031
    sa02Printf("Error! Cannot open header file %s\n",fname);
3032
    return -1;
3033
  }
3034
 
3035
  while (fgets(line,ndim,fp)!=NULL ) {
3036
    char ctrl[32];
3037
    int ctrlid;
3038
    int nb = sscanf(line,"%s%s%d",cmd, ctrl, &ctrlid);
3039
    if (strstr(cmd,"#define")!=NULL && nb==3) {
3040
      strcpy(gUirCtrlMap[gNUirCtrlMap].name, ctrl );
3041
      if (gNUirCtrlMap<MAX_UIRCTRLMAP_SIZE) {
3042
        gUirCtrlMap[gNUirCtrlMap].id     = ctrlid;
3043
        gUirCtrlMap[gNUirCtrlMap].handle = GetPanelHandle(ctrl);
3044
        gNUirCtrlMap++;
3045
      } else {
3046
        sa02Printf("ERROR: Increase gNUirCtrlMap\n");
3047
      }
3048
    }
3049
  }
3050
  fclose(fp);
3051
  sa02Printf("Number of Controls loaded from File %s = %d \n", fname,gNUirCtrlMap-n0);
3052
  return 0;
3053
}
3054
 
3055
 
3056
char *str_replace(const char *str, const char *old, const char *new) {
3057
 
3058
  /* Adjust each of the below values to suit your needs. */
3059
 
3060
  /* Increment positions cache size initially by this number. */
3061
  size_t cache_sz_inc = 16;
3062
  /* Thereafter, each time capacity needs to be increased,
3063
   * multiply the increment by this factor. */
3064
  const size_t cache_sz_inc_factor = 3;
3065
  /* But never increment capacity by more than this number. */
3066
  const size_t cache_sz_inc_max = 1048576;
3067
 
3068
  char *pret, *ret = NULL;
3069
  const char *pstr2, *pstr = str;
3070
  size_t i, count = 0;
3071
  ptrdiff_t *pos_cache = NULL;
3072
  size_t cache_sz = 0;
3073
  size_t cpylen, orglen, retlen, newlen =0, oldlen = strlen(old);
3074
 
3075
  /* Find all matches and cache their positions. */
3076
  while ((pstr2 = strstr(pstr, old)) != NULL) {
3077
    count++;
3078
 
3079
    /* Increase the cache size when necessary. */
3080
    if (cache_sz < count) {
3081
      cache_sz += cache_sz_inc;
3082
      pos_cache = realloc(pos_cache, sizeof(*pos_cache) * cache_sz);
3083
      if (pos_cache == NULL) {
3084
        goto end_repl_str;
3085
      }
3086
      cache_sz_inc *= cache_sz_inc_factor;
3087
      if (cache_sz_inc > cache_sz_inc_max) {
3088
        cache_sz_inc = cache_sz_inc_max;
3089
      }
3090
    }
3091
 
3092
    pos_cache[count-1] = pstr2 - str;
3093
    pstr = pstr2 + oldlen;
3094
  }
3095
 
3096
  orglen = pstr - str + strlen(pstr);
3097
 
3098
  /* Allocate memory for the post-replacement string. */
3099
  if (count > 0) {
3100
    newlen = strlen(new);
3101
    retlen = orglen + (newlen - oldlen) * count;
3102
  } else  retlen = orglen;
3103
  ret = malloc(retlen + 1);
3104
  if (ret == NULL) {
3105
    goto end_repl_str;
3106
  }
3107
 
3108
  if (count == 0) {
3109
    /* If no matches, then just duplicate the string. */
3110
    strcpy(ret, str);
3111
  } else {
3112
    /* Otherwise, duplicate the string whilst performing
3113
     * the replacements using the position cache. */
3114
    pret = ret;
3115
    memcpy(pret, str, pos_cache[0]);
3116
    pret += pos_cache[0];
3117
    for (i = 0; i < count; i++) {
3118
      memcpy(pret, new, newlen);
3119
      pret += newlen;
3120
      pstr = str + pos_cache[i] + oldlen;
3121
      cpylen = (i == count-1 ? orglen : (size_t)pos_cache[i+1]) - pos_cache[i] - oldlen;
3122
      memcpy(pret, pstr, cpylen);
3123
      pret += cpylen;
3124
    }
3125
    ret[retlen] = '\0';
3126
  }
3127
 
3128
end_repl_str:
3129
  /* Free the cache and return the post-replacement string,
3130
   * which will be NULL in the event of an error. */
3131
  free(pos_cache);
3132
  return ret;
3133
}
3134
 
3135
 
3136
int CVICALLBACK run_script(void *functionData) {
3137
  FILE *fp = NULL;
3138
  FILE *fpout =NULL;
3139
 
3140
 
3141
  char *line;
3142
  char buf[MAX_PATHNAME_LEN];
3143
  int status;
3144
  char type[MAX_PATHNAME_LEN];
3145
  char param[MAX_PATHNAME_LEN];
3146
  char paramValue[MAX_PATHNAME_LEN];
3147
  int scx,nx,xstep,xmin,scy,ny,ystep,ymin,direction,nevents,tresh;
3148
  char test[256];
3149
  char outputFileSuffix[128];
3150
  char outputFile[MAX_PATHNAME_LEN];
3151
  char HAPDserialNumber[128];
3152
  ssize_t size;
3153
  int data[2];
3154
  int runno=0;
3155
 
3156
  char scriptname[MAX_PATHNAME_LEN];
3157
  GetCtrlVal(p1h,P1_SCRIPTNAME, scriptname);
3158
 
3159
 
3160
  if ( GetFileInfo(scriptname,&size) ) fp = fopen(scriptname,"r");
3161
  if (!fp) {
3162
    sa02Printf("Error! Cannot open script file %s\n",scriptname);
3163
    return -1;
3164
  }
3165
  while (fgets(buf,MAX_PATHNAME_LEN,fp)!=NULL ) {
3166
 
3167
    if (buf[0]!='#' && strlen(buf)>2) {
3168
      if (strstr(buf, "%RUN%")!=NULL) {
3169
          char srun[16];
3170
          sprintf(srun,"%04d",runno);
3171
          line = str_replace(buf,"%RUN%", srun);
3172
      } else {
3173
          line = buf;
3174
      }
3175
      sa02Printf("#[%d] %s",strlen(buf),buf);  
3176
 
3177
      sscanf(line,"%s",type);
3178
 
3179
      if (strstr(type,"SetCtrlVal")!=NULL) {
3180
        int pID;  
3181
        int rID;
3182
        int datatype;
3183
        sscanf(line,"%*s%s%s",param,paramValue);
3184
 
3185
        pID= GetPanelHandle(param);  
3186
        rID= GetControlID(param);
3187
        if (rID>0 && pID>0) {
3188
          GetCtrlAttribute (pID, rID, ATTR_DATA_TYPE, &datatype);
3189
 
3190
          switch (datatype){
3191
            case VAL_INTEGER: SetCtrlVal (pID, rID, atoi(paramValue)); break;
3192
            case VAL_UNSIGNED_INTEGER: SetCtrlVal (pID, rID, strtoul(paramValue,NULL,0)); break;
3193
            case VAL_SHORT_INTEGER: SetCtrlVal (pID, rID, atoi(paramValue)); break;
3194
            case VAL_UNSIGNED_SHORT_INTEGER: SetCtrlVal (pID, rID, strtoul(paramValue,NULL,0)); break;
3195
            case VAL_DOUBLE : SetCtrlVal (pID, rID, atof(paramValue)); break;
3196
            case VAL_STRING : SetCtrlVal (pID, rID, paramValue      ); break;
3197
            default: sa02Printf("[%s] ATTR_DATA_TYPE of the %s not supported datatype %d p4h=%d\n\n", type, param, datatype, p4h);
3198
          }
3199
          //sa02Printf("[%s] SetCtrlVal %s %s panel=%d control=%d\n",type,param, paramValue,pID,rID);  
3200
        } else {
3201
           sa02Printf("[%s] Invalid Ctrl %s %s panel=%d control=%d\n",type,param, paramValue,pID,rID);
3202
        }  
3203
 
3204
      } else if (strstr(type,"2D")!=NULL) {
3205
        sscanf(line,"%*s%d%d%d%d%d%d%d%d%d%d%d%s",&scx,&nx,&xstep,&xmin,&scy,&ny,&ystep,&ymin,&direction,&nevents,&tresh,outputFileSuffix);
3206
        sprintf(test,"%d %d %d %d %d %d %d %d %d %d %d %s *\n",scx,nx,xstep,xmin,scy,ny,ystep,ymin,direction,nevents,tresh,outputFileSuffix);
3207
        sa02Printf("%s *\n\n",test);
3208
        SetCtrlVal (p2h, P2_SCANUNITSX, scx);
3209
        SetCtrlVal (p2h, P2_NX, nx);
3210
        SetCtrlVal (p2h, P2_XSTEP, xstep);
3211
        SetCtrlVal (p2h, P2_XMIN, xmin);
3212
        SetCtrlVal (p2h, P2_SCANUNITSY, scy);
3213
        SetCtrlVal (p2h, P2_NY, ny);
3214
        SetCtrlVal (p2h, P2_YSTEP, ystep);
3215
        SetCtrlVal (p2h, P2_YMIN, ymin);
3216
        SetCtrlVal (p2h, P2_DIRECTION, direction);
3217
 
3218
        SetCtrlVal (p2h, P2_NEVE, nevents);
3219
        SetCtrlVal (p2h, P2_PEDESTAL, tresh);
3220
 
3221
        GetCtrlVal (p1h, P1_SERIAL_1, HAPDserialNumber);
3222
        sprintf(outputFile,"%s_%s", HAPDserialNumber, outputFileSuffix);
3223
        SetCtrlVal (p2h, P2_DFILE, outputFile);
3224
 
3225
 
3226
        daq_scan(NULL);
3227
 
3228
      } else if (strstr(type,"Delay")!=NULL) {
3229
        int idelay=0;
3230
        sscanf(line,"%*s%s",paramValue);
3231
        for (idelay=atoi(paramValue) ; idelay>0; idelay--) {
3232
          Delay(1);
3233
          SetCtrlVal(p1h, P1_DELAY, idelay);
3234
          ProcessSystemEvents();
3235
          if (ctrl_c) break;
3236
        }
3237
      }  else if (strstr(type,"ThresholdLinearity")!=NULL) {
3238
        char *fname;
3239
        uint16_t mask = GetConnectedFebMask();
3240
 
3241
        sscanf(line,"%*s%s",paramValue);
3242
        fname = paramValue;
3243
 
3244
 
3245
        ThresholdLinearityCB (p1h, P1_THRVSADC, EVENT_COMMIT, NULL, 0, 0 );
3246
        fpout = fopen(fname,"ab");
3247
        if(fpout) {
3248
          for (int board=0; board<4; board++) if ( mask &(1<<board))  H1DWrite2File(board,fpout);
3249
          fclose(fpout);
3250
        }
3251
 
3252
      }  else if (strstr(type,"LaunchExecutable")!=NULL) {
3253
        int index = FindPattern (line, 0, -1, "LaunchExecutable", 0, 0) + 17;
3254
 
3255
        char *cmd = &line[index];
3256
        sa02Printf("cmd %d=%s\n",index, cmd);
3257
        if (strlen(cmd)>0) LaunchExecutable( cmd );
3258
      }  else if (strstr(type,"CAEN_V729")!=NULL) {  
3259
        char *fname;
3260
        //FILE *fpmon=NULL;
3261
 
3262
        sscanf(line,"%*s%s",paramValue);
3263
        fname=paramValue;
3264
 
3265
        fpout = fopen(fname,"ab");
3266
        if (fpout) {
3267
 
3268
          V729_SetFilePointer(fpout);
3269
          V729_daq(NULL);
3270
          fclose(fpout);
3271
        }
3272
      } else if (strstr(type,"HvMonitor")!=NULL) {
3273
        int nrepetitions;
3274
        int delaytime;
3275
        int k=0;
3276
        FILE *fpmon=NULL;
3277
        sscanf(line,"%*s%s%d%d",paramValue, &delaytime, &nrepetitions );
3278
        fpmon = fopen(paramValue,"ab");
3279
 
3280
        if ( fpmon ) {
3281
          hvmonFirst = 0;
3282
          for (k=0; k<nrepetitions; k++) {
3283
            double thv0,thv1;
3284
            thv0 = Timer();
3285
            GetHvMonitor();
3286
            for (int board=0;board<4;board++){
3287
              double sdata[12];
3288
              for (int k=0;k<6;k++){
3289
                 sdata[k] = monrec.imon[k+4*board];
3290
                 sdata[k+6] = 0;
3291
              }
3292
 
3293
              SetAxisScalingMode (p1h, chart_control[board], VAL_LEFT_YAXIS, VAL_AUTOSCALE, 0, 1);
3294
              SetAxisScalingMode (p1h, chart_control[board], VAL_RIGHT_YAXIS, VAL_AUTOSCALE, 0, 1);
3295
              PlotStripChart (p1h, chart_control[board], sdata, 12, 0, 0, VAL_DOUBLE);
3296
            }  
3297
            monrec.id = MONREC_ID;
3298
            monrec.len = sizeof(monrec);
3299
            thv1=Timer();
3300
            status = (int) fwrite( &monrec,  1,  sizeof(monrec),fpmon);
3301
            sa02Printf("[%04d] HvMonitor dt= %f s status=%d\n", runno, thv1-thv0, status );
3302
            for (int idelay=delaytime ; idelay>0; idelay--) {
3303
              Delay(1);
3304
              SetCtrlVal(p1h, P1_DELAY, idelay);
3305
              ProcessSystemEvents();
3306
              if (ctrl_c) break;
3307
            }
3308
            if (ctrl_c) break;
3309
          }
3310
          fclose(fpmon);
3311
        } else {
3312
          sa02Printf("%s cannot open file %s\n",param, paramValue );
3313
        }
3314
 
3315
      } else if (strstr(type,"GetRunNumberFromFile")!=NULL) {
3316
        sscanf(line,"%*s%s",paramValue);
3317
        runno = GetRunNumberFromFile(paramValue);
3318
        SetCtrlVal(p1h, P1_RUNNO, runno);
3319
        sa02Printf("%s %s run=>%d\n",type, paramValue, runno );
3320
      } else if (strstr(type,"IncreaseNumberInFile")!=NULL) {
3321
        sscanf(line,"%*s%s",paramValue);
3322
        runno = IncreaseRunNumberInFile(paramValue);
3323
        sa02Printf("%s %s run=>%d\n",type, paramValue, runno );
3324
        SetCtrlVal(p1h, P1_RUNNO, runno);
3325
      } else if (strstr(type,"LoadParameters")!=NULL) {
3326
        LoadParameters(p3h, P3_LOADPAR,EVENT_COMMIT,NULL,0,0);
3327
        sa02Printf("Loading parameters *\n\n");
3328
      } else if (strstr(type,"QueueUserEvent")!=NULL || strstr(type,"ProcessUserEvent")!=NULL) {
3329
        char scontrol[0xFF];
3330
        int panelHandle=0;
3331
        int controlID;
3332
        sscanf(line,"%*s%s",scontrol);
3333
        panelHandle = GetPanelHandle(scontrol);
3334
        controlID   = GetControlID(scontrol);
3335
        sa02Printf("UserEvent %s panelHandle %d controlID %d\n",scontrol, panelHandle, controlID );
3336
        if (panelHandle>=0 && controlID >=0 ) {
3337
          if (strstr(type,"ProcessUserEvent")!=NULL) {
3338
            ProcessUserEvent(panelHandle, controlID,0);
3339
          } else {
3340
            data[1] = controlID;
3341
            data[0] = panelHandle;
3342
 
3343
            status = CmtWriteTSQData (pTSQ, data, 1, TSQ_INFINITE_TIMEOUT, NULL);
3344
          }  
3345
        }
3346
 
3347
      }  else if (strstr(type,"SetPositionAndMux")!=NULL) {
3348
        int ix,iy;
3349
        sscanf(line,"%*s%d%d",&ix,&iy);
3350
        sa02Printf("SetPositionAndMux %d %d \n", ix,iy);
3351
 
3352
        SetCtrlVal (p2h, P2_CHX,  ix);
3353
        SetCtrlVal (p2h, P2_CHY,  iy);
3354
        SetPositionAndMux(  p2h,0, EVENT_COMMIT , NULL,0,0);
3355
 
3356
      }  else if (strstr(type,"Treshold")!=NULL) {
3357
        sscanf(line,"%*s%s",outputFileSuffix);
3358
 
3359
        GetCtrlVal (p1h, P1_SERIAL_1, HAPDserialNumber);
3360
        sprintf(outputFile,"%s_%s.dat", HAPDserialNumber, outputFileSuffix);
3361
        SetCtrlVal (p1h, P1_OUTPUTFILE, outputFile);
3362
 
3363
        sprintf(test,"Treshold scan to file %s",outputFile);
3364
        sa02Printf("%s *\n\n", test);
3365
 
3366
        daq(NULL);
3367
      } else if (strstr(type,"Fitanje")!=NULL) {
3368
        FitH2DCoarse(p3h, P3_CALIBRATION_2,EVENT_COMMIT,NULL,0,0);
3369
        sa02Printf("Coarse fit parameters *\n\n");
3370
      } else if (strstr(type,"UploadChannelParameters")!=NULL) {
3371
        UploadChannelParameters(p3h, P3_CPARLOAD,EVENT_COMMIT,NULL,0,0);
3372
        sa02Printf("Loading channel parameters *\n\n");
3373
      } else if (strstr(type,"KalibracijaMizice")!=NULL) {
3374
        SetHome(p2h, P2_HO,EVENT_COMMIT,NULL,0,0);
3375
        SetCtrlVal(p2h,P2_XC,gCENTER_X);
3376
        SetCtrlVal(p2h,P2_YC,gCENTER_Y);
3377
        sa02Printf("Calibration *\n\n");
3378
      } else if (strstr(type,"LaserHVOn")!=NULL) {
3379
        set_dac(1);
3380
        sa02Printf("Low intensity laser *\n\n");
3381
      } else if (strstr(type,"LaserHVOff")!=NULL) {
3382
        set_dac(0);
3383
        sa02Printf("High intensity laser *\n\n");
3384
      } else if (strstr(type,"Gain")!=NULL) {
3385
        sscanf(line,"%*s%d",paramValue);
3386
        sprintf(test,"    %d", atoi(paramValue));
3387
        sa02Printf("%s *\n\n", test);
3388
        changeGlobalParam(12, atoi(paramValue)); // Global parameter Gain has ID 12
3389
      } else if (strstr(type,"ShapingTime")!=NULL) {
3390
        sscanf(line,"%*s%s",paramValue);
3391
        sprintf(test,"    %d", atoi(paramValue));
3392
        sa02Printf("%s *\n\n", test);
3393
        changeGlobalParam(13, atoi(paramValue)); // Global parameter ShapingTime has ID 13
3394
      }
3395
    }
3396
    if (ctrl_c) {
3397
      break;
3398
    }
3399
  }
3400
  fclose(fp);
3401
  return 0;
3402
}
3403
 
3404
/*
3405
int CVICALLBACK StartPositionScan (int panel, int control, int event,
3406
    void *callbackData, int eventData1, int eventData2)
3407
{
3408
  switch (event)
3409
    {
3410
    case EVENT_COMMIT:
3411
        daq_scan(NULL);
3412
      break;
3413
    }
3414
  return 0;
3415
}
3416
*/
3417
 
3418
int CVICALLBACK SetHome (int panel, int control, int event,
3419
                         void *callbackData, int eventData1, int eventData2) {
3420
  switch (event) {
3421
    case EVENT_COMMIT:
3422
      SetWaitCursor (1);
3423
      if (gMIKRO_X)  MIKRO_ReferenceMove (MIKRO_X);
3424
      if (gMIKRO_Y)  MIKRO_ReferenceMove (MIKRO_Y);
3425
      if (gMIKRO_Z)  MIKRO_ReferenceMove (MIKRO_Z);
3426
      SetWaitCursor (0);
3427
      break;
3428
  }
3429
  return 0;
3430
}
3431
 
3432
int CVICALLBACK CBTimer (int panel, int control, int event,
3433
                         void *callbackData, int eventData1, int eventData2) {
3434
  switch (event) {
3435
    case EVENT_TIMER_TICK:
3436
//      ProcessSystemEvents();
3437
      break;
3438
  }
3439
  return 0;
3440
}
3441
 
3442
int CVICALLBACK GetPosition (int panel, int control, int event,
3443
                             void *callbackData, int eventData1, int eventData2) {
3444
  int xpos=0,ypos=0,zpos=0;
3445
  switch (event) {
3446
 
3447
    case EVENT_COMMIT:
3448
 
3449
      if (gMIKRO_X) {
3450
        MIKRO_GetPosition(MIKRO_X,&xpos);
3451
        Delay(0.01);
3452
        SetCtrlVal (p2h, P2_X, xpos);
3453
      }
3454
 
3455
      if (gMIKRO_Y) {
3456
        MIKRO_GetPosition(MIKRO_Y,&ypos);
3457
        Delay(0.01);
3458
        SetCtrlVal (p2h, P2_Y, ypos);
3459
      }
3460
      if (gMIKRO_X) {
3461
        MIKRO_GetPosition(MIKRO_Z,&zpos);
3462
        Delay(0.01);
3463
        SetCtrlVal (p2h, P2_Z, zpos);
3464
        sa02Printf("x=%d y=%d z=%d\n",xpos,ypos,zpos);
3465
      }
3466
 
3467
 
3468
      break;
3469
  }
3470
  return 0;
3471
}
3472
 
3473
int CVICALLBACK ReRead (int panel, int control, int event,
3474
                        void *callbackData, int eventData1, int eventData2) {
3475
  switch (event) {
3476
    case EVENT_COMMIT: {
3477
      int status;
3478
      char dfile[MAX_PATHNAME_LEN];
3479
      FILE *fp;
3480
 
3481
      status = FileSelectPopup ("", "*.dat", ".dat",
3482
                                "Izberi datoteko s podatki",
3483
                                VAL_LOAD_BUTTON, 0, 0, 1, 0, dfile);
3484
      if (status==1) {
3485
        fp = fopen (dfile, "rb");
3486
        status = (int) fread (&runrec, 1, sizeof(runrec), fp);
3487
        fclose(fp);
3488
        if (runrec.id==RUNREC_ID) {
3489
          SetCtrlVal (p2h, P2_NX, runrec.nx);
3490
          SetCtrlVal (p2h, P2_XSTEP, runrec.dx);
3491
          SetCtrlVal (p2h, P2_XMIN, runrec.x0);
3492
          SetCtrlVal (p2h, P2_NY, runrec.ny);
3493
          SetCtrlVal (p2h, P2_YSTEP, runrec.dy);
3494
          SetCtrlVal (p2h, P2_YMIN, runrec.y0);
3495
          SetCtrlVal (p2h, P2_NEVE, runrec.nev);
3496
          SetCtrlVal (p2h, P2_SCANUNITSX, runrec.fver%2);
3497
          SetCtrlVal (p2h, P2_SCANUNITSY, runrec.fver/2);
3498
          SetCtrlVal (p2h, P2_DIRECTION, runrec.direction);
3499
        }
3500
      }
3501
    }
3502
    break;
3503
  }
3504
  return 0;
3505
}
3506
 
3507
int CVICALLBACK Zset (int panel, int control, int event,
3508
                      void *callbackData, int eventData1, int eventData2) {
3509
  switch (event) {
3510
    case EVENT_COMMIT: {
3511
      int zpos;
3512
      GetCtrlVal (p2h, P2_ZSET, &zpos);
3513
      if (gMIKRO_Z) MIKRO_MoveTo (MIKRO_Z, zpos);
3514
 
3515
    }
3516
    break;
3517
  }
3518
  return 0;
3519
}
3520
 
3521
int CVICALLBACK HidePanelCB (int panel, int control, int event,
3522
                             void *callbackData, int eventData1, int eventData2) {
3523
  switch (event) {
3524
    case EVENT_COMMIT:
3525
      HidePanel (panel);
3526
      break;
3527
  }
3528
  return 0;
3529
}
3530
 
3531
int GetChannelPosition(int chip, int ch, int *chx, int *chy) {
3532
 
3533
  int i=0;
3534
 
3535
  for (i=0; i<144; i++) {
3536
 
3537
    if (eid2hapdxy[i].chip == chip && eid2hapdxy[i].ch == ch) {
3538
      *chx   = eid2hapdxy[i].chx;
3539
      *chy   = eid2hapdxy[i].chy  ;
3540
      return 0;
3541
    }
3542
  }
3543
  return -1;
3544
 
3545
}
3546
 
3547
int LoadElectronicMap(const char *fname) {
3548
 
3549
  FILE *fp = fopen(fname,"r");
3550
  int chip,ch,chx,chy,chxr,chyr;
3551
  int nread=0;
3552
  int ndim=400;
3553
  char line[400];
3554
  int  nr=0;
3555
 
3556
  while (fgets(line,ndim,fp)!=NULL) {
3557
 
3558
    nr = sscanf(line,"%d%d%d%d",&chip,&ch,&chxr,&chyr);
3559
    if (nr) {
3560
// Orientation of HAPD in xy system - position of APD A:LR,UR,UL,LL and view:B,F
3561
//LRB
3562
//      chx=11-chxr;
3563
//      chy=11-chyr;
3564
//URB
3565
      chx=chyr;
3566
      chy=11-chxr;
3567
//ULB
3568
//      chx=chxr;
3569
//      chy=chyr;
3570
//LLB
3571
//      chx=11-chyr;
3572
//      chy=chxr;
3573
      eid2hapdxy[nread].chip = chip;
3574
      eid2hapdxy[nread].ch   = ch  ;
3575
      eid2hapdxy[nread].chx  = chx ;
3576
      eid2hapdxy[nread].chy  = chy ;
3577
    }
3578
    nread++;
3579
  }
3580
  sa02Printf("eid2hapdxy %d records read.\n",nread);
3581
  fclose(fp);
3582
  return 0;
3583
 
3584
}
3585
 
3586
int CVICALLBACK SetParameters (int panel, int control, int event,
3587
                               void *callbackData, int eventData1, int eventData2) {
3588
  //uint32_t address;
3589
  //char saddress[0xFF],
3590
  char fname[0xFF];
3591
 
3592
  switch (event) {
3593
    case EVENT_COMMIT:
3594
      GetCtrlVal(p3h, P3_INPUTFILE, fname);
3595
      SetParametersFromFile(fname);
3596
 
3597
      break;
3598
  }
3599
  return 0;
3600
}
3601
 
3602
int CVICALLBACK UploadGlobalParameters (int panel, int control, int event,
3603
                                        void *callbackData, int eventData1, int eventData2) {
3604
  uint32_t response[2]= {0,0};
3605
  switch (event) {
3606
    case EVENT_COMMIT:
3607
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 1);
3608
      {
3609
        uint32_t gdata;
3610
 
3611
        int board,asic;
3612
        int i=0,imin=0,imax=0;
3613
        Rect trange;
3614
        Point cell;
3615
        int row=0;
3616
        unsigned short val;
3617
        sa02AsicGlobalRegister  *greg = (sa02AsicGlobalRegister *) &gdata ;
3618
        uint16_t mask=GetConnectedFebMask();
3619
//        GetCtrlVal(p1h,P1_BOARDNUMBER,&board);
3620
        GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
3621
 
3622
        if (control== P3_SELGPARLOAD) {
3623
          GetTableSelection (p3h, P3_GREG, &trange);
3624
          if ((trange.top!=0)&&(trange.left!=0)) {
3625
            imin= trange.top - 1;
3626
            imax= imin + trange.height;
3627
 
3628
          } else {
3629
            if (!GetActiveTableCell(p3h, P3_GREG, &cell)) {
3630
              imin = cell.y-1;
3631
              imax = imin;
3632
            } else return 0;
3633
          }
3634
        } else {
3635
          imin=0;
3636
          imax=4*4;
3637
        }
3638
 
3639
        for (i=imin; i<imax; i++) {
3640
          row=i+1;
3641
          GetTableCellVal (p3h, P3_GREG, MakePoint (1,row), &val);
3642
          greg->phasecmps = val;
3643
          GetTableCellVal (p3h, P3_GREG, MakePoint (2,row), &val);
3644
          greg->gain = val;
3645
          GetTableCellVal (p3h, P3_GREG, MakePoint (3,row), &val);
3646
          greg->shapingtime = val;
3647
          GetTableCellVal (p3h, P3_GREG, MakePoint (4,row), &val);
3648
          greg->comparator = val;
3649
          GetTableCellVal (p3h, P3_GREG, MakePoint (5,row), &val);
3650
          greg->vrdrive = val;
3651
          GetTableCellVal (p3h, P3_GREG, MakePoint (6,row), &val);
3652
          greg->monitor = val;
3653
          //GetTableCellVal (p3h, P3_GREG, MakePoint (7,row), &val); greg->id = val;
3654
          greg->id = 0;
3655
          greg->unused=0;
3656
          board=i/4;
3657
          asic=i%4;
3658
 
3659
          if (mask & (1<<board) ) sa02Cmd(board,SA0x_ASIC0_GREG, gdata, asic, 0,1,response);
3660
          if (ctrl_c) {
3661
            break;
3662
          }
3663
        }
3664
      }
3665
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 0);
3666
      sa02Printf("Global Parameters Uploaded to the ASICs\n");
3667
      break;
3668
  }
3669
  return 0;
3670
}
3671
 
3672
int CVICALLBACK UploadChannelParameters (int panel, int control, int event,
3673
    void *callbackData, int eventData1, int eventData2) {
3674
  uint32_t response[2]= {0,0};
3675
  switch (event) {
3676
    case EVENT_COMMIT:
3677
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 1);
3678
      {
3679
        uint32_t cdata;
3680
        int state;
3681
        Rect trange;
3682
        Point cell;
3683
 
3684
        sa02AsicChannelRegister *creg = (sa02AsicChannelRegister *) &cdata ;
3685
 
3686
        unsigned int i=0,imin=0,imax=0;
3687
        int row=0;
3688
        uint32_t board;
3689
        uint16_t mask=GetConnectedFebMask();
3690
 
3691
        unsigned short val,asic,ch;
3692
 
3693
//        GetCtrlVal(p1h,P1_BOARDNUMBER, &board);
3694
        GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
3695
 
3696
        if ((panel==p3h)&&(control==P3_SELCPARLOAD)) {
3697
          state = GetTableSelection (p3h, P3_CREG, &trange);
3698
          if ((trange.top!=0)&&(trange.left!=0)) {
3699
            imin= trange.top-1;
3700
            imax= imin + trange.height;
3701
 
3702
          } else {
3703
            if (!GetActiveTableCell(p3h, P3_CREG, &cell)) {
3704
              imin = cell.y-1;
3705
              imax = imin+1;
3706
            } else return 0;
3707
          }
3708
        } else if ((panel==p1h)&&(control==P1_CHPARLOAD)) {
3709
          GetCtrlVal(p1h,P1_NSLIX,&imin);
3710
          imax=imin+1;
3711
        } else {
3712
          imin=0;
3713
          imax=144*4;
3714
        }
3715
 
3716
        for (i=imin; i<imax; i++) {
3717
//          asic=(unsigned short )(i/36);
3718
//          ch=(unsigned short )(i%36);
3719
          int err = 0;
3720
          row=i+1;
3721
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (1,row), &asic)) err=1;
3722
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (2,row), &ch)) err=1;
3723
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (3,row), &val)) err=1;
3724
          creg->decaytime=val;
3725
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (4,row), &val)) err=1;
3726
          creg->offset = val;
3727
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (5,row), &val)) err=1;
3728
          creg->fineadj_unipol = val;
3729
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (6,row), &val)) err=1;
3730
          creg->fineadj_diff = val;
3731
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (7,row), &val)) err=1;
3732
          creg->tpenb = val;
3733
          //sa02Printf("===%d   %d\n",i, val);
3734
          if (GetTableCellVal (p3h, P3_CREG, MakePoint (8,row), &val)) err=1;
3735
          creg->kill = val;
3736
          creg->unused=0;
3737
          board=i/144;
3738
          if (mask & (1<<board) ) sa02Cmd(board,SA0x_ASIC0_CREG, cdata, asic, ch,1,response);
3739
          if (sa02Verbose >0) {
3740
            sa02Printf("===%d\n",i);
3741
          }
3742
          if (err) sa02Printf("*** Table read error at row %d ***\n",row);
3743
          if (ctrl_c) {
3744
            break;
3745
          }
3746
        }
3747
        sa02Printf("Channel Parameters Uploaded to the ASICs\n");
3748
 
3749
      }
3750
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 0);
3751
      break;
3752
  }
3753
  return 0;
3754
}
3755
 
3756
int CVICALLBACK UploadFPGAParameters (int panel, int control, int event,
3757
                                      void *callbackData, int eventData1, int eventData2) {
3758
 
3759
  int n=0;
3760
  int i=0;
3761
  int nb=0;
3762
#define NDIM 400
3763
  int asic=0;
3764
  char buf[NDIM];
3765
  char cmd[NDIM];
3766
  char sasic[NDIM];
3767
  uint32_t sa02code;
3768
  uint32_t board;
3769
  uint32_t response[2]= {0,0};
3770
 
3771
  switch (event) {
3772
    case EVENT_COMMIT: {
3773
      uint16_t mask=GetConnectedFebMask();
3774
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 1);
3775
 
3776
      GetNumTextBoxLines(p3h, P3_FPGAPAR,&n);
3777
      for (i=0; i<n; i++) {
3778
        GetTextBoxLine(p3h, P3_FPGAPAR, i, buf);
3779
        nb = sscanf(buf,"%s%s",cmd,sasic);
3780
        asic =   strtoul (sasic,NULL,0);
3781
        sa02code = sa02GetCmdCode(cmd);
3782
        if (strcmp(cmd,"MUXASIC")==0) {
3783
          asic = sa02MuxMap(asic);
3784
        }
3785
        for (board = 0; board < 4; board ++) if ( mask & (1 << board) ) sa02Cmd(board,sa02code, asic, 0, 0, 2,response);
3786
        sa02Printf("%s\n",buf);
3787
      }
3788
      sa02Printf("FPGA Parameters Uploaded to FEBS\n");
3789
      SetCtrlAttribute (panel, control, ATTR_DIMMED, 0);
3790
      break;
3791
    }
3792
  }
3793
  return 0;
3794
}
3795
 
3796
int CVICALLBACK SetSelectionToVal (int panel, int control, int event,
3797
                                   void *callbackData, int eventData1, int eventData2) {
3798
  int state, input_cid=-1,output_cid=-1;
3799
  Rect trange;
3800
  unsigned short value;
3801
  switch (event) {
3802
    case EVENT_COMMIT:
3803
      switch (control) {
3804
        case P3_SETSELCPAR:
3805
          input_cid=P3_SETCPAR;
3806
          output_cid=P3_CREG;
3807
          break;
3808
        case P3_SETSELGPAR:
3809
          input_cid=P3_SETGPAR;
3810
          output_cid=P3_GREG;
3811
          break;
3812
 
3813
      }
3814
      state = GetTableSelection (p3h, output_cid, &trange);
3815
      if ((trange.top!=0)&&(trange.left!=0)) {
3816
        GetCtrlVal(p3h,input_cid, &value);
3817
        state = FillTableCellRange (p3h, output_cid, trange, value);
3818
      }
3819
      break;
3820
  }
3821
  return 0;
3822
}
3823
 
3824
int CVICALLBACK SelectMux (int panel, int control, int event,
3825
                           void *callbackData, int eventData1, int eventData2) {
3826
  int cid[4]= {P3_MUX0,P3_MUX1,P3_MUX2,P3_MUX3};
3827
  int id=0,i;
3828
  uint32_t sa02code;
3829
  uint32_t board;
3830
  uint32_t response[2]= {0,0};
3831
 
3832
  switch (event) {
3833
    case EVENT_COMMIT:
3834
 
3835
      switch (control) {
3836
        case P3_MUX0:
3837
          id=0;
3838
          break;
3839
        case P3_MUX1:
3840
          id=1;
3841
          break;
3842
        case P3_MUX2:
3843
          id=2;
3844
          break;
3845
        case P3_MUX3:
3846
          id=3;
3847
          break;
3848
        default:
3849
          id=0;
3850
      }
3851
      SetCtrlVal(panel,control,1);
3852
      sa02code = sa02GetCmdCode("MUX");
3853
      GetCtrlVal(p1h,P1_BOARDNUMBER,&board);
3854
      sa02Cmd(board,sa02code, id, 0, 0, 2,response);
3855
 
3856
 
3857
      for (i=0; i<4; i++) {
3858
        if (id!= i) {
3859
          SetCtrlVal(panel,cid[i],0);
3860
        }
3861
      }
3862
      sa02Printf("MUX %d\n",id);
3863
      break;
3864
  }
3865
  return 0;
3866
}
3867
 
3868
int CVICALLBACK UploadFromPanels (int panel, int control, int event,
3869
                                  void *callbackData, int eventData1, int eventData2) {
3870
  switch (event) {
3871
    case EVENT_COMMIT:
3872
      UploadFPGAParameters(panel,control,event,callbackData,eventData1,eventData2);
3873
      UploadChannelParameters(panel,control,event,callbackData,eventData1,eventData2);
3874
      UploadGlobalParameters(panel,control,event,callbackData,eventData1,eventData2);
3875
      break;
3876
  }
3877
  return 0;
3878
}
3879
 
3880
double erf(double x, double par[], int npar) {
3881
  double y=0;
3882
  double x0= (x-par[0])*par[1];
3883
  Erf(x0,&y);
3884
  return (y);
3885
}
3886
 
3887
int CVICALLBACK FitH2D (int panel, int control, int event,
3888
                        void *callbackData, int eventData1, int eventData2) {
3889
  char name[MAX_PATHNAME_LEN];
3890
 
3891
  switch (event) {
3892
    case EVENT_COMMIT: {
3893
      //sprintf(name ,"C:\\root\\bin\\root.exe");
3894
      int status;
3895
      char dfile[MAX_PATHNAME_LEN];
3896
      char efile[MAX_PATHNAME_LEN];
3897
 
3898
      status = FileSelectPopup ("data", "*.th2d", ".th2d",
3899
                                "Izberi datoteko s histogramom",
3900
                                VAL_LOAD_BUTTON, 0, 0, 1, 0, efile);
3901
      EscapeString(efile,dfile);
3902
      sprintf(name ,"C:/root/bin/root.exe ../macros/sa02fit.cxx(\\\"%s\\\")", dfile);
3903
 
3904
 
3905
 
3906
      sa02Printf("%s\n",name);
3907
 
3908
      LaunchExecutable(name);
3909
 
3910
 
3911
    }
3912
    break;
3913
  }
3914
  return 0;
3915
}
3916
 
3917
double Round(double x) {
3918
 
3919
  int ix= (int)x;
3920
  if (x>0) {
3921
    if (x - ix > 0.5 ) {
3922
      return ix+1;
3923
    } else {
3924
      return ix;
3925
    }
3926
  } else {
3927
    if (x - ix < -0.5 ) {
3928
      return ix-1;
3929
    } else {
3930
      return ix;
3931
    }
3932
  }
3933
 
3934
 
3935
}
3936
 
3937
//const double ffine    = -1.45; //  dac steps/offset unit  (fine)
3938
const double foffset  = -13.;  // dac steps/offset unit (coarse)
3939
const double ffine    = foffset/16.; //  dac steps/offset unit  (fine)
3940
 
3941
double sa02getshift(int offset, int fineadj_unipol ) {
3942
 
3943
  int c=offset;
3944
  int f=fineadj_unipol;
3945
  if (c>7) {
3946
    c-=16;
3947
  }
3948
  if (f>7) {
3949
    f-=16;
3950
  }
3951
  return foffset*c+ffine*f;
3952
}
3953
 
3954
double sa02getoffset(double x, double fx, int *dx) {
3955
 
3956
  *dx = (int) Round(x/ fx) ;
3957
  if (*dx>7) {
3958
    *dx=7;
3959
  }
3960
  if (*dx<-8) {
3961
    *dx=-8;
3962
  }
3963
  x=x-(*dx)*fx;
3964
  if (*dx<0) {
3965
    *dx+=16;
3966
  }
3967
  return x;
3968
}
3969
 
3970
//______________________________________________________________________________
3971
double GetMean(int fNpoints, double *fX, double *fY) {
3972
// Return mean value of X
3973
  int i;
3974
  double sumw  = 0;
3975
  double sumwx = 0;
3976
  if (fNpoints <= 0) {
3977
    return 0;
3978
  }
3979
 
3980
  for (i=0; i<fNpoints; i++) {
3981
    sumw += fY[i];
3982
    sumwx += fX[i]* fY[i];
3983
  }
3984
  return sumwx/sumw;
3985
}
3986
 
3987
//______________________________________________________________________________
3988
double GetRMS(int fNpoints, double *fX, double *fY) {
3989
// Return RMS of X
3990
 
3991
  int i;
3992
  double sumw = 0, sumwx = 0,mean,rms2;
3993
  double sumwx2 = 0;
3994
  if (fNpoints <= 0) {
3995
    return 0;
3996
  }
3997
 
3998
  for (i=0; i<fNpoints; i++) {
3999
    sumwx += fX[i]* fY[i];
4000
    sumw += fY[i];
4001
    sumwx2 += fX[i]* fX[i]* fY[i];
4002
 
4003
  }
4004
  if (sumw <= 0) {
4005
    return 0;
4006
  }
4007
  mean = sumwx/sumw;
4008
  rms2 = fabs(sumwx2/sumw -mean*mean);
4009
  return sqrt(rms2);
4010
}
4011
 
4012
 
4013
int FitGraph(int mode, int n, double *x, double *y, double *par) {
4014
  const double threshold=0.5;
4015
  ssize_t i,imax,imin;
4016
  double dmax,dmin;
4017
//  double rms=0;
4018
//  double sum=0;
4019
 
4020
  MaxMin1D(y,n,&dmax,&imax,&dmin,&imin);
4021
  switch (mode) {
4022
    case 0:
4023
      par[0]=x[imax];
4024
      par[1]=0;
4025
      break;
4026
    case 1:
4027
      for (i=0; i<n; i++)
4028
        if (y[i]>threshold) {
4029
          par[0]=x[i];
4030
        }
4031
      par[1]=0;
4032
      break;
4033
    case 2:
4034
      par[0]=GetMean(n,x,y);
4035
      par[1]=GetRMS(n,x,y);
4036
      break;
4037
    case 3:
4038
      break;
4039
    case 4: {
4040
      int npar=2;
4041
      double fitpar[2];
4042
      double rms;
4043
      NonLinearFit (y, x, datayfit,n, erf, fitpar, npar, &rms);
4044
      par[0]=0;
4045
      par[1]=0;
4046
      break;
4047
    }
4048
    default:
4049
      break;
4050
  }
4051
  return 0;
4052
}
4053
 
4054
int CVICALLBACK FitH2DCoarse (int panel, int control, int event,
4055
                              void *callbackData, int eventData1, int eventData2) {
4056
  double mean[144*2*4];
4057
  double rms[144*2*4];
4058
  int ix,iy;
4059
 
4060
  double fpar[3]= {0,0,0};
4061
  int h2=0;
4062
  switch (event) {
4063
    case EVENT_COMMIT: {
4064
      unsigned short offsets[144*2*4];
4065
      double x;
4066
      int offset=0, fineadj_unipol=0;
4067
      //unsigned short val;
4068
      double mean0,rms0;
4069
      uint16_t mask=GetConnectedFebMask();
4070
      int nch = H2DGetNbinsX(h2);
4071
      int npt = H2DGetNbinsY(h2);
4072
      int fitmode  =0;
4073
      double minx  =  H2DGetMinX(h2);
4074
      double stepx =  H2DGetStepX(h2);
4075
      GetCtrlVal(p3h,P3_FITMODE,&fitmode);
4076
      GetCtrlVal(p3h,P3_TARGETOFFSET,&mean0);
4077
      GetCtrlVal(p3h,P3_TARGETRMS,&rms0);
4078
      for (iy=0; iy < npt; iy++ ) {
4079
        datax[iy] = H2DGetYBinCenter(h2,iy);
4080
      }
4081
      GetTableCellRangeVals (p3h, P3_CREG, MakeRect (1, 4, 144*4, 2), offsets, VAL_ROW_MAJOR);
4082
      for (ix=0; ix < nch; ix++ ) {
4083
        if (!(mask & (1<<(ix/144)) )) {
4084
          mean[ix] = datax[0];
4085
          rms[ix]  = 0;
4086
          continue;
4087
        }
4088
        for (iy=0; iy < npt; iy++ ) {
4089
          datay[iy] = H2DGetBinContent(h2,ix,iy); // /H2DGetMax(h2);
4090
        }
4091
        FitGraph(fitmode, npt, datax , datay, fpar);
4092
        mean[ix]=fpar[0];
4093
        rms[ix] =fpar[1];
4094
        offset         = offsets[ix*2];
4095
        fineadj_unipol = offsets[ix*2+1];
4096
 
4097
        x =  sa02getshift(offset, fineadj_unipol);
4098
        x += (mean0-(mean[ix]+rms0*rms[ix]));
4099
        /*if (x<0) {
4100
          sa02Printf(" ch. %d mean+%f*sigma %g above threshold %f \n",ix, rms0,mean[ix]+rms0*rms[ix],mean0);
4101
        }*/
4102
        x = sa02getoffset(x, foffset, &offset);
4103
        x = sa02getoffset(x, ffine  , &fineadj_unipol);
4104
        //sa02Printf("offsets ch. %d mean=%f rms %f  shift=%f calcshift=%f offset %d fineadj %d\n",ix, mean[ix],rms[ix], x, sa02getshift(offset, fineadj_unipol),offset, fineadj_unipol);
4105
        offsets[ix*2]=(unsigned short) offset;
4106
        offsets[ix*2+1]=(unsigned short) fineadj_unipol;
4107
        ProcessSystemEvents();
4108
      }
4109
 
4110
      SetTableCellRangeVals (p3h, P3_CREG, MakeRect (1, 4, 144*4, 2), offsets, VAL_ROW_MAJOR);
4111
 
4112
 
4113
      if (nch>0) {
4114
        if (plothandle2dfit) {
4115
          DeleteGraphPlot (p1h, P1_GRAPH2D, plothandle2dfit, VAL_IMMEDIATE_DRAW);
4116
        }
4117
        plothandle2dfit = PlotWaveform (p1h, P1_GRAPH2D, mean, nch,
4118
                                        VAL_DOUBLE, 1.0, 0.0, minx,
4119
                                        stepx, VAL_FAT_LINE,
4120
                                        VAL_EMPTY_SQUARE, VAL_SOLID, 1,
4121
                                        VAL_YELLOW);
4122
        if (plothandleslix) {
4123
          DeleteGraphPlot (p1h, P1_GRAPHY, plothandleslix, VAL_IMMEDIATE_DRAW);
4124
        }
4125
 
4126
        plothandleslix = PlotWaveform (p1h, P1_GRAPHY, rms, nch,
4127
                                       VAL_DOUBLE, 1.0, 0.0, minx,
4128
                                       stepx, VAL_FAT_LINE,
4129
                                       VAL_EMPTY_SQUARE, VAL_SOLID, 1,
4130
                                       VAL_BLUE);
4131
        sa02Printf("offset calculated:\n");
4132
      }
4133
    }
4134
    break;
4135
  }
4136
  return 0;
4137
}
4138
 
4139
int CVICALLBACK LedCB (int panel, int control, int event,
4140
                       void *callbackData, int eventData1, int eventData2) {
4141
 
4142
  if (!gBELLEPTS)return 0;
4143
 
4144
  switch (event) {
4145
 
4146
    case EVENT_COMMIT: {
4147
      char saddress[0xFF];
4148
      uint32_t address;
4149
      uint32_t value=0;
4150
      GetCtrlVal(p3h,P3_ADDRESS, saddress);
4151
      address =  strtoul (saddress,NULL,0);
4152
      VME_A32D32_R(address+FEB_DEADBEEF, &value);
4153
      sa02Printf("READ at FEB_DEADBEEF 0x%08x\n",  value);
4154
 
4155
 
4156
      GetCtrlVal(p1h,P1_PTSLED,&value);
4157
      value++;
4158
      sa02Printf("LedCB ADDR 0x%08x VAL %d\n",address,  value);
4159
      //VME_A24D32_W(address,&value);
4160
 
4161
      VME_A32D32_W(address,value);
4162
      /*
4163
      NIM standard level ports.
4164
 
4165
            You should write 0x7600 to address : baseaddress + 4 .
4166
 
4167
            0x7600 means the connection
4168
            CLKOUT1 -> 7 -> CLK_VOUT1 (VOUT1 pin of FPGA)
4169
            CLKOUT0 -> 6 -> CLK_VOUT0 (VOUT1 pin of FPGA)
4170
            SCLK    -> 0 -> CLK_IN    (internal clock)
4171
            PCLK    -> 0 -> CLK_IN    (internal clock)
4172
      */
4173
 
4174
      if (value==2) {
4175
        value=0x7600;
4176
      } else {
4177
        value=0;
4178
      }
4179
      VME_A32D32_W(address+4,value); // enable outputs
4180
    }
4181
    sa02Printf("SizeOf(Double)=%d\n",sizeof(double));
4182
    break;
4183
  }
4184
  return 0;
4185
}
4186
 
4187
int CVICALLBACK SetPositionAndMux (int panel, int control, int event,
4188
                                   void *callbackData, int eventData1, int eventData2) {
4189
  const float fx= (float)(1000./0.3595); // 4M scaling factor steps/mm
4190
  int chx,x0,chy,y0;
4191
  float gapx,gapy, dx , dy;
4192
 
4193
  switch (event) {
4194
    case EVENT_COMMIT:
4195
      GetCtrlVal (p2h, P2_CHX,  &chx);
4196
      GetCtrlVal (p2h, P2_CHY,  &chy);
4197
      GetCtrlVal (p2h, P2_GAPX,  &gapx);
4198
      GetCtrlVal (p2h, P2_GAPX,  &gapy);
4199
      GetCtrlVal (p2h, P2_DX, &dx);
4200
      GetCtrlVal (p2h, P2_DX, &dy);
4201
      GetCtrlVal (p2h, P2_XC,  &x0);
4202
      GetCtrlVal (p2h, P2_YC,  &y0);
4203
      y0 = (int)(y0 - 5.5* fx * dy  - gapy * fx * 0.5);
4204
      x0 = (int)(x0 - 5.5* fx * dx  - gapx * fx * 0.5);
4205
      if (gMIKRO_Y) {
4206
        posrec.yset =  (int32_t)(y0+dy *fx * chy);
4207
        if (chy>5) {
4208
          posrec.yset +=gapy * fx;
4209
        }
4210
        MIKRO_MoveTo (MIKRO_Y, posrec.yset);
4211
        sa02Printf("->MIKRO_MoveTo (2, y);%d\n",posrec.yset);
4212
      }
4213
      if (gMIKRO_X) {
4214
        posrec.xset=(int32_t)(x0+dx*fx*chx);
4215
        if (chx>5) {
4216
          posrec.xset +=gapx * fx;
4217
        }
4218
        MIKRO_MoveTo (MIKRO_X, posrec.xset);
4219
        sa02Printf("->MIKRO_MoveTo (1, x);%d\n",posrec.xset);
4220
      }
4221
//      GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
4222
      SetCMon(chx,chy);
4223
      break;
4224
  }
4225
  return 0;
4226
}
4227
 
4228
int CVICALLBACK SetCenter (int panel, int control, int event,
4229
                           void *callbackData, int eventData1, int eventData2) {
4230
  int x0,y0;
4231
  switch (event) {
4232
    case EVENT_COMMIT:
4233
      GetCtrlVal (p2h, P2_XC,  &x0);
4234
      GetCtrlVal (p2h, P2_YC,  &y0);
4235
      if (gMIKRO_X)  MIKRO_MoveTo (MIKRO_X, x0);
4236
      if (gMIKRO_Y)  MIKRO_MoveTo (MIKRO_Y, y0);
4237
      break;
4238
  }
4239
  return 0;
4240
}
4241
 
4242
void CVICALLBACK EndOfThread ( CmtThreadPoolHandle poolhandle,
4243
                               CmtThreadFunctionID functionID, unsigned int event,
4244
                               int value, void *callbackData  ) {
4245
 
4246
  daq_on=0;
4247
  SetDimming(0);
4248
  sa02Printf("End of Thread \n");
4249
  return ;
4250
 
4251
}
4252
 
4253
int Asic_TENB_Shift( void ) {
4254
 
4255
  int i,stanje;
4256
  unsigned short inmask[144], outmask[144], tmp;
4257
  for (int board = 0; board<4; board++) {
4258
    stanje = GetTableCellRangeVals (p3h, P3_CREG, MakeRect (1+board*144, 7, 144, 1),
4259
                                    inmask, VAL_COLUMN_MAJOR);
4260
    tmp = inmask[143];
4261
    for (i=0; i<143; i++) {
4262
      outmask[i+1]=inmask[i];
4263
    }
4264
    outmask[0]=tmp;
4265
 
4266
    stanje = SetTableCellRangeVals (p3h, P3_CREG, MakeRect (1+board*144, 7, 144, 1),
4267
                                    outmask, VAL_COLUMN_MAJOR);
4268
 
4269
  }
4270
  return 0;
4271
}
4272
 
4273
int CVICALLBACK daq_scanpar (void *functionData) {
4274
 
4275
 
4276
  char filename[0xFF];
4277
  int scanpar=0;
4278
  int ix, x0,dx,nx;
4279
  int value,state;
4280
  Rect save_range,trange;
4281
  int cid=0;
4282
  int daqexe;
4283
  time_t t,told=0, tstart;
4284
  FILE *fp;
4285
  int spar;
4286
  int nch;
4287
  const int maxrange[20]= {0,0,8,16,16,16,2,2,2,0, 4,4,4,2,256,4,512};
4288
 
4289
  trange.top=0;
4290
  trange.left=0;
4291
 
4292
  GetCtrlVal(p3h,P3_SCANPAR, &scanpar);
4293
  sa02Printf("%d\n",scanpar);
4294
  GetCtrlVal(p3h,P3_X0, &x0);
4295
  GetCtrlVal(p3h,P3_DX, &dx);
4296
  GetCtrlVal(p3h,P3_NX, &nx);
4297
  GetCtrlVal(p3h,P3_DAQEXE,&daqexe);
4298
  GetCtrlVal(p1h,P1_OUTPUTFILE, filename);
4299
 
4300
 
4301
  if (!scanpar) {
4302
    return 0;
4303
  }
4304
  if (scanpar>10) {
4305
    cid=P3_GREG;
4306
    spar=scanpar-10;
4307
    nch=4*4;
4308
 
4309
  } else {
4310
    cid=P3_CREG;
4311
    spar=scanpar;
4312
    nch=144*4;
4313
 
4314
  }
4315
  if (spar==1) {
4316
    spar=7;
4317
  }
4318
  sa02Printf("Range:%d\n",maxrange[scanpar-1]);
4319
  state = GetTableSelection (p3h, cid, &save_range);
4320
 
4321
  trange = MakeRect (1, spar, nch, 1);
4322
  state = SetTableSelection (p3h, cid, trange);
4323
  if ((trange.top!=0)&&(trange.left!=0)) {
4324
 
4325
 
4326
 
4327
    time(&t);
4328
    tstart=t;
4329
    if (daqexe) {
4330
      iteratorrec.id = ITERATORREC_ID;
4331
      iteratorrec.len = sizeof(iteratorrec);
4332
      iteratorrec.value = x0;
4333
      iteratorrec.n     = nx;
4334
      iteratorrec.step  = dx;
4335
      iteratorrec.level = 2;
4336
      fp = fopen(filename, "ab");
4337
      if(fp) {
4338
        fwrite (&datrec, 1, datrec.len, fp);
4339
        fclose(fp);
4340
      }
4341
      sa02Printf("new ITERATORREC recid=0x%x\n", iteratorrec.id);
4342
    }
4343
 
4344
 
4345
    for (ix=0; ix<nx; ix++) {
4346
      value = ix*dx + x0;
4347
      if (scanpar!=1) {
4348
        state = FillTableCellRange (p3h, cid, MakeRect (1, spar, nch, 1), value%maxrange[scanpar-1]);
4349
        if (maxrange[scanpar-1] && value/maxrange[scanpar-1]) {
4350
          state = FillTableCellRange (p3h, cid, MakeRect (1, spar-1, nch, 1), value/maxrange[scanpar-1]);
4351
        }
4352
      }
4353
      switch (cid) {
4354
        case P3_CREG:
4355
          UploadChannelParameters(p3h,cid,EVENT_COMMIT,functionData,0,0);
4356
          break;
4357
        case P3_GREG:
4358
          UploadGlobalParameters (p3h,cid,EVENT_COMMIT,functionData,0,0);
4359
          break;
4360
      }
4361
      if (scanpar==1) {
4362
        Asic_TENB_Shift();
4363
      }
4364
      if (t!=told  ) {
4365
        ProcessSystemEvents ();
4366
      }
4367
      if (ctrl_c) {
4368
        break;
4369
      }
4370
 
4371
      if (daqexe) {
4372
        datrec.id = DATREC_ID;
4373
        datrec.len = sizeof(datrec);
4374
        datrec.cmd    =0xBEEF0000+ scanpar;
4375
        datrec.data   =value;
4376
        datrec.chip   =-1;
4377
        datrec.channel=-1;
4378
        datrec.retval =value;
4379
 
4380
        fp = fopen(filename, "ab");
4381
        if(fp) {
4382
          fwrite (&datrec, 1, datrec.len, fp);
4383
          fclose(fp);
4384
        }
4385
        sa02Printf("new DATREC recid=0x%x  datrec->cmd=0x%x\n", datrec.id , datrec.cmd);
4386
        daq(NULL);
4387
        sa02Printf("H2D image saved as %s\n", filename);
4388
 
4389
      }
4390
      if (ctrl_c) {
4391
        break;
4392
      }
4393
 
4394
      if (t!=told  ) {
4395
        ProcessSystemEvents ();
4396
      }
4397
      told=t;
4398
      time(&t);
4399
 
4400
    }
4401
  }
4402
  state = SetTableSelection (p3h, cid, save_range);
4403
 
4404
 
4405
 
4406
 
4407
 
4408
  return 0;
4409
}
4410
 
4411
 
4412
int CVICALLBACK ExportParameters (int panel, int control, int event,
4413
                                  void *callbackData, int eventData1, int eventData2) {
4414
  int status;
4415
  char filename[MAX_PATHNAME_LEN];
4416
  switch (event) {
4417
    case EVENT_COMMIT:
4418
 
4419
      status = FileSelectPopup ("./parameters/", "*.param", "*.param",
4420
                                "Export Parameters to file", VAL_SAVE_BUTTON, 0,
4421
                                0, 1, 1, filename);
4422
      sa02Printf("ExportParameters to %d\n",MAX_PATHNAME_LEN);
4423
      switch (status) {
4424
        case 1:
4425
          MessagePopup ("Warning", "File exist. Remove it first or choose another file");
4426
          break;
4427
        case 2: {
4428
          int n,i,row,asic,ch;
4429
          unsigned short val;
4430
          time_t t;
4431
          char buf[MAX_PATHNAME_LEN];
4432
          FILE   *fp = fopen(filename, "w");
4433
          if (fp) {
4434
            //--------------------------------------------------- Parameters header
4435
            time(&t);
4436
            fprintf(fp, "#Parameter exported from CVI %s\n",ctime(&t) );
4437
            //--------------------------------------------------- FPGA parameters
4438
            GetNumTextBoxLines(p3h, P3_FPGAPAR,&n);
4439
            for (i=0; i<n; i++) {
4440
              GetTextBoxLine(p3h, P3_FPGAPAR, i, buf);
4441
              fprintf(fp, "%s\n",buf);
4442
            }
4443
            //--------------------------------------------------- Global parameters
4444
            for (row=1; row<1+16; row++) {
4445
              int irow = (row-1)%4;
4446
              int iboard = (row-1)/4;
4447
              if ( (row-1)%4 == 0 ) fprintf(fp, "param_board %d\n",iboard);
4448
              fprintf(fp, "## global parameter for chip %d\n",(row-1)%4);
4449
              fprintf(fp, "param_global %d 0x1ffff\n",irow);
4450
              GetTableCellVal (p3h, P3_GREG, MakePoint (1,row), &val);
4451
              fprintf(fp, "phasecmps %d 0x%x\n",irow,val);
4452
              GetTableCellVal (p3h, P3_GREG, MakePoint (2,row), &val);
4453
              fprintf(fp, "gain %d 0x%x\n",irow,val);
4454
              GetTableCellVal (p3h, P3_GREG, MakePoint (3,row), &val);
4455
              fprintf(fp, "shapingtime %d 0x%x\n",irow,val);
4456
              GetTableCellVal (p3h, P3_GREG, MakePoint (4,row), &val);
4457
              fprintf(fp, "comparator %d 0x%x\n",irow,val);
4458
              GetTableCellVal (p3h, P3_GREG, MakePoint (5,row), &val);
4459
              fprintf(fp, "vrdrive %d 0x%x\n",irow,val);
4460
              GetTableCellVal (p3h, P3_GREG, MakePoint (6,row), &val);
4461
              fprintf(fp, "monitor %d 0x%x\n",irow,val);
4462
              GetTableCellVal (p3h, P3_GREG, MakePoint (7,row), &val);
4463
              fprintf(fp, "id %d 0x%x\n",irow,val);
4464
 
4465
              fprintf(fp, "load_global  %d\n\n\n",irow);
4466
            }
4467
 
4468
            //--------------------------------------------------- Channel parameters
4469
            for (i=0; i<144*4; i++) {
4470
              int board = i/144;
4471
              int j= i%144;
4472
              asic=(j/36);
4473
              ch=j%36;
4474
              row=(i+1);
4475
              if (i%36==0) {
4476
                fprintf(fp, "# channel parameter for chip %d\n\n",asic);
4477
              }
4478
 
4479
              if (i%144 == 0) fprintf(fp, "param_board %d\n",board);
4480
              fprintf(fp, "param_ch       %d %d 0x0000\n",asic,ch);
4481
 
4482
              GetTableCellVal (p3h, P3_CREG, MakePoint (3,row), &val);
4483
              fprintf(fp, "decaytime %d %d 0x%x\n",asic,ch,val);
4484
              GetTableCellVal (p3h, P3_CREG, MakePoint (4,row), &val);
4485
              fprintf(fp, "offset %d %d 0x%x\n",asic,ch,val);
4486
              GetTableCellVal (p3h, P3_CREG, MakePoint (5,row), &val);
4487
              fprintf(fp, "fineadj_unipol %d %d 0x%x\n",asic,ch,val);
4488
              GetTableCellVal (p3h, P3_CREG, MakePoint (6,row), &val);
4489
              fprintf(fp, "fineadj_diff %d %d 0x%x\n",asic,ch,val);
4490
              GetTableCellVal (p3h, P3_CREG, MakePoint (7,row), &val);
4491
              fprintf(fp, "tpenb %d %d 0x%x\n",asic,ch,val);
4492
              GetTableCellVal (p3h, P3_CREG, MakePoint (8,row), &val);
4493
              fprintf(fp, "kill %d %d 0x%x\n",asic,ch,val);
4494
              fprintf(fp, "load_ch  %d %d\n\n\n",asic,ch);
4495
            }
4496
 
4497
            fclose(fp);
4498
 
4499
          }
4500
          break;
4501
        }
4502
      }
4503
 
4504
      break;
4505
  }
4506
  return 0;
4507
}
4508
 
4509
 
4510
 
4511
int ProcessUserEvent(int pID, int rID,int mode){    
4512
    ThreadFunctionPtr mythread = NULL;
4513
    if (pID ==p1h && rID == P1_DAQ            ) mythread=daq;
4514
    if (pID ==p1h && rID == P1_READOUT        ) mythread=daq_readonly;
4515
    if (pID ==p1h && rID == P1_FPGAWRITE      ) mythread=MultiFpgaWrite;
4516
    if (pID ==p1h && rID == P1_MULTIFPGAWRITE ) mythread=MultiFpgaWrite;
4517
    if (pID ==p1h && rID == P1_TESTING        ) mythread=Testing;
4518
    if (pID ==p2h && rID == P2_DAQ            ) mythread=daq_scan;
4519
    if (pID ==p6h && rID == MINIRICH_START    ) mythread=daq;
4520
    if (pID ==p2h && rID == P2_RUNSCRIPT      ) {
4521
      char scriptname[MAX_PATHNAME_LEN] ;
4522
 
4523
      int status = FileSelectPopup ("./scripts/", "*.txt", "*.txt",
4524
                                    "Select Script file", VAL_LOAD_BUTTON, 0, 0,
4525
                                    1, 0, scriptname);
4526
      if (status) {
4527
        SetCtrlVal(p1h, P1_SCRIPTNAME, scriptname );
4528
        mythread=run_script;
4529
      }
4530
    }
4531
    if (pID ==p1h && rID == P1_RUNSCRIPT      ) mythread=run_script;
4532
    if (pID ==p3h && rID == P3_DAQ            ) mythread=daq_scanpar;
4533
    if (pID ==p4h && rID == P4_DAQ            ) mythread=V729_daq;
4534
    if (mythread!=NULL) {
4535
      sa02Printf("New Thread panel=%d button=%d\n", pID, rID);
4536
      ctrl_c=0;
4537
      daq_on = 1;
4538
      SetDimming(1);
4539
      if (mode){
4540
        CmtScheduleThreadPoolFunctionAdv (poolHandle, mythread, &rID,
4541
                                        DEFAULT_THREAD_PRIORITY,
4542
                                        EndOfThread,
4543
                                        EVENT_TP_THREAD_FUNCTION_END,
4544
                                        NULL, RUN_IN_SCHEDULED_THREAD,
4545
                                        &tfID);
4546
      } else {
4547
        mythread(NULL);
4548
      }  
4549
    }
4550
 
4551
    if ( pID==p1h && rID == P1_SLOWC ) {
4552
      uint32_t board;
4553
      GetCtrlVal(p1h,P1_BOARDNUMBER, &board);
4554
      SlowControl(board, NULL);
4555
    }
4556
    // if ( pID==p1h && rID == P1_STEPONE )       StepOne();
4557
    if ( pID==p1h && rID == P1_FEBTESTANA ) FebTestAna();
4558
    if ( pID==p1h && rID == P1_TEST )       FebTest();
4559
    if ( pID==p1h && rID == P1_MODULETEST ) ModuleTest();
4560
 
4561
    if ( pID==p1h && rID == P1_GET_FPGA_SERIAL ) {
4562
      int ison=0;
4563
      GetCtrlVal(p1h,P1_BOARDTYPE,&sa02BoardType);
4564
      for (int board=0; board<4; board++) {
4565
        char saddress[0xff]="";
4566
        GetCtrlVal(p1h, hapd_onoff[board], &ison);
4567
        sa02GetSerial(board, saddress);
4568
        sa02Printf("SERIAL FPGA = %s \n", saddress);
4569
        SetCtrlVal(p1h,fpga_serials[board],saddress);
4570
      }
4571
    };
4572
 
4573
    if ( ( pID==p1h && rID == P1_STOP )
4574
         || ( pID==p2h && rID == P2_STOP )
4575
         || ( pID==p3h && rID == P3_STOP )  
4576
         || ( pID==p6h && rID == MINIRICH_STOP )  
4577
         || ( pID==p4h && rID == P4_STOP ) ) {
4578
      sa02Printf("Stopping the  Thread %d\n", tfID);
4579
      ctrl_c=1;
4580
    }
4581
    if (pID ==p5h) {
4582
      if (rID == P5_SET_DAC_HV_ON) set_dac(1);
4583
      if (rID == P5_SET_DAC_HV_OFF) set_dac(0);
4584
      if (rID == P5_SET_HV_ON) set_hv(1);
4585
      if (rID == P5_SET_HV_OFF) set_hv(0);
4586
    }
4587
    return 0;
4588
}
4589
 
4590
 
4591
 
4592
void CVICALLBACK QueueUserEventCallback (CmtTSQHandle queueHandle, unsigned int event, int value, void *callbackData) {
4593
  //int *data= (int *)  callbackData;
4594
  int mdata[2];
4595
  CmtReadTSQData (queueHandle, mdata, 1, 0, 0);
4596
  sa02Printf("QueueUserEvent --->TSQ  %d %d\n", mdata[0],mdata[1]);
4597
  QueueUserEvent (1001, mdata[0], mdata[1]);
4598
}
4599
 
4600
/*************************** MAIN ***************************/
4601
 
4602
int __stdcall WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
4603
                       LPSTR lpszCmdLine, int nCmdShow) {
4604
 
4605
  char title[0xFF];
4606
  char saddress[0xff]="";
4607
  //uint32_t board;
4608
  int i;
4609
  int status=0;
4610
 
4611
  if (InitCVIRTE (hInstance, 0, 0) == 0) {
4612
    return -1;  /* out of memory */
4613
  }
4614
 
4615
  SetSleepPolicy(VAL_SLEEP_MORE);
4616
  CmtNewThreadPool (MAX_THREADS,  &poolHandle);
4617
 
4618
  if ( (status = CmtNewTSQ (1, 2*sizeof(int), OPT_TSQ_AUTO_FLUSH_ALL, &pTSQ)) <0)
4619
    printf("CmtNewTSQ cannot be installed\n");
4620
  if ( (status = CmtInstallTSQCallback (pTSQ, EVENT_TSQ_ITEMS_IN_QUEUE, EVENT_TSQ_QUEUE_SIZE,
4621
                                       QueueUserEventCallback, pTSQData, CmtGetCurrentThreadID(), NULL))  <0)
4622
    printf("CmtInstallTSQCallback cannot be installed\n");  ;
4623
 
4624
  SetStdioPort (CVI_STDIO_WINDOW );
4625
 
4626
  readIni("febdaq.ini");
4627
 
4628
  VME_START(gVME_CONTROLLER);
4629
  if ( gCAEN_V288 ) {
4630
    V288_Map(0,gCAEN_V288);
4631
    V288_Init(0);
4632
  }
4633
 
4634
  if (gMIKRO_PORT) {
4635
    MIKRO_Open (gMIKRO_PORT);
4636
    if (gMIKRO_X) MIKRO_Init (gMIKRO_X,0);
4637
    if (gMIKRO_Y) MIKRO_Init (gMIKRO_Y,0);
4638
    if (gMIKRO_Z) MIKRO_Init (gMIKRO_Z,0);
4639
  }
4640
 
4641
  if ((p1h = LoadPanel (0, "sa02_CVI.uir", P1)) < 0) return -1;
4642
  if ((p2h = LoadPanel (0, "sa02_CVI.uir", P2)) < 0) return -1;
4643
  if ((p3h = LoadPanel (0, "sa02_CVI.uir", P3)) < 0) return -1;
4644
  if ((p4h = V729_LoadPanel (0, "CAEN_V729\\CAEN_V729_CVI.uir", P4)) < 0) return -1;
4645
  if ((p5h = LoadPanel (0, "sa02_CVI.uir", P5)) < 0) return -1;
4646
  if ((p6h = LoadPanel (0, "ICFA\\minirich.uir", MINIRICH)) < 0) return -1;
4647
  if ((pm1 = LoadMenuBar (p1h, "sa02_CVI.uir", MENU)) < 0)  return -1;
4648
 
4649
  SetPanelMenuBar(p1h, pm1);
4650
  DisplayPanel (p1h);
4651
 
4652
  LoadUirHeader("sa02_CVI.h");
4653
  LoadUirHeader("CAEN_V729\\CAEN_V729_CVI.h");
4654
 
4655
  SetCtrlVal(p2h,P2_XC,gCENTER_X);
4656
  SetCtrlVal(p2h,P2_YC,gCENTER_Y);
4657
 
4658
  SetCtrlVal(p3h, P3_INPUTFILE,gFEBParam);
4659
  SetParametersFromFile(gFEBParam);
4660
 
4661
  SetCtrlAttribute (p1h, P1_GRAPH2D, ATTR_CALLBACK_DATA, (void *)integer_val);
4662
  SetCtrlAttribute (p1h, P1_SLIY, ATTR_CALLBACK_DATA, (void *)integer_val);
4663
  SetCtrlAttribute (p1h, P1_SLIX, ATTR_CALLBACK_DATA, (void *)integer_val);
4664
  SetCtrlAttribute (p1h, P1_NSLIY, ATTR_CALLBACK_DATA, (void *)integer_val);
4665
  SetCtrlAttribute (p1h, P1_NSLIX, ATTR_CALLBACK_DATA, (void *)integer_val);
4666
 
4667
  for (i=0; i<12; i++) {
4668
    SetTraceAttributeEx (p1h, chart_control[0], i+1, ATTR_TRACE_LG_TEXT, (char *) slowcname[i]);
4669
  }
4670
 
4671
  GetPanelAttribute (p1h, ATTR_TITLE, title );
4672
  if (gVME_CONTROLLER == WIENER_VMEMM) sprintf( title, "%s + WIENER_VMEMM", title );
4673
  if (gVME_CONTROLLER == WIENER_VMUSB) sprintf( title, "%s + WIENER_VMUSB", title );
4674
  if (gVME_CONTROLLER == CAEN_V1718) sprintf( title, "%s + CAEN_V1718", title );
4675
  if (gCAEN_V1495) sprintf( title, "%s + CAEN_V1495", title );
4676
  if (gCAEN_V288 ) sprintf( title, "%s + CAEN_V288", title );
4677
 
4678
  if (gBELLEPTS) {
4679
    sprintf( title, "%s + BELLEPTS", title );
4680
    sprintf(saddress,"0x%08x", gBELLEPTS );
4681
    SetCtrlVal(p3h,P3_ADDRESS,saddress );
4682
  }
4683
  if (gMIKRO_PORT)
4684
    sprintf( title, "%s + USE_MIKRO", title );
4685
  else
4686
    sprintf( title, "%s + MIKRO not used", title );
4687
  SetPanelAttribute (p1h, ATTR_TITLE, title );
4688
 
4689
  for (i=0; i<4; i++)
4690
    SetCtrlVal(p1h,hapd_onoff[i],gFEBMask&(1<<i));
4691
  SetCtrlVal(p1h,P1_SENDSWTRIG,gTriggerType);
4692
  SetCtrlVal(p1h,P1_TPENB,CHECK_BIT(uInterf,0));
4693
 
4694
  sa02SetAddress(strtoul (saddress,NULL,0));
4695
 
4696
  LedCB(p1h,P1_PTSLED,EVENT_COMMIT, NULL,0,0);
4697
 
4698
 
4699
  StdIo2FileCB (p1h, P1_STDIOLOG, EVENT_COMMIT, NULL,0,0);
4700
  InitColors();
4701
  sa02Printf("Panels=%d %d %d %d\n", p1h, p2h,p3h,p4h);
4702
  GetCtrlVal(p1h,P1_VERBOSE,&sa02Verbose);
4703
 
4704
  LoadElectronicMap("eid2hapdxy.map");
4705
  icfa_Init();
4706
 
4707
 
4708
  loop_on=1;
4709
  do {
4710
    GetUserEvent (1, &pID, &rID);  
4711
    ProcessUserEvent(pID,rID,1);
4712
  } while (loop_on);
4713
 
4714
  CmtDiscardThreadPool (poolHandle);
4715
  DiscardPanel (p4h);
4716
  DiscardPanel (p3h);
4717
  DiscardPanel (p2h);
4718
  DiscardPanel (p1h);
4719
 
4720
  if (gMIKRO_PORT) MIKRO_Close ();
4721
 
4722
 
4723
  VME_STOP();
4724
  return 0;
4725
}
4726
 
4727
int CVICALLBACK ResetStdOut (int panel, int control, int event,
4728
                             void *callbackData, int eventData1, int eventData2) {
4729
  switch (event) {
4730
    case EVENT_COMMIT:
4731
      ResetTextBox (p1h,P1_STDIO,"");
4732
      break;
4733
  }
4734
  return 0;
4735
}
4736
 
4737
int CVICALLBACK TrgHvMon (int panel, int control, int event,
4738
                          void *callbackData, int eventData1, int eventData2) {
4739
  switch (event) {
4740
    case EVENT_TIMER_TICK:
4741
      hvmon=1;
4742
      break;
4743
  }
4744
  return 0;
4745
}
4746
 
4747
 
4748
//---------------------------------------------------------------------
4749
 
4750
int Pts_write(uint32_t addr, uint32_t data ) {
4751
  VME_A32D32_W(addr,data);
4752
  return 0;
4753
}
4754
 
4755
int Pts_Mwrite(uint32_t addr, uint32_t data ) {
4756
  VME_MW(VME_A32, VME_D32, addr,data);
4757
  return 0;
4758
}
4759
 
4760
int Pts_read(uint32_t addr, uint32_t *data ) {
4761
  VME_A32D32_R(addr,data);
4762
  return 0;
4763
}
4764
 
4765
int Pts_Mread(uint32_t addr, uint32_t *data ) {
4766
  VME_MRRST();
4767
  VME_MR(VME_A32, VME_D32,addr, data);
4768
  VME_MREXEC(data);
4769
  return 0;
4770
}
4771
 
4772
 
4773
int Pts_erase( uint32_t addr, int verbose ) {
4774
  uint32_t dum;
4775
 
4776
  Pts_write( addr + ADR_CSR1, 0 );
4777
  Delay(0.1);
4778
  Pts_read( addr +ADR_CSR1, &dum);
4779
  if( verbose ) {
4780
    sa02Printf( "CSR1(0x%02x) = 0x%04x\n", ADR_CSR1,dum & 0xffff );
4781
 
4782
  }
4783
  Pts_write( addr +ADR_CSR1, CSR1_PROGRAM_ );
4784
  Delay(0.1);
4785
  Pts_read( addr +ADR_CSR1, &dum);
4786
  if( verbose ) {
4787
    sa02Printf( "CSR1(0x%02x) = 0x%04x\n", ADR_CSR1, dum & 0xffff );
4788
 
4789
  }
4790
  return 1;
4791
}
4792
 
4793
int Pts_configure_bit(uint32_t addr, const char *filename, int mode, int verbose ) {
4794
  int c,j;
4795
  int dummyword;
4796
  FILE *fp;
4797
  const long byte_per_dot = BYTE_PER_DOT;
4798
  unsigned long nchar = 0;
4799
 
4800
  fp = fopen(filename, "rb");
4801
  if( fp == NULL ) {
4802
    if( verbose ) {
4803
      sa02Printf(  "cannot open \"%s\"\n", filename );
4804
    }
4805
    return -1;
4806
  }
4807
  if(verbose) sa02Printf(  "file \"%s\" opened.\n", filename );
4808
 
4809
  /* ------------------------------------------------------------ *\
4810
    The data for the configuration start from 0xffff_ffff_aa99_aa66
4811
    ( cf. xapp138; we don't know the definition of the BIT file )
4812
  \* ------------------------------------------------------------ */
4813
  dummyword = 0;
4814
  do {
4815
    if( (c = getc( fp )) == EOF ) {
4816
      if(verbose) {
4817
        sa02Printf( "EOF detected. Exit.\n");
4818
 
4819
 
4820
      }
4821
      return -1;
4822
    }
4823
    (c == 0xff) ? dummyword++ : (dummyword=0);
4824
  } while( dummyword < 4 );
4825
 
4826
  if( mode == SLAVESERIAL_MODE ) {
4827
    if(verbose)  sa02Printf("slave serial mode");
4828
    Pts_write( addr +ADR_MODE, mode );
4829
    Pts_erase( addr, verbose );
4830
    for( j=0; j<32; j++ ) Pts_write( addr + ADR_CFG, 0x1 );
4831
    while( (c=getc(fp))!=EOF ) {
4832
      for( j=0; j<8; j++ ) Pts_write( addr + ADR_CFG, (c>>(7-j))&0x1 );
4833
      nchar++;
4834
      if( verbose && nchar%byte_per_dot==0 ) {
4835
        sa02Printf( "#");
4836
      }
4837
    }
4838
  } else if( mode == SELECTMAP_MODE ) {
4839
    if( verbose ) sa02Printf("select map mode\n");
4840
    Pts_write( addr + ADR_MODE, SELECTMAP_MODE );
4841
    Pts_erase( addr, verbose );
4842
    VME_MWRST();
4843
    for( j=0; j<4; j++ ) Pts_Mwrite( addr + ADR_CFG, 0xff );
4844
    VME_MWEXEC();
4845
 
4846
    VME_MWRST();
4847
    while( (c=getc(fp))!=EOF ) {
4848
      int cc = 0;
4849
      for(j=0; j<8; j++) cc |= ((c&(1<<j))>>j)<<(7-j);
4850
      Pts_Mwrite( addr + ADR_CFG, cc );
4851
      nchar++;
4852
      if( verbose && nchar%byte_per_dot==0 ) {
4853
        VME_MWEXEC();
4854
        VME_MWRST();
4855
        sa02Printf( "#");
4856
 
4857
      }
4858
    }
4859
    VME_MWEXEC();
4860
  } else {
4861
    if(verbose) {
4862
      sa02Printf( "\nIllegal mode\n");
4863
 
4864
    }
4865
    return -1;
4866
  }
4867
  if(verbose) {
4868
    sa02Printf("\ntotal %ld bits\n", nchar);
4869
  }
4870
  fclose(fp);
4871
  return Pts_check_configure( addr, verbose );
4872
}
4873
 
4874
int Pts_check_configure( uint32_t addr ,int verbose ) {
4875
  uint32_t csr1_value;
4876
  Pts_read(addr + ADR_CSR1,&csr1_value);
4877
  if(verbose) {
4878
    sa02Printf("CSR1(0x%02x)=0x%04x\n",ADR_CSR1,csr1_value&0xffff);
4879
  }
4880
  if(csr1_value&CSR1_DONE) {
4881
    if(verbose) sa02Printf("configure complete.\n");
4882
    return 1;
4883
  } else {
4884
    if(verbose)  sa02Printf("configure not complete.");
4885
    return -1;
4886
  }
4887
}
4888
 
4889
 
4890
int CVICALLBACK PtsDownloadCB (int panel, int control, int event,
4891
                               void *callbackData, int eventData1, int eventData2) {
4892
  char filename[254];
4893
  int mode=0;
4894
  char saddress[0xFF];
4895
  uint32_t addr;
4896
 
4897
 
4898
  switch (event) {
4899
    case EVENT_COMMIT:
4900
      GetCtrlVal(p3h,P3_ADDRESS, saddress);
4901
      addr=  strtoul (saddress,NULL,0);
4902
      GetCtrlVal(p3h,P3_PTSFIRMWARE,filename);
4903
      GetCtrlVal(p3h,P3_PTSMODE,&mode);
4904
      if(VME_CONNECTED() >=0 ) {
4905
        Pts_configure_bit( addr , filename, mode,  1 );
4906
      } else {
4907
        MessagePopup ("Warning", "Connect VME!!");
4908
      }
4909
      break;
4910
  }
4911
  return 0;
4912
}
4913
 
4914
 
4915
 
4916
int CVICALLBACK SelectPtsOutputCB (int panel, int control, int event,
4917
                                   void *callbackData, int eventData1, int eventData2) {
4918
  switch (event) {
4919
    case EVENT_COMMIT: {
4920
      unsigned short value;
4921
      GetCtrlVal(panel,control,&value);
4922
      sa02Printf("Selecting Pts Output Channel %d\n",value);
4923
      Sa02SetPtsOutput(value);
4924
      break;
4925
    }
4926
  }
4927
  return 0;
4928
}
4929
 
4930
int CVICALLBACK SendTriggerTypeCB (int panel, int control, int event,
4931
                                   void *callbackData, int eventData1, int eventData2) {
4932
  switch (event) {
4933
    case EVENT_COMMIT: {
4934
      int trglen, trg;
4935
      uint16_t mask;
4936
      //int ison;
4937
      GetCtrlVal(p1h,P1_SENDSWTRIG,&trg);
4938
      GetCtrlVal(p1h,P1_INTTRGLEN, &trglen);
4939
      mask=GetConnectedFebMask();
4940
      sa02Printf("Selecting Trigger %d length of the internal triger %d mask =%04x\n", trg, trglen);
4941
      Sa02SelectTriggerWithMaskAndLength (trg, mask, trglen);
4942
 
4943
      break;
4944
    }
4945
  }
4946
  return 0;
4947
}
4948
 
4949
int CVICALLBACK StdIo2FileCB (int panel, int control, int event,
4950
                              void *callbackData, int eventData1, int eventData2) {
4951
  switch (event) {
4952
    case EVENT_COMMIT:
4953
      GetCtrlVal(p1h,P1_STDIOLOG, &gLog);
4954
      break;
4955
  }
4956
  return 0;
4957
}