Subversion Repositories f9daq

Rev

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