Subversion Repositories f9daq

Compare Revisions

No changes between revisions

Ignore whitespace Rev 145 → Rev 146

/lab/sipmscan/trunk/.rootrc
0,0 → 1,13
#Rint.Logon: /afs/p-ng.si/home/gkukec/private/Gasper/Programi/rootlogon.C
Gui.DefaultFont: -*-helvetica-medium-r-normal-*-12-*-*-*-*-*-iso8859-1
Gui.MenuFont: -*-helvetica-medium-r-normal-*-12-*-*-*-*-*-iso8859-1
Gui.MenuHiFont: -*-helvetica-bold-r-normal-*-12-*-*-*-*-*-iso8859-1
Gui.DocFixedFont: -*-courier-medium-r-normal-*-12-*-*-*-*-*-iso8859-1
Gui.DocPropFont: -*-helvetica-medium-r-normal-*-12-*-*-*-*-*-iso8859-1
Gui.IconFont: -*-helvetica-medium-r-normal-*-10-*-*-*-*-*-iso8859-1
Gui.StatusFont: -*-helvetica-medium-r-normal-*-10-*-*-*-*-*-iso8859-1
Root.MemStat: 1
Root.ObjectStat: 1
Root.UseTTFonts: true
Root.TTFontPath: $(ROOTSYS)/fonts
X11.UseXft: yes
/lab/sipmscan/trunk/configure
0,0 → 1,295
#!/bin/bash
 
function colorecho
{
echo -e$2 "\033[33m$1\033[39m"
}
 
function errorecho
{
echo -e "\031[33m$1\033[39m"
}
 
function helptext()
{
colorecho "#------------------------------"
colorecho "# Configure instructions: -----"
colorecho "#------------------------------"
colorecho ""
colorecho "./configure [option] [type] [install directories] [ostype]"
colorecho ""
colorecho "[option] = Option for configure:"
colorecho " help Display configure instructions."
colorecho " nomake Only prepare system dependent files (base directory and online/offline mode)."
colorecho " all Prepare system dependent files and make used libraries."
colorecho " clean Clean the installation directory. Does not clean the results directory."
colorecho " compress Compress the source code in a tar-ball."
colorecho ""
colorecho "[type] = Configure for use in online or offline mode (only needed in nomake and all):"
colorecho " I Online mode."
colorecho " O Offline mode (no connection to CAMAC, motor, voltage supply and scope)."
colorecho " S Offline mode with scope connection (no connection to CAMAC, motor and voltage supply)."
colorecho ""
colorecho "[install directories] = Directories where ROOT and NET-SNMP are installed (when running with superuser, this is important, otherwise optional):"
colorecho " --root-install=/root/install/directory"
colorecho " --snmp-install=/snmp/install/directory"
colorecho ""
colorecho "[ostype] = Specific setting for 64bit or 32bit version of OS (optional):"
colorecho " --ostype=i686 32bit OS type"
colorecho " --ostype=x86_64 64bit OS type"
colorecho ""
colorecho "Example:"
colorecho " ./configure all I --root-install=/home/user/root --snmp-install=/home/user/snmp"
colorecho ""
colorecho "#------------------------------"
}
 
# Check for arguments
if [ "$1" == "" ]; then
errorecho "Error! No arguments supplied."
echo ""
helptext
exit 1
else
# When using help, only display help and then exit
if [ "$1" == "help" ]; then
helptext
exit 0
fi
 
# Print help and exit if we give a wrong first argument
if [ "$1" != "nomake" ] && [ "$1" != "all" ] && [ "$1" != "clean" ] && [ "$1" != "compress" ]; then
errorecho "Error! Wrong configuration option selected (first argument)."
echo ""
helptext
exit 1
fi
 
startdir=$PWD
 
# Check for ROOT and NET-SNMP install directories and for OS type
snmpsearch="--snmp-install="
rootsearch="--root-install="
ossearch="--ostype="
snmpdirectory=-1
rootdirectory=-1
osmanual=-1
for var in $@
do
case $var in
"$snmpsearch"*)
snmpdirectory=${var#$snmpsearch}
echo "NET-SNMP directory: $snmpdirectory";;
"$rootsearch"*)
rootdirectory=${var#$rootsearch}
echo "ROOT directory: $rootdirectory";;
"$ossearch"*)
osmanual=${var#$ossearch};;
*) ;;
esac
done
# If not supplied, check automatically for OS type
if [ $osmanual == -1 ]; then
ostype=`uname -p`
if [ "$ostype" != "x86_64" ] && [ "$ostype" != "i686" ]; then
ostype=`uname -i`
if [ "$ostype" != "x86_64" ] && [ "$ostype" != "i686" ]; then
ostype=`uname -m`
fi
fi
else
ostype=$osmanual
fi
# Check for installation directory of ROOT - if variables not currently set, remind user to set them before running make
if [ "$1" != "clean" ] && [ "$1" != "compress" ]; then
if [ $rootdirectory != -1 ]; then
printenv ROOTSYS > /dev/null
if [ $? != 0 ]; then
colorecho "ROOT environment variables not set. Please run \"source $rootdirectory/bin/thisroot.sh\", before using make."
fi
else
colorecho "Before running make, please make sure ROOT environment variables are set."
fi
fi
 
# Compiles the table microcontroller program
if [ "$1" == "all" ]; then
if [ -d $startdir/src/MIKRO ]; then
cd $startdir/src/MIKRO
rm -f $startdir/src/MIKRO/mikro_ctrl
make
cd $startdir
fi
fi
 
# When using compress, only create a tar-ball and then exit
if [ "$1" == "compress" ]; then
cd $startdir
if [ ! -d $startdir/sipmscan_trunk ]; then
mkdir $startdir/sipmscan_trunk
mkdir $startdir/sipmscan_trunk/results
mkdir $startdir/sipmscan_trunk/layout
mkdir $startdir/sipmscan_trunk/settings
echo "Copying files to temporary directory $startdir/sipmscan_trunk..."
cp -r configure ./dict ./doc ./include ./input ./src ./sipmscan_trunk/
cp -r ./layout/default.layout ./sipmscan_trunk/layout/
echo "default.layout" > ./sipmscan_trunk/layout/selected_layout.txt
# TODO - Settings default files
cd $startdir/sipmscan_trunk
echo "Cleaning the base directory in $startdir/sipmscan_trunk..."
rm -f ./*.bak
echo "Cleaning the subdirectories of $startdir/sipmscan_trunk..."
rm -f ./*/*.bak
cd $startdir/sipmscan_trunk/src
rm -f ./*/*.bak
cd $startdir/sipmscan_trunk/include/vxi11_x86_64
echo "Cleaning the 64 bit VXI11 directory in $startdir/sipmscan_trunk/include/vxi11_x86_64..."
rm -f ./*.bak
make clean
cd $startdir/sipmscan_trunk/include/vxi11_i686
echo "Cleaning the 32 bit VXI11 directory in $startdir/sipmscan_trunk/include/vxi11_i686..."
rm -f ./*.bak
make clean
cd $startdir
echo "Creating a tar-ball sipmscan_trunk.tar.gz..."
tar czf $startdir/sipmscan_trunk.tar.gz ./sipmscan_trunk
echo "Removing the temporary directory $startdir/sipmscan_trunk..."
rm -fr $startdir/sipmscan_trunk
exit 0
else
errorecho "Error! Directory ./sipmscan_trunk already exists."
exit 1
fi
fi
 
# Configure the workstation information and directory of program (0 if we find something and 1 otherwise)
basedir=$(echo $startdir | sed 's/\//\\\//g')
 
if [ "$1" == "nomake" ] || [ "$1" == "all" ]; then
if [ "$2" == "O" ] || [ "$2" == "I" ] || [ "$2" == "S" ]; then
# Setting up the current working computer
grep -q "#define WORKSTAT 'N'" $startdir/input/workstation.h.in
if [ $? == 0 ]; then
sed "s/define WORKSTAT 'N'/define WORKSTAT '$2'/" $startdir/input/workstation.h.in > $startdir/input/workstation.h.mid
fi
grep -q "#define rootdir \"path-to-installation\"" $startdir/input/workstation.h.in
if [ $? == 0 ]; then
sed "s/path-to-installation/$basedir/g" $startdir/input/workstation.h.mid > $startdir/input/workstation.h.mid2
rm $startdir/input/workstation.h.mid
fi
# Check if we are connected to IJS network
etnet=$(ifconfig | grep "178.172.43.")
if [ "$etnet" == "" ]; then
sed "s/define IJSNET 1/define IJSNET 0/" $startdir/input/workstation.h.mid2 > $startdir/include/workstation.h
rm $startdir/input/workstation.h.mid2
else
cp $startdir/input/workstation.h.mid2 $startdir/include/workstation.h
rm $startdir/input/workstation.h.mid2
fi
# Setting up the OS type specific files
grep -q "#include \"vxi11_user.h\"" $startdir/input/daqscope.C.in
if [ $? == 0 ]; then
sed "s/vxi11_user.h/..\/include\/vxi11_$ostype\/vxi11_user.h/g" $startdir/input/daqscope.C.in > $startdir/src/daqscope.C
fi
grep -q "SHLIB = \$(LIBFILE) \$(LDIR)\/libvxi11.a" $startdir/input/Makefile.in
if [ $? == 0 ]; then
if [ "$2" == "I" ]; then
sed "s/SHLIB = \$(LIBFILE) \$(LDIR)\/libvxi11.a/SHLIB = \$(LIBFILE) \$(LDIR)\/libvxi11.a -lusb/g" $startdir/input/Makefile.in > $startdir/Makefile.mid
fi
fi
grep -q "CAMLIB = \$(LIBFILE)" $startdir/input/Makefile.in
if [ $? == 0 ]; then
if [ "$2" == "I" ]; then
sed "s/CAMLIB = \$(LIBFILE)/CAMLIB = \$(LIBFILE) -lusb/g" $startdir/Makefile.mid > $startdir/Makefile.mid2
rm $startdir/Makefile.mid
elif [ "$2" == "O" ] || [ "$2" == "S" ]; then
cp $startdir/input/Makefile.in $startdir/Makefile.mid2
fi
fi
sed "s/OSTYPE=none/OSTYPE=$ostype/g" $startdir/Makefile.mid2 > $startdir/Makefile
rm $startdir/Makefile.mid2
 
if [ "$2" == "O" ] || [ "$2" == "S" ]; then
cp $startdir/input/daqusb.C.offline $startdir/src/daqusb.C
cp $startdir/input/libxxusb.h.offline $startdir/include/libxxusb.h
cp $startdir/input/usb.h.offline $startdir/include/usb.h
elif [ "$2" == "I" ]; then
cp $startdir/input/daqusb.C.online $startdir/src/daqusb.C
cp $startdir/input/libxxusb.h.online $startdir/include/libxxusb.h
fi
 
echo "#!/bin/bash" > $startdir/start.sh
echo "dir=\`dirname \$0\`" >> $startdir/start.sh
echo "" >> $startdir/start.sh
echo "snmpdirectory=$snmpdirectory" >> $startdir/start.sh
echo "rootdirectory=$rootdirectory" >> $startdir/start.sh
echo "" >> $startdir/start.sh
cat $startdir/input/start.sh.in >> $startdir/start.sh
chmod ug+x $startdir/start.sh
fi
fi
 
# In case we just want to set the workstation information, exit here
if [ "$1" == "nomake" ]; then
exit 0
fi
 
# 64 bit configuration rules
if [ $ostype == "x86_64" ]; then
vxidir=$startdir/include/vxi11_$ostype
if [ -d $vxidir ]; then
cd $vxidir
if [ "$1" == "clean" ]; then
make clean
cd $startdir
make clean
rm -f Makefile
else
if [ "$2" == "O" ] || [ "$2" == "I" ] || [ "$2" == "S" ]; then
make
else
errorecho "Error! No configuration type selected (second argument)."
echo ""
helptext
exit 1
fi
fi
cd $startdir
else
errorecho "No 64 bit VXI11 source folder."
exit 1
fi
# 32 bit configuration rules
elif [ $ostype == "i686" ]; then
vxidir=$startdir/include/vxi11_$ostype
if [ -d $vxidir ]; then
cd $vxidir
if [ "$1" == "clean" ]; then
make clean
cd $startdir
make clean
rm -f Makefile
else
if [ "$2" == "O" ] || [ "$2" == "I" ] || [ "$2" == "S" ]; then
make
else
errorecho "Error! No installation type selected (second argument)."
echo ""
helptext
exit 1
fi
fi
cd $startdir
else
errorecho "No 32 bit VXI11 source folder."
exit 1
fi
else
errorecho "No OS type information found."
exit 1
fi
fi
 
exit 0
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/lab/sipmscan/trunk/dict/GuiLinkDef.h
0,0 → 1,18
#ifdef __CINT__
 
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
 
//#pragma link C++ class TGMdiSubwindow+;
#pragma link C++ class TGAppMainFrame+;
 
//#pragma link C++ function MyEventHandler;
//#pragma link C++ function GetDebug;
//#pragma link C++ function MyRedraw;
//#pragma link C++ function MyTimer;
 
//#pragma link C++ class daq;
 
#endif
 
/lab/sipmscan/trunk/dict/LibLinkDef.h
0,0 → 1,8
#ifdef __CINT__
 
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
 
#endif
 
/lab/sipmscan/trunk/dict/TestLinkDef.h
0,0 → 1,9
#ifdef __CINT__
 
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
 
#pragma link C++ class TSubStructure+;
 
#endif
/lab/sipmscan/trunk/doc/INSTALL
0,0 → 1,56
SOFTWARE FOR SIPM CHARACTERIZATION WITH CAMAC, SCOPE, BIAS VOLTAGE AND TABLE POSITION SUPPORT
=============================================================================================
By Gasper Kukec Mezek, April 2015.
 
________________
1. Installation:
 
Pre-requisites for offline and online modes:
a) Offline mode (support for histogramming and analysis):
- A newer (5.34 or higher, support for version 6 not added yet) pro version of ROOT (https://root.cern.ch).
b) Online mode (support for histogramming, analysis and data acquisition):
- Perl developer package libperl-dev for installation of net-snmp (sudo apt-get install libperl-dev).
- Current version of net-snmp (http://www.net-snmp.org).
- A newer (5.34 or higher, support for version 6 not added yet) pro version of ROOT (https://root.cern.ch).
- USB developer package libusb-dev (sudo apt-get install libusb-dev).
 
Installation is done through the usual "./configure" and "make" commands to enable the use of this software with 32 bit or 64 bit systems.
 
Configure takes the following arguments:
- First argument is the configure option (help, nomake, all, clean, compress):
help = shows configure help
all = prepares OS dependent files and makes the needed usb daq libraries
nomake = only prepares OS dependent files
clean = cleans the installation to the base file structure (keeps the results directory)
compress = compresses the base installation into a tar-ball
- Second argument is the online/offline configure setting (only used when first argument is nomake or all), that enables the software to work with:
a connected CAMAC and scope (I) = Online mode
only a connected scope (S) = Offline mode with oscilloscope connection
with no connected devices (O) = Offline mode
- The following arguments set specific computer details and can be entered in any order:
a) --root-install=/path/to/root/directory -> The ROOT install directory, if it is not installed in a standard location (especially needed when running the program with superuser, since it usually does not have the required environment variables).
b) --snmp-install=/path/to/snmp/directory -> The NET-SNMP install directory, if it is not installed in a standard location.
c) --ostype=YYYY -> Optional argument to specifically set the OS type to either 32bit (YYYY = i686) or 64bit (YYYY = x86_64). If argument not supplied, the configure script will try to get this information automatically through uname.
 
Running "./configure" or "./configure help" will give more information on specific uses.
Example:
./configure all I --root-install=/opt/root --snmp-install=/opt/net-snmp --ostype=i686
 
Makefile:
Once configuration is done, a Makefile will be generated and further installation is done by running "make". Running "make relib" will only recreate the libraries in case something has been edited in them.
Example:
make
 
On first run of the program, make sure to copy the ./mpod/WIENER-CRATE-MIB.txt to the MIB directory in your installation of net-snmp. This can be in:
~/.snmp/mibs
or
[/snmp/install/directory]/share/snmp/mibs
 
________________________
2. Running the software:
 
Once installation is performed, use
./start.sh
to start the software in offline mode or
sudo ./start.sh
to start the software in online mode. Once the software starts, it will let you know (in the terminal) if connection to CAMAC was correctly established.
/lab/sipmscan/trunk/doc/README
0,0 → 1,576
SOFTWARE FOR SIPM CHARACTERIZATION WITH CAMAC, SCOPE, BIAS VOLTAGE AND TABLE POSITION SUPPORT
=============================================================================================
By Gasper Kukec Mezek, April 2015.
 
==============
= Contents ===
==============
 
1. Installation
2. Running the software
3. Program feature overview
3a. Current program version (trunk)
3b. Old program version (trunk_v0.9)
4. Preparing for measurements
4a. Pre-software checks
4b. Experimental setup pre-measurement checks
4c. Software pre-measurement checks
5. Measurements
5a. Measurement settings
5b. Temperature chamber considerations
5c. Movement table
5d. Bias voltage supply
6. Measurement files
6a. ROOT file structure
6b. Opening measurement files
7. Analysis
8. Change log
 
=====================
= 1. Installation ===
=====================
 
See $sipmscan/doc/INSTALL for installation instructions or use "./configure help".
 
=============================
= 2. Running the software ===
=============================
 
Once installation is performed, use
./start.sh
to start the software in offline mode or
sudo ./start.sh
to start the software in online mode. Once the software starts, it will let you know (in the terminal) if connection to CAMAC
was correctly established.
 
=================================
= 3. Program feature overview ===
=================================
 
This part describes the different parts of the software and a short description on what they do.
____________________________________
3a. Current program version (trunk):
 
The main window is divided into 4 tabs and then further into subwindows:
1) Measurement tab:
a) Settings pane:
- ON/OFF switches for voltage, surface, Z axis and rotation scans (ON when checked).
- A voltage limiter -> Sets the maximum output voltage that can be set under Output voltage (sample safety reasons).
- Nr. of channels -> The number of channels to measure. Each channel corresponds to an ADC/TDC pair.
- Position units -> For display, use either movement table native units or micrometers (table units default).
- Rotation units -> For display, use either rotation table native units or degrees (degrees default).
- Scope IP -> Sets the oscilloscope IP address for connections to a device.
- LASER settings info panel -> Additional information to be written to the output file header (most generally used for
laser information).
- Chamber temperature -> Chamber temperature to be written to the output file (temperature not directly taken from the
fieldpoint sensor).
- Live histogram ON/OFF -> ON/OFF switch for live histogram update. Offers quick overview of the current measurement.
Should be avoided for scans.
b) Display: Display of the live histogram, when it is turned on.
c) Main measurement window:
- Settings for bias voltage, table position and incidence angle measurements.
- Additional settings enabled, when scans are enabled.
- If only one directional scan in X or Y direction is needed, set measurement to a surface scan and leave the other
step size to 0.
- Number of events -> Number of events gathered in one measurement.
- Time stamp -> Date and time of measurement that is written to the header of the output file.
- Save to file -> Selecting of output file filename. For scans, sequential numbers are appended to the end of the
selected filename (i.e. /path/to/test.root will in a scan have /path/to/test_001.root, /path/to/test_002.root,...).
- Start acquisition -> Starts the measurement based on currently selected settings.
- Current measurement progress bar -> Determines the status of the current measurement.
 
2) Analysis tab:
a) Histogram file selection:
- Open past measurements for analysis. Additional display of header information for quicker reference.
- If using multiple files for the analysis, use multiple file select or select all listed files. They will be used in
order displayed on the list.
- Use the Clear list button to clear all entries in from the list.
- Use the edit header button to update any information inside the headers of entries selected on the list.
b) Histogram: Displays the currently selected histogram from the histogram file selection subwindow.
c) Histogram controls:
- Enables plotting options for the currently selected histogram and to setup spectral options for analysis.
- ADC range -> Sets the range of the ADC spectrum. Ranges are automatic, when set to (0,0).
- TDC range -> Sets the range of the TDC spectrum. TDC spectrum determines the events used for plotting the ADC spectrum.
- Y range -> Sets the range of the Y axis on the spectrum. Ranges are automatic, when set to (0,0).
- Display channel -> Selects the channel to plot, when opening a multichannel measurement file.
- Plot type buttons -> Buttons to change between ADC, TDC or ADC/TDC type of plot.
- Logarithmic scale ON/OFF -> Toggle for logarithmic Y axis scale.
- Clean plots ON/OFF -> Toggle for hiding plot information or not (such as plot title, fitting information, statistics
information).
- Export -> Exports the currently selected histograms (ADC, TDC or ADC/TDC form selected files) into the .pdf format.
- Edit -> UNDER DEVELOPMENT! Opens the currently visible plot in the Histogram subwindow in a new tab to enable editing.
d) Analysis:
- Options for specific analysis types (integrate spectrum, relative PDE, breakdown voltage, surface scan, timing). When
using Start button, analysis starts, saves results and quits. When using Start and edit button, analysis starts and gives
options to further edit the results.
- General fit settings (Peak sigma, S/N ratio, background interpolation, ADC spectrum offset, Maximum acceptable peak
fit error, pedestal lower limit, background subtraction, export fits). Settings for analysis based on fitting of peaks
on the ADC spectra (breakdown voltage and relative PDE). The current progress of the analysis is displayed on the
progress bar.
 
3) Monitoring tab: UNDER DEVELOPMENT! Fieldpoint temperature sensor data view.
 
4) Help tab: Displays the contents of this help file.
 
On the top, there are 3 menus:
a) File:
- Set user layout -> Set a user saved layout of the program subwindows or use the default.
- Save current layout -> Save the program subwindow layout to be used later. This will remember the sizes of each subwindow
(Settings pane, Main measurement window, Display, Histogram file selection,...) and the overall size of the program window.
- Save current measurement settings -> UNDER DEVELOPMENT! Will evantually save the entered values from the Measurement tab.
- Save current analysis settings -> UNDER DEVELOPMENT! Will eventually save the entered values from the Analysis tab.
- Exit -> Exit the software (shortkey x)
 
b) Analysis (each takes you to the appropriate options for the analysis):
- Histogram type -> Change between histogram types (same as in histogram controls window).
- Fit spectrum -> UNDER DEVELOPMENT! Will produce a fit of ADC spectrum peak structure of the current file/files.
- Integrate spectrum -> Integrate the ADC spectrum of the current file/files inside the selected ADC range.
- Integrate spectrum (X direction) -> Same as Integrate spectrum, but the selected files were produced as X axis scans.
Makes the determination of an X directional edge scan and produces a 2D plot if Z axis scan was also enabled.
- Integrate spectrum (Y direction) -> Same as Integrate spectrum (X direction), but the selected files were produced as
Y axis scans.
- Relative PDE -> Produce a relative PDE plot, where selected files were produced as incidence angle scans.
- Surface 2D scan -> Produce an integral of the ADC spectrum, where selected files were produced as surface scans (in
X and Y directions).
- Timing analysis -> UNDER DEVELOPMENT! Will make an analysis on the TDC spectrum of measurements.
 
c) Help information
 
Important!
When using any analysis method, only events inside the selected TDC window will be used (set the TDC range accordingly).
 
_____________________________________
3b. Old program version (trunk_v0.9):
 
The main window is divided into 5 subwindows:
a) Settings window:
- ON/OFF switches for voltage and surface scans.
- a voltage limiter -> sets the maximum output voltage for safety reasons
- clean plots toggle switch -> when ON, no additional stats will be displayed on plots/histograms
- scope IP -> sets the oscilloscope IP address
- LASER settings info panel -> this will be written to the output file and is used for supplying additional information
- chamber temperature -> the chamber temperature to be written to the output file
- incidence angle -> the angle at which the sample is rotated around its axis, relative to the LASER beam (0 degrees is
perpendicular to LASER beam)
 
b) Main measurement window:
- settings for table position and bias voltage
- when scans are enabled, additional settings for scans
- number of events -> setting for the number of events to gather in a measurement
- time stamp -> informational time (start time of measurement is written to output file)
- file selector (for scans, the filenames will be appended sequential numbers to distinguish them)
- start acquisition button -> starts the measurement based on selected settings
- waveform analysis settings (channel, measurement type)
- possibility to send custom one-line commands
 
c) Histogram file selection window:
- open past measurements for analysis
- if using multiple files, use multiple file select or select all listed files
- files will be used in order displayed on the list
- to clear the complete list, use the clear list button
- to edit the header information of currently selected files, use the edit header button
- any opened measurement has an info display of its header at the bottom for easier navigation
 
d) Histogram window:
- displays the currently selected histogram in the histogram file selection window
 
e) Histogram controls window:
- directly linked to the histogram window, it enables plotting options
- can set ranges on histogram plots
- can change between different histogram types (ADC, TDC, ADC vs. TDC, 2D surface plot)
- for the 2D surface plot, the relevant files need to be selected in the histogram file selection window
- toggle for logarithmic Y scale
- the currently selected histogram can be manually exported with the export button
- fit settings used when running "Fit spectrum" and "Fit all selected" options in the Analysis menu
 
On the top, there are 4 menus:
a) File:
- New Measurement -> not working
- Exit -> exit the software (shortkey x)
 
b) Analysis:
- Histogram type -> change between histogram types (same as in histogram controls window)
- Fit spectrum -> fit the currently open spectrum for peaks
- Fit all selected -> fit all the selected ADC spectra selected in the histogram file selection window for peaks and display
the breakdown voltage plots
- Integrate spectrum (X, Y) -> integrate the ADC spectrum for multiple files with an X or Y scan (used for edge scans)
- Relative PDE -> calculation of the relative PDE for the currently selected files
 
c) Tools:
- Fieldpoint temperature sensor -> direct graphing of the fieldpoint temperature sensor (with settings for fieldpoint channel,
start time and end time), output is a graph (if exporting) and a comma separated list saved to folder ./fieldpoint. Updating
the graph can cause unstable behavior. If possible, use ~/sipmscan/fieldpoint_standalone instead.
 
d) Windows:
- Specific window tiling
- Switch between active windows
 
e) Help information
 
Important!
When using any analysis method (surface 2D plot, fitting, integration, ADC spectra display) only events inside the selected TDC
window will be used so set the TDC range accordingly.
 
===================================
= 4. Preparing for measurements ===
===================================
 
General information for preparing the experimental setup and software for measurements.
 
________________________
4a. Pre-software checks:
 
Before running the Online version of the program, make sure that CAMAC (Computer Automated Measurement And Control) is turned
on and is connected to the computer via a USB cable. If upon starting, the program gives the following message:
 
daq::connect() - No devices were detected!
 
then CAMAC was not started or the program did not properly register it.
 
In addition, for the Online version of the program, make sure that all movement table controllers are turned on and are connected
to the computer via a USB cable.
 
For the connection with the oscilloscope (Online and Offline with scope control versions of the program), make sure it is
connected to the same network with a UTP cable and that the VXI software is started on it.
 
______________________________________________
4b. Experimental setup pre-measurement checks:
 
When making changes inside the setup, make sure that no cables are hindering the movement of any of the movement tables. For
the X, Y and Z axis table, the most critical are motor control cables (white, flat, multiwire cables) and the optical cable
for laser optics (yellow or orange optical fibre). For the rotation table, the most critical are voltage supply cable (marked
with BIAS) and signal cables (the same as bias cable, but unmarked or marked with SIGNAL).
 
Additionally, whenever putting the experimental setup back together, note the distance between the laser optics and the sample.
The sample should be placed out of harms way from the collimator of the optics (check it by setting Z axis position to 0).
 
____________________________________
4c. Software pre-measurement checks:
 
Before starting any measurement, it is suggested to set the Voltage limit (Settings pane, Measurement tab) in order to avoid
any unwanted mistakes in bias voltage settings (to avoid any irreparable damage to the sample). Also, make sure to note the
output channel for bias voltage supply and not change any other channels (since they could be connected to other experimental
setups).
 
=====================
= 5. Measurements ===
=====================
 
Information on the settings for performing measurements available in this program and information on the movement tables.
 
_________________________
5a. Measurement settings:
 
On the Settings pane in the Measurement tab, the type of measurement can be selected:
- None is checked: The program will perform a single measurement (useful for quickly determining the state of the setup).
- Voltage scan is checked: The program will enable V(min), V(max) and V(step) settings and perform multiple measurements at
different bias voltages. The number of measurements is equal to:
 
Floor( [V(max) - V(min)]/V(step) )
 
The last measurement is at a voltage always lower or equal to V(max) for safety reasons. Whenever V(step) is 0, only one
measurement will be performed at V(min).
 
- Surface scan is checked: The program will enable X(min), X(max) and X(step), and Y(min), Y(max) and Y(step) settings and
perform multiple measurements at different table positions (surface scan). The number of measurements is equal to:
 
Floor( [X(max) - X(min)]/X(step) ) Floor( [Y(max) - Y(min)]/Y(step) )
 
The last measurement is at a position always smaller or equal to X(max) or Y(max). Whenever X(step) is 0, only one measurement
will be performed at X(min) and equally in the Y axis direction. By setting one axis step size to 0, only scans along one axis
are performed (for example for edge scans).
 
- Z-axis scan is checked: The program will enable Z(min), Z(max) and Z(step) settings and perform multiple measurements at
different distances between laser optics and the sample (Z axis). The number of measurements is equal to:
 
Floor( [Z(max) - Z(min)]/Z(step) )
 
The last measurement is at a position always smaller or equal to Z(max). Whenever Z(step) is 0, only one measurement will be
performed at Z(min).
 
- Rotation scan is checked: The program will enable Angle(min), Angle(max) and Angle(step) settings and perform multiple
measurements at different incidence angles (angle away from perpendicular incidence of laser light on the sample). The number
of measurements is equal to:
 
Floor( [Angle(max) - Angle(min)]/Angle(step) )
 
The last measurement is at an angle always smaller or equal to Angle(max). Whenever Angle(step) is 0, only one measurement
will be performed at Angle(min).
 
Surface scan and Z axis scan can be combined to perform edge scans at different distances between optics and sample (useful
for finding the focal point of the laser).
 
_______________________________________
5b. Temperature chamber considerations:
 
Whenever using the temperature chamber, be careful about the set temperature. SiPM samples have a specific operational and
storage temperatures that should not be exceeded. The temperature chamber, however, has slight overshoots when increasing
the temperature, thus heating slightly above the set temperature (sometimes as much as 5 degrees) and then cooling back down.
 
The chamber also has some problems cooling after previous heating (ex. coming from 0 degrees to 25 degrees and then again
cooling the chamber). In this case, it will seem to remain around some temperature, although it is supposed to be cooling
down. Sometimes this can be solved by turning off the chamber and waiting for some time or by making a large temperature
jump from higher to lower temperature (taking into consideration the sample temperature range).
 
Opening the chamber after measurements at low temperatures should be very short, since condensation forms very quickly that
can then lead to the water droplets freezing at low temperatures. Ideally, the chamber should be warmed close to room
temperature before opening, but any very short changes to the setup can still be performed when at lower temperatures.
 
___________________
5c. Movement table:
 
The movement tables are controlled by National Aperture MicroMini controllers through a subprogram found in
$sipmscan/trunk/src/MIKRO. Sometimes special measures are needed (in case of problems) that are not available inside the
sipmscan software, but can be achieved by going directly to the subprogram. The subprogram can be run, by going directly
to its directory and running:
 
./mikro_ctrl [arguments]
 
The arguments can be (only running ./mikro_ctrl will bring up help information):
- Node select: -n [node nr]. The [nodenr] is the address number of the controller as set on the front of the MicroMini
controller.
- Initialize node: -i [init type]. The [inittype] is the initialization type that can be 3M Linear (1), 3M Rotational (2),
4M Linear (3) or 4M Rotational (4). 3M are the smaller/shorter versions, while 4M are the larger/longer versions (all three
axis are 4M Linear and the angle is 3M Rotational). Always needs the node select argument (-n).
- Node homing: -h. Sets the node to a predetermined 0 value (home). Always needs the node select argument (-n). IMPORTANT: The
rotational table must never be set to home! It does not have a predetemined zero, so the table will infinitely spin and can
cause harm to the sample or attached cables.
- Reset node: -r. Does a complete reset of the controller. Always needs the node select argument (-n). After reset, the
controller needs to be initialized in order to work properly.
- Node status: -a. Returns the current status of the controller. Can be used with node select argument (-n) to target specific
controller or without to display status from all.
- Node position: -p. Returns the current position of the controller. Always needs the node select argument (-n).
- Node get command: -g [command]. Get return value from the issued command. Always needs the node select argument (-n). For
possible commands, see the MicroMini user manual.
- Node set command: -v [value] -s [command]. Set a value with an issued command. Always needs the node select argument (-n).
For possible commands and values, see the MicroMini user manual.
- Custom node command: -c [command]. Run one of the node commands without setting a value. Always needs the node select
argument (-n). For possible commands and values, see the MicroMini user manual.
 
Example commands:
- Reset node 1:
./mikro_ctrl -n 1 -r
- Initialize node 2 as a 4M Linear type:
./mikro_ctrl -n 2 -i 3
- Home node 3:
./mikro_ctrl -n 3 -h
- Determine node 1 position:
./mikro_ctrl -n 1 -p
- Prepare to move node 2 to an absolute position of 1000 and move it:
./mikro_ctrl -n 2 -v 500 -s la
./mikro_ctrl -c m
- Prepare to move node 3 relative to current position for -500 and move it:
./mikro_ctrl -n 2 -v -500 -s lr
./mikro_ctrl -c m
- Abort the current movement of node 4:
./mikro_ctrl -n 4 -c ab
 
Documentation:
- MicroMini controller manual: http://www-f9.ijs.si/~rok/detectors/oprema/national_aperture_stages/MicroMini_Manual.pdf
- 4M Linear table: http://www.naimotion.com/mm4mex.htm
- 3M Rotational table: http://www.naimotion.com/mm3mr.htm
 
________________________
5d. Bias voltage supply:
 
The bias voltage is supplied by the MPOD HV & LV power supply system through a subscript found in $sipmscan/trunk/src/mpod
(using the snmp software). Sometimes special measures are needed (in case of problems) that are not available inside the
sipmscan software, but can be achieved by going directly to the subprogram. The subprogram can be run, by going directly to
its directory and running:
 
./mpod_voltage.sh [arguments]
 
The arguments can be:
- Reset all output channels: --resetall
- Reset a selected output channel: -r [channel]
- Selects an output channel: -o [channel]
- Sets the output channel voltage: -v [voltage]
- Turns the output on/off: -s [0/1]
- Get the current output channel voltage: -g
 
Example commands:
- Get the set bias voltage on channel 1 (U0):
./mpod_voltage.sh -o 1 -g
- Turn the bias voltage off on channel 2 (U1):
./mpod_voltage.sh -o 2 -s 0
- Turn the bias voltage on and set it to 24.5V on channel 1 (U0):
./mpod_voltage.sh -o 1 -v 24.5 -s 1
- Reset channel 2 (U1):
./mpod_voltage.sh -o 2 -r
 
In its complete state, the command used in the script mpod_voltage.sh for setting for example an output voltage of 24.5 to
channel 1 (U0):
snmpset -v 2c -M +. -m +WIENER-CRATE-MIB -c guru [IP address] outputVoltage.1 F 24.5
 
Documentation:
- Net-SNMP: http://www.net-snmp.org/docs/man/
- MPOD: http://file.wiener-d.com/documentation/MPOD/Manual_MPOD_LV-HV_2.9.pdf
 
==========================
= 6. Measurement files ===
==========================
 
The measurement files, used for saving results, are constructed in native ROOT format to increase the read/write speeds while
reading and saving data.
________________________
6a. ROOT file structure:
 
The output ROOT files are structured in this way:
 
ROOT file (TFile)
|
|== header_data (TTree): Header information (same for all events)
| |
| |== nrch (TBranch): Number of channels (ADC + TDC channels)
| |== timestamp (TBranch): Unix timestamp for start of measurement
| |== biasvolt (TBranch): Measurement bias voltage
| |== xpos (TBranch): X axis position in table units
| |== ypos (TBranch): Y axis position in table units
| |== zpos (TBranch): Z axis position in table units
| |== temperature (TBranch): Chamber temperature
| |== angle (TBranch): Incidence angle of measurement
| |== laserinfo (TBranch): Additional info for measurement
|
|== meas_data (TTree): Measured values from ADC and TDC (all events)
| |
| |== ADC0 (TBranch): All events from ADC channel 0 saved in order
| |== TDC0 (TBranch): All events from TDC channel 0 saved in order
| |== ADC1 (TBranch): All events from ADC channel 1 saved in order
| |== TDC1 (TBranch): All events from TDC channel 1 saved in order
| |== ... (TBranch): Additional channels up to 8 (0-7) in total
|
|== scope_data (TTree, optional): Measured values from the oscilloscope
|
|== measdata (TBranch): Currently in development
 
 
The easiest way to get the data is to create structures:
 
struct EventHeader {
int nrch;
int timestamp;
double biasvolt;
int xpos;
int ypos;
int zpos;
double temperature;
double angle;
char laserinfo[256];
} evtheader;
 
struct EventData {
int adcdata[8];
int tdcdata[8];
} evtdata;
 
struct EventMeas {
double measdata;
} evtmeas;
 
 
Then opening the file:
 
TFile* inputfile = TFile::Open("filename.root","READ");
 
Then getting separate information:
- for instance for reading the bias voltage from header:
 
TTree* sometree;
inputfile->GetObject("header_data", sometree);
sometree->SetBranchAddress("biasvolt", &evtheader.biasvolt);
sometree->GetEntry(0);
 
- for instance for reading all ADC and TDC events in a file from channel 1 (ADC0):
 
TTree* sometree;
inputfile->GetObject("meas_data", sometree);
char selectedCh[256];
for(int i = 0; i < sometree->GetEntries(); i++)
{
sprintf(selectedCh, "ADC%d", 0);
sometree->SetBranchAddress(selectedCh, &evtdata.adcdata[i]);
sometree->GetEntry(i);
 
sprintf(selectedCh, "TDC%d", 0);
sometree->SetBranchAddress(selectedCh, &evtdata.tdcdata[i]);
sometree->GetEntry(i);
}
 
______________________________
6b. Opening measurement files:
 
The sipmscan software has internal handling for saving and opening measurement files. To open these files for an analysis, use
the File selection button in the Histogram file selection window (Analysis tab). Once the file or files are opened, it is possible
to double click a file on the list to display its histogram. The histogram can then be manipulated by changing ADC or TDC ranges,
or changing the type of displayed histogram (ADC, TDC ADC versus TDC).
 
Each of the selected files has a display of its header below the file list in order to quickly determine at what conditions and
when this measurement was taken. If there are any problems with the header, modifications can be performed with the Edit header
button.
 
After that analysis on the measurements can be performed, based on the selected ranges for ADC and TDC (note that each measured
event has a ADC and TDC channel value saved to the file).
 
=================
= 7. Analysis ===
=================
 
The sipmscan software already includes a number of analysis options:
- Plotting ADC (Analog-to-Digital Converter) spectrum, TDC (Time-to-Digital Converter) spectrum and ADC versus TDC 2D plots.
- Fitting of ADC spectrum photon equivalent peaks.
- ADC spectrum integration: Single or along X or Y directions (for edge scans).
- Relative Photon Detection Efficiency: Efficiency of sample relative to incidence angle.
- Breakdown voltage: Determination of silicon detector breakdown voltage through ADC spectrum photon peak separation (gain).
- Surface scan: Production of a 2D plot by integrating the ADC spectrum in each laser position.
 
Still to come...
 
===================
= 8. Change log ===
===================
 
4.4.2016 (Current Rev):
a) Complete restructure of the program, so that it now runs seperately, not through ROOT (libraries are constructed pre-run).
Program is now split into multiple tabs for easier use, three of which are Measurement, Analysis and Help.
b) Added support for relative PDE measurements with included sample rotation table.
c) Improvement of analysis part of the program (includes ADC spectrum integration, breakdown voltage characterization, surface
scans, relative PDE characterization,...).
d) Added tooltips for different parts of the program for quick reference. Use them by hovering over any text entries, number
entries, check boxes or buttons.
e) Connection to temperature data and oscilloscope currently under development.
f) Older version of program moved to https://f9pc00.ijs.si/svn/f9daq/lab/sipmscan/trunk_v0.9 and will no longer be in development.
 
17.7.2015 (Rev 129):
a) Fixed a problem with ADC peak fitting (peak fitting returning a segmentation fault).
b) Added support to edit file headers (in case, some were created at an older date and did not include some header information or
there was a mistake in writing them).
c) Temperature data can only be retrieved when connected to the IJS network (IP = 178.172.43.xxx) and is disabled otherwise.
d) The relative PDE measurement now takes the incidence angle value directly from input files.
e) Currently, data acquisition only works on 32bit computers.
f) Fixed issue with program not correctly writting multiple channels.
 
5.5.2015 (Rev 128):
a) Added a header display for opened files in the histogram file selection window. This enables a quicker view of the measurement
information.
b) Added an incidence angle input to be able to save sample rotation angle to headers of files.
c) Added support for the fieldpoint temperature sensor (FP RTD 122). Can now plot and export data from the sensor for a specific
channel and specific time range. For now, this option only works if the PC you are using this program on is connected to an
internet/ethernet connection at IJS.
d) Added a limited relative PDE analysis option. At this time, it takes the selected files and calculates the PDE, relative to
the first selected file. The first file should be measured at incidence angle 0, with others having an incidence angle shift of
+15 (1st file -> 0, 2nd file -> 15, 3rd file -> 30,...).
 
9.4.2015 (Rev 127):
a) Added communications panel for connecting to a Tektronix scope.
b) Added limited support for waveform analysis with a Tektronix scope. For now, it only works when linking it to CAMAC acquisition.
c) Added a manual chamber temperature entry field.
 
16.3.2015 (Rev 117):
a) First version of sipmscan.
b) Added support for CAMAC, bias voltage settings and table position settings.
c) Added support for opening measured histograms.
d) Added support for analysis:
- making surface plots
- fitting the ADC spectrum
- creating breakdown voltage plots
- integrating the ADC spectrum with changing X or Y direction (edge scans)
/lab/sipmscan/trunk/doc/configuration.txt
0,0 → 1,61
$BASE/.rootrc:
This file is for setting ROOT environment. See the following to properly use it:
https://root.cern.ch/root/html/TAttText.html
ftp://root.cern.ch/root/doc/ROOTUsersGuideHTML/ch02s07.html
https://root.cern.ch/root/roottalk/roottalk01/2867.html
 
Here is an example of a .rootrc file:
Gui.DefaultFont: -*-helvetica-medium-r-normal-*-14-*-*-*-*-*-iso8859-1
Gui.MenuFont: -*-helvetica-medium-r-normal-*-14-*-*-*-*-*-iso8859-1
Gui.MenuHiFont: -*-helvetica-bold-r-normal-*-14-*-*-*-*-*-iso8859-1
Gui.DocFixedFont: -*-courier-medium-r-normal-*-14-*-*-*-*-*-iso8859-1
Gui.DocPropFont: -*-helvetica-medium-r-normal-*-14-*-*-*-*-*-iso8859-1
Gui.IconFont: -*-helvetica-medium-r-normal-*-12-*-*-*-*-*-iso8859-1
Gui.StatusFont: -*-helvetica-medium-r-normal-*-12-*-*-*-*-*-iso8859-1
Root.MemStat: 1
Root.ObjectStat: 1
 
If needed we can also add additional instructions in a C file and run it on each ROOT login:
Rint.Logon: /path/to/rootlogon.C
 
/---------------------------
/--- rootlogon.C -----------
/---------------------------
{
TStyle *mystyle = new TStyle("mystyle", "My own ROOT style");
 
mystyle->SetCanvasBorderMode(0);
mystyle->SetFrameBorderMode(0);
mystyle->SetPalette(1,0);
mystyle->SetOptTitle(0);
mystyle->SetCanvasColor(0);
 
mystyle->SetStatFontSize(0.024);
mystyle->SetStatBorderSize(1);
mystyle->SetStatColor(kGray);
mystyle->SetStatX(0.925);
mystyle->SetStatY(0.925);
mystyle->SetStatW(0.13);
 
mystyle->SetTextFont(132);
mystyle->SetTextSize(0.08);
 
mystyle->SetLabelSize(0.03,"xyz");
mystyle->SetLabelOffset(0.01,"xyz");
mystyle->SetPadTickX(1);
mystyle->SetPadTickY(1);
 
mystyle->SetCanvasDefX(100);
mystyle->SetCanvasDefY(50);
mystyle->SetCanvasDefW(900);
mystyle->SetCanvasDefH(600);
mystyle->SetPadBottomMargin(0.1);
mystyle->SetPadTopMargin(0.04);
mystyle->SetPadLeftMargin(0.125);
mystyle->SetPadRightMargin(0.04);
 
gROOT->SetStyle("mystyle");
cout << "Setting custom style from /path/to/.rootlogon.C" << endl;
return;
}
 
/lab/sipmscan/trunk/doc/documentation.html
0,0 → 1,568
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Software for SiPM characterization</title>
<link rel="stylesheet" type="text/css" href="style_sheet.css">
</head>
 
<body>
 
<h1 id="#top">Software for SiPM characterization with CAMAC, scope, bias voltage and table position support</h1>
 
<div>
<h2>Contents</h2>
<ol>
<li><a href="#install">Installation</a></li>
<li><a href="#softrun">Running the software</a></li>
<li><a href="#featall">Program feature overview</a></li>
<ol type="a">
<li><a href="#featnew">Current program version (trunk)</a></li>
<li><a href="#featold">Old program version (trunk_v0.9)</a></li>
</ol>
<li><a href="#prepmeasure">Preparing for measurements</a></li>
<ol type="a">
<li><a href="#presoft">Pre-software checks</a></li>
<li><a href="#exppremeasure">Experimental setup pre-measurement checks</a></li>
<li><a href="#softpremeasure">Software pre-measurement checks</a></li>
</ol>
<li><a href="#measures">Measurements</a></li>
<ol type="a">
<li><a href="#meassettings">Measurement settings</a></li>
<li><a href="#tempchamber">Temperature chamber considerations</a></li>
<li><a href="#movement">Movement table</a></li>
<li><a href="#biasvolt">Bias voltage supply</a></li>
</ol>
<li><a href="#measfiles">Measurement files</a></li>
<ol type="a">
<li><a href="#rootfile">ROOT file structure</a></li>
<li><a href="#fileopen">Opening measurement files</a></li>
</ol>
<li><a href="#analysis">Analysis</a></li>
<li><a href="#changelog">Change log</a></li>
</ol>
 
<h2 id="install">1. Installation</h2>
<p>Pre-requisites for offline and online modes:</p>
<ol type="a">
<li>Offline mode (support for histogramming and analysis):</li>
<ul>
<li>A newer (5.34 or higher, support for version 6 not added yet) pro version of ROOT (<a href="https://root.cern.ch" target="_blank">https://root.cern.ch</a>).</li>
</ul>
<li>Online mode (support for histogramming, analysis and data acquisition):</li>
<ul>
<li>Perl developer package libperl-dev for installation of net-snmp (<tt>sudo apt-get install libperl-dev</tt>).</li>
<li>Current version of net-snmp (<a href="http://www.net-snmp.org" target="_blank">http://www.net-snmp.org</a>).</li>
<li>A newer (5.34 or higher, support for version 6 not added yet) pro version of ROOT (<a href="https://root.cern.ch" target="_blank">https://root.cern.ch</a>).</li>
<li>USB developer package libusb-dev (<tt>sudo apt-get install libusb-dev</tt>).</li>
</ul>
</ol>
 
<p>Installation is done through the usual <tt>./configure</tt> and <tt>make</tt> commands to enable the use of this software with 32 bit or 64 bit systems.</p>
 
<p>Configure takes the following arguments:</p>
<ul>
<li>First argument is the configure option (help, nomake, all, clean, compress):</li>
<ul style="list-style-type:none">
<li><tt>help</tt> = shows configure help</li>
<li><tt>all</tt> = prepares OS dependent files and makes the needed usb daq libraries</li>
<li><tt>nomake</tt> = only prepares OS dependent files</li>
<li><tt>clean</tt> = cleans the installation to the base file structure (keeps the results directory)</li>
<li><tt>compress</tt> = compresses the base installation into a tar-ball</li>
</ul>
<li>Second argument is the online/offline configure setting (only used when first argument is nomake or all), that enables the software to work with:</li>
<ul style="list-style-type:none">
<li><tt>I</tt> = a connected CAMAC and scope (Online mode)</li>
<li><tt>S</tt> = only a connected scope (Offline mode with oscilloscope connection)</li>
<li><tt>O</tt> = with no connected devices (Offline mode)</li>
</ul>
<li>The following arguments set specific computer details and can be entered in any order:</li>
<ol type="a">
<li><tt>--root-install=/path/to/root/directory</tt> = The ROOT install directory, if it is not installed in a standard location (especially needed when running the program with superuser, since it usually does not have the required environment variables).</li>
<li><tt>--snmp-install=/path/to/snmp/directory</tt> = The NET-SNMP install directory, if it is not installed in a standard location.</li>
<li><tt>--ostype=YYYY</tt> = Optional argument to specifically set the OS type to either 32bit (<tt>YYYY = i686</tt>) or 64bit (<tt>YYYY = x86_64</tt>). If argument not supplied, the configure script will try to get this information automatically through uname.</li>
</ol>
</ul>
 
<p>Running <tt>./configure</tt> or <tt>./configure help</tt> will give more information on specific uses.</p>
<p>Example:</p>
<div class="codeback"><pre><code>./configure all I --root-install=/opt/root --snmp-install=/opt/net-snmp --ostype=i686</code></pre></div>
<p>Once configuration is done, a Makefile will be generated and further installation is done by running <tt>make</tt>. Running <tt>make relib</tt> will only recreate the libraries in case something has been edited in them.</p>
<p>Example:</p>
<div class="codeback"><pre><code>make</code></pre></div>
 
<p>On first run of the program, make sure to copy the <tt>./mpod/WIENER-CRATE-MIB.txt</tt> to the MIB directory in your installation of net-snmp. This can be in <tt>~/.snmp/mibs</tt> or <tt>[/snmp/install/directory]/share/snmp/mibs</tt>.</p>
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="softrun">2. Running the software</h2>
<p>Once installation is performed, use</p>
<div class="codeback"><pre><code>./start.sh</code></pre></div>
<p>to start the software in offline mode or</p>
<div class="codeback"><pre><code>sudo ./start.sh</code></pre></div>
<p>to start the software in online mode. Once the software starts, it will let you know (in the terminal) if connection to CAMAC was correctly established.</p>
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="featall">3. Program feature overview</h2>
<p>This part describes the different parts of the software and a short description on what they do.</p>
 
<h3 id="featnew">3a. Current program version (trunk)</h3>
<p>The main window is divided into 4 tabs and then further into subwindows:</p>
<ol>
<li>Measurement tab:</li>
<ol type="a">
<li>Settings pane:</li>
<ul>
<li>ON/OFF switches for voltage, surface, Z axis and rotation scans (ON when checked).</li>
<li>A voltage limiter: Sets the maximum output voltage that can be set under Output voltage (sample safety reasons).</li>
<li>Nr. of channels: The number of channels to measure. Each channel corresponds to an ADC/TDC pair.</li>
<li>Position units: For display, use either movement table native units or micrometers (table units default).</li>
<li>Rotation units: For display, use either rotation table native units or degrees (degrees default).</li>
<li>Scope IP: Sets the oscilloscope IP address for connections to a device.</li>
<li>LASER settings info panel: Additional information to be written to the output file header (most generally used for laser information).</li>
<li>Chamber temperature: Chamber temperature to be written to the output file (temperature not directly taken from the fieldpoint sensor).</li>
<li>Live histogram ON/OFF: ON/OFF switch for live histogram update. Offers quick overview of the current measurement. Should be avoided for scans.</li>
</ul>
<li>Display: Display of the live histogram, when it is turned on.</li>
<li>Main measurement window:</li>
<ul>
<li>Settings for bias voltage, table position and incidence angle measurements.</li>
<li>Additional settings enabled, when scans are enabled.</li>
<li>If only one directional scan in X or Y direction is needed, set measurement to a surface scan and leave the other step size to 0.</li>
<li>Number of events: Number of events gathered in one measurement.</li>
<li>Time stamp: Date and time of measurement that is written to the header of the output file.</li>
<li>Save to file: Selecting of output file filename. For scans, sequential numbers are appended to the end of the selected filename (i.e. <tt>/path/to/test.root</tt> will in a scan have <tt>/path/to/test_001.root</tt>, <tt>/path/to/test_002.root</tt>,...).</li>
<li>Start acquisition: Starts the measurement based on currently selected settings.</li>
<li>Current measurement progress bar: Determines the status of the current measurement.</li>
</ul>
</ol><br/>
 
<li>Analysis tab:</li>
<ol type="a">
<li>Histogram file selection:</li>
<ul>
<li>Open past measurements for analysis. Additional display of header information for quicker reference.</li>
<li>If using multiple files for the analysis, use multiple file select or select all listed files. They will be used in order displayed on the list.</li>
<li>Use the Clear list button to clear all entries in from the list.</li>
<li>Use the edit header button to update any information inside the headers of entries selected on the list.</li>
</ul>
<li>Histogram: Displays the currently selected histogram from the histogram file selection subwindow.</li>
<li>Histogram controls:</li>
<ul>
<li>Enables plotting options for the currently selected histogram and to setup spectral options for analysis.</li>
<li>ADC range: Sets the range of the ADC spectrum. Ranges are automatic, when set to (0,0).</li>
<li>TDC range: Sets the range of the TDC spectrum. TDC spectrum determines the events used for plotting the ADC spectrum.</li>
<li>Y range: Sets the range of the Y axis on the spectrum. Ranges are automatic, when set to (0,0).</li>
<li>Display channel: Selects the channel to plot, when opening a multichannel measurement file.</li>
<li>Plot type buttons: Buttons to change between ADC, TDC or ADC/TDC type of plot.</li>
<li>Logarithmic scale ON/OFF: Toggle for logarithmic Y axis scale.</li>
<li>Clean plots ON/OFF: Toggle for hiding plot information or not (such as plot title, fitting information, statistics information).</li>
<li>Export: Exports the currently selected histograms (ADC, TDC or ADC/TDC form selected files) into the .pdf format.</li>
<li>Edit: UNDER DEVELOPMENT! Opens the currently visible plot in the Histogram subwindow in a new tab to enable editing.</li>
</ul>
<li>Analysis:</li>
<li>Options for specific analysis types (integrate spectrum, relative PDE, breakdown voltage, surface scan, timing). When using Start button, analysis starts, saves results and quits. When using Start and edit button, analysis starts and gives options to further edit the results.</li>
<li>General fit settings (Peak sigma, S/N ratio, background interpolation, ADC spectrum offset, Maximum acceptable peak fit error, pedestal lower limit, background subtraction, export fits). Settings for analysis based on fitting of peaks on the ADC spectra (breakdown voltage and relative PDE). The current progress of the analysis is displayed on the progress bar.</li>
</ol><br/>
 
<li>Monitoring tab: UNDER DEVELOPMENT! Fieldpoint temperature sensor data view.</li><br/>
<li>Help tab: Displays the contents of this help file.</li><br/>
</ol>
 
<p>On the top, there are 3 menus:</p>
<ol>
<li>File:</li>
<ul>
<li>Set user layout: Set a user saved layout of the program subwindows or use the default.</li>
<li>Save current layout: Save the program subwindow layout to be used later. This will remember the sizes of each subwindow (Settings pane, Main measurement window, Display, Histogram file selection,...) and the overall size of the program window.</li>
<li>Save current measurement settings: UNDER DEVELOPMENT! Will evantually save the entered values from the Measurement tab.</li>
<li>Save current analysis settings: UNDER DEVELOPMENT! Will eventually save the entered values from the Analysis tab.</li>
<li>Exit: Exit the software (shortkey x)</li>
</ul>
<li>Analysis (each takes you to the appropriate options for the analysis):</li>
<ul>
<li>Histogram type: Change between histogram types (same as in histogram controls window).</li>
<li>Fit spectrum: UNDER DEVELOPMENT! Will produce a fit of ADC spectrum peak structure of the current file/files.</li>
<li>Integrate spectrum: Integrate the ADC spectrum of the current file/files inside the selected ADC range.</li>
<li>Integrate spectrum (X direction): Same as Integrate spectrum, but the selected files were produced as X axis scans. Makes the determination of an X directional edge scan and produces a 2D plot if Z axis scan was also enabled.</li>
<li>Integrate spectrum (Y direction): Same as Integrate spectrum (X direction), but the selected files were produced as Y axis scans.</li>
<li>Relative PDE: Produce a relative PDE plot, where selected files were produced as incidence angle scans.</li>
<li>Surface 2D scan: Produce an integral of the ADC spectrum, where selected files were produced as surface scans (in X and Y directions).</li>
<li>Timing analysis: UNDER DEVELOPMENT! Will make an analysis on the TDC spectrum of measurements.</li>
</ul>
 
<li>Help information</li>
</ol>
 
<p><span>Important!</span> When using any analysis method, only events inside the selected TDC window will be used (set the TDC range accordingly).</p>
 
<h3 id="featold">3b. Old program version (trunk_v0.9)</h3>
<p>The main window is divided into 5 subwindows:</p>
<ol>
<li>Settings window:</li>
<ul>
<li>ON/OFF switches for voltage and surface scans</li>
<li>a voltage limiter: sets the maximum output voltage for safety reasons</li>
<li>clean plots toggle switch: when ON, no additional stats will be displayed on plots/histograms</li>
<li>scope IP: sets the oscilloscope IP address</li>
<li>LASER settings info panel: this will be written to the output file and is used for supplying additional information</li>
<li>chamber temperature: the chamber temperature to be written to the output file</li>
<li>incidence angle: the angle at which the sample is rotated around its axis, relative to the LASER beam (0 degrees is perpendicular to LASER beam)</li>
</ul></br>
 
<li>Main measurement window:</li>
<ul>
<li>settings for table position and bias voltage</li>
<li>when scans are enabled, additional settings for scans</li>
<li>number of events: setting for the number of events to gather in a measurement</li>
<li>time stamp: informational time (start time of measurement is written to output file)</li>
<li>file selector (for scans, the filenames will be appended sequential numbers to distinguish them)</li>
<li>start acquisition button: starts the measurement based on selected settings</li>
<li>waveform analysis settings (channel, measurement type)</li>
<li>possibility to send custom one-line commands</li>
</ul><br/>
 
<li>Histogram file selection window:</li>
<ul>
<li>open past measurements for analysis</li>
<li>if using multiple files, use multiple file select or select all listed files</li>
<li>files will be used in order displayed on the list</li>
<li>to clear the complete list, use the clear list button</li>
<li>to edit the header information of currently selected files, use the edit header button</li>
<li>any opened measurement has an info display of its header at the bottom for easier navigation</li>
</ul><br/>
<li>Histogram window: displays the currently selected histogram in the histogram file selection window</li><br/>
 
<li>Histogram controls window:</li>
<ul>
<li>directly linked to the histogram window, it enables plotting options</li>
<li>can set ranges on histogram plots</li>
<li>can change between different histogram types (ADC, TDC, ADC vs. TDC, 2D surface plot)</li>
<li>for the 2D surface plot, the relevant files need to be selected in the histogram file selection window</li>
<li>toggle for logarithmic Y scale</li>
<li>the currently selected histogram can be manually exported with the export button</li>
<li>fit settings used when running "Fit spectrum" and "Fit all selected" options in the Analysis menu</li>
</ul><br/>
</ol>
 
<p>On the top, there are 4 menus:</p>
<ol>
<li>File:</li>
<ul>
<li>New Measurement: not working</li>
<li>Exit: exit the software (shortkey x)</li>
</ul>
 
<li>Analysis:</li>
<ul>
<li>Histogram type: change between histogram types (same as in histogram controls window)</li>
<li>Fit spectrum: fit the currently open spectrum for peaks</li>
<li>Fit all selected: fit all the selected ADC spectra selected in the histogram file selection window for peaks and display the breakdown voltage plots</li>
<li>Integrate spectrum (X, Y): integrate the ADC spectrum for multiple files with an X or Y scan (used for edge scans)</li>
<li>Relative PDE: calculation of the relative PDE for the currently selected files</li>
</ul>
 
<li>Tools:</li>
<ul>
<li>Fieldpoint temperature sensor: direct graphing of the fieldpoint temperature sensor (with settings for fieldpoint channel, start time and end time), output is a graph (if exporting) and a comma separated list saved to folder <tt>./fieldpoint</tt>. Updating the graph can cause unstable behavior. If possible, use <tt>~/sipmscan/fieldpoint_standalone</tt> instead.</li>
</ul>
 
<li>Windows:</li>
<ul>
<li>Specific window tiling</li>
<li>Switch between active windows</li>
</ul>
 
<li>Help information</li>
</ol>
 
<p><span>Important!</span> When using any analysis method (surface 2D plot, fitting, integration, ADC spectra display) only events inside the selected TDC window will be used so set the TDC range accordingly.</p>
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="prepmeasure">4. Preparing for measurements</h2>
<p>General information for preparing the experimental setup and software for measurements.</p>
 
<h3 id="presoft">4a. Pre-software checks</h3>
<p>Before running the Online version of the program, make sure that CAMAC (Computer Automated Measurement And Control) is turned on and is connected to the computer via a USB cable. If upon starting, the program gives the following message:</p>
<div class="codeback"><pre><code>daq::connect() - No devices were detected!</code></pre></div>
<p>then CAMAC was not started or the program did not properly register it.</p>
<p>In addition, for the Online version of the program, make sure that all movement table controllers are turned on and are connected to the computer via a USB cable.</p>
<p>For the connection with the oscilloscope (Online and Offline with scope control versions of the program), make sure it is connected to the same network with a UTP cable and that the VXI software is started on it.</p>
 
<h3 id="exppremeasure">4b. Experimental setup pre-measurement checks</h3>
<p>When making changes inside the setup, make sure that no cables are hindering the movement of any of the movement tables. For the X, Y and Z axis table, the most critical are motor control cables (white, flat, multiwire cables) and the optical cable for laser optics (yellow or orange optical fibre). For the rotation table, the most critical are voltage supply cable (marked with BIAS) and signal cables (the same as bias cable, but unmarked or marked with SIGNAL).</p>
<p>Additionally, whenever putting the experimental setup back together, note the distance between the laser optics and the sample. The sample should be placed out of harms way from the collimator of the optics (check it by setting Z axis position to 0).</p>
 
<h3 id="softpremeasure">4c. Software pre-measurement checks</h3>
<p>Before starting any measurement, it is suggested to set the Voltage limit (Settings pane, Measurement tab) in order to avoid any unwanted mistakes in bias voltage settings (to avoid any irreparable damage to the sample). Also, make sure to note the output channel for bias voltage supply and not change any other channels (since they could be connected to other experimental setups).</p>
 
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="measures">5. Measurements</h2>
<p>Information on the settings for performing measurements available in this program and information on the movement tables.</p>
 
<h3 id="meassettings">5a. Measurement settings</h3>
<p>On the Settings pane in the Measurement tab, the type of measurement can be selected:</p>
<ul>
<li>None is checked: The program will perform a single measurement (useful for quickly determining the state of the setup).</li><br/>
<li>Voltage scan is checked: The program will enable <tt>V(min)</tt>, <tt>V(max)</tt> and <tt>V(step)</tt> settings and perform multiple measurements at different bias voltages. The number of measurements is equal to:
<div class="codeback"><pre><code>Floor( [V(max) - V(min)]/V(step) )</code></pre></div>
The last measurement is at a voltage always lower or equal to <tt>V(max)</tt> for safety reasons. Whenever <tt>V(step)</tt> is 0, only one measurement will be performed at <tt>V(min).</tt></li><br/>
<li>Surface scan is checked: The program will enable <tt>X(min)</tt>, <tt>X(max)</tt> and <tt>X(step)</tt>, and <tt>Y(min)</tt>, <tt>Y(max)</tt> and <tt>Y(step)</tt> settings and perform multiple measurements at different table positions (surface scan). The number of measurements is equal to:
<div class="codeback"><pre><code>Floor( [X(max) - X(min)]/X(step) )
Floor( [Y(max) - Y(min)]/Y(step) )</code></pre></div>
The last measurement is at a position always smaller or equal to <tt>X(max)</tt> or <tt>Y(max)</tt>. Whenever <tt>X(step)</tt> is 0, only one measurement will be performed at <tt>X(min)</tt> and equally in the Y axis direction. By setting one axis step size to 0, only scans along one axis are performed (for example for edge scans).</li><br/>
<li>Z-axis scan is checked: The program will enable <tt>Z(min)</tt>, <tt>Z(max)</tt> and <tt>Z(step)</tt> settings and perform multiple measurements at different distances between laser optics and the sample (Z axis). The number of measurements is equal to:
<div class="codeback"><pre><code>Floor( [Z(max) - Z(min)]/Z(step) )</code></pre></div>
The last measurement is at a position always smaller or equal to <tt>Z(max)</tt>. Whenever <tt>Z(step)</tt> is 0, only one measurement will be performed at <tt>Z(min)</tt>.</li><br/>
<li>Rotation scan is checked: The program will enable <tt>Angle(min)</tt>, <tt>Angle(max)</tt> and <tt>Angle(step)</tt> settings and perform multiple measurements at different incidence angles (angle away from perpendicular incidence of laser light on the sample). The number of measurements is equal to:
<div class="codeback"><pre><code>Floor( [Angle(max) - Angle(min)]/Angle(step) )</code></pre></div>
The last measurement is at an angle always smaller or equal to <tt>Angle(max)</tt>. Whenever <tt>Angle(step)</tt> is 0, only one measurement will be performed at <tt>Angle(min)</tt>.</li>
</ul>
 
<p>Surface scan and Z axis scan can be combined to perform edge scans at different distances between optics and sample (useful for finding the focal point of the laser).</p>
 
<h3 id="tempchamber">5b. Temperature chamber considerations</h3>
<p>Whenever using the temperature chamber, be careful about the set temperature. SiPM samples have a specific operational and storage temperatures that should not be exceeded. The temperature chamber, however, has slight overshoots when increasing the temperature, thus heating slightly above the set temperature (sometimes as much as 5 degrees) and then cooling back down.</p>
<p>The chamber also has some problems cooling after previous heating (ex. coming from 0 degrees to 25 degrees and then again cooling the chamber). In this case, it will seem to remain around some temperature, although it is supposed to be cooling down. Sometimes this can be solved by turning off the chamber and waiting for some time or by making a large temperature jump from higher to lower temperature (taking into consideration the sample temperature range).</p>
<p>Opening the chamber after measurements at low temperatures should be very short, since condensation forms very quickly that can then lead to the water droplets freezing at low temperatures. Ideally, the chamber should be warmed close to room temperature before opening, but any very short changes to the setup can still be performed when at lower temperatures.</p>
 
<h3 id="movement">5c. Movement table</h3>
<p>The movement tables are controlled by National Aperture MicroMini controllers through a subprogram found in <tt>$sipmscan/trunk/src/MIKRO</tt>. Sometimes special measures are needed (in case of problems) that are not available inside the sipmscan software, but can be achieved by going directly to the subprogram. The subprogram can be run, by going directly to its directory and running:</p>
<div class="codeback"><pre><code>./mikro_ctrl [arguments]</code></pre></div>
<p>The arguments can be (only running <tt>./mikro_ctrl</tt> will bring up help information):</p>
<ul>
<li>Node select: <tt>-n [node nr]</tt>. The <tt>[nodenr]</tt> is the address number of the controller as set on the front of the MicroMini controller.</li>
<li>Initialize node: <tt>-i [init type]</tt>. The <tt>[inittype]</tt> is the initialization type that can be 3M Linear (1), 3M Rotational (2), 4M Linear (3) or 4M Rotational (4). 3M are the smaller/shorter versions, while 4M are the larger/longer versions (all three axis are 4M Linear and the angle is 3M Rotational). Always needs the node select argument (<tt>-n</tt>).</li>
<li>Node homing: <tt>-h</tt>. Sets the node to a predetermined 0 value (home). Always needs the node select argument (<tt>-n</tt>). <span>IMPORTANT:</span> The rotational table must never be set to home! It does not have a predetemined zero, so the table will infinitely spin and can cause harm to the sample or attached cables.</li>
<li>Reset node: <tt>-r</tt>. Does a complete reset of the controller. Always needs the node select argument (<tt>-n</tt>). After reset, the controller needs to be initialized in order to work properly.</li>
<li>Node status: <tt>-a</tt>. Returns the current status of the controller. Can be used with node select argument (<tt>-n</tt>) to target specific controller or without to display status from all.</li>
<li>Node position: <tt>-p</tt>. Returns the current position of the controller. Always needs the node select argument (<tt>-n</tt>).</li>
<li>Node get command: <tt>-g [command]</tt>. Get return value from the issued command. Always needs the node select argument (<tt>-n</tt>). For possible commands, see the MicroMini user manual.</li>
<li>Node set command: <tt>-v [value] -s [command]</tt>. Set a value with an issued command. Always needs the node select argument (<tt>-n</tt>). For possible commands and values, see the MicroMini user manual.</li>
<li>Custom node command: <tt>-c [command]</tt>. Run one of the node commands without setting a value. Always needs the node select argument (<tt>-n</tt>). For possible commands and values, see the MicroMini user manual.</li>
</ul>
 
<p>Example commands:</p>
<ul>
<li>Reset node 1:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 1 -r</code></pre></div>
<li>Initialize node 2 as a 4M Linear type:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 2 -i 3</code></pre></div>
<li>Home node 3:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 3 -h</code></pre></div>
<li>Determine node 1 position:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 1 -p</code></pre></div>
<li>Prepare to move node 2 to an absolute position of 1000 and move it:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 2 -v 500 -s la
./mikro_ctrl -c m</code></pre></div>
<li>Prepare to move node 3 relative to current position for -500 and move it:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 2 -v -500 -s lr
./mikro_ctrl -c m</code></pre></div>
<li>Abort the current movement of node 4:</li>
<div class="codeback"><pre><code>./mikro_ctrl -n 4 -c ab</code></pre></div>
</ul>
 
<p>Documentation:</p>
<ul>
<li><a href="http://www-f9.ijs.si/~rok/detectors/oprema/national_aperture_stages/MicroMini_Manual.pdf" target="_blank">MicroMini controller manual</a></li>
<li><a href="http://www.naimotion.com/mm4mex.htm" target="_blank">4M Linear table information</a></li>
<li><a href="http://www.naimotion.com/mm3mr.htm" target="_blank">3M Rotational table information</a></li>
</ul>
 
<h3 id="biasvolt">5d. Bias voltage supply</h3>
<p>The bias voltage is supplied by the MPOD HV & LV power supply system through a subscript found in <tt>$sipmscan/trunk/src/mpod</tt> (using the snmp software). Sometimes special measures are needed (in case of problems) that are not available inside the sipmscan software, but can be achieved by going directly to the subprogram. The subprogram can be run, by going directly to its directory and running:</p>
<div class="codeback"><pre><code>./mpod_voltage.sh [arguments]</code></pre></div>
<p>The arguments can be:</p>
<ul>
<li>Reset all output channels: <tt>--resetall</tt></li>
<li>Reset a selected output channel: <tt>-r [channel]</tt></li>
<li>Selects an output channel: <tt>-o [channel]</tt></li>
<li>Sets the output channel voltage: <tt>-v [voltage]</tt></li>
<li>Turns the output on/off: <tt>-s [0/1]</tt></li>
<li>Get the current output channel voltage: <tt>-g</tt></li>
</ul>
 
<p>Example commands:</p>
<ul>
<li>Get the set bias voltage on channel 1 (U0):</li>
<div class="codeback"><pre><code>./mpod_voltage.sh -o 1 -g</code></pre></div>
<li>Turn the bias voltage off on channel 2 (U1):</li>
<div class="codeback"><pre><code>./mpod_voltage.sh -o 2 -s 0</code></pre></div>
<li>Turn the bias voltage on and set it to 24.5V on channel 1 (U0):</li>
<div class="codeback"><pre><code>./mpod_voltage.sh -o 1 -v 24.5 -s 1</code></pre></div>
<li>Reset channel 2 (U1):</li>
<div class="codeback"><pre><code>./mpod_voltage.sh -o 2 -r</code></pre></div>
</ul>
 
<p>In its complete state, the command used in the script mpod_voltage.sh for setting for example an output voltage of 24.5 to channel 1 (U0):</p>
<div class="codeback"><pre><code>snmpset -v 2c -M +. -m +WIENER-CRATE-MIB -c guru [IP address] outputVoltage.1 F 24.5</code></pre></div>
 
<p>Documentation:</p>
<ul>
<li><a href="http://www.net-snmp.org/docs/man/" target="_blank">Net-SNMP</a></li>
<li><a href="http://file.wiener-d.com/documentation/MPOD/Manual_MPOD_LV-HV_2.9.pdf" target="_blank">MPOD documentation</a></li>
</ul>
 
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="measfiles">6. Measurement files</h2>
<p>The measurement files, used for saving results, are constructed in native ROOT format to increase the read/write speeds while reading and saving data.</p>
 
<h3 id="rootfile">6a. ROOT file structure</h3>
<p>The output ROOT files are structured in this way:</p>
<div class="codeback"><div class="codename">ROOT file structure</div>
<pre><code>ROOT file (TFile)
|
|== header_data (TTree): Header information (same for all events)
| |
| |== nrch (TBranch): Number of channels (ADC + TDC channels)
| |== timestamp (TBranch): Unix timestamp for start of measurement
| |== biasvolt (TBranch): Measurement bias voltage
| |== xpos (TBranch): X axis position in table units
| |== ypos (TBranch): Y axis position in table units
| |== zpos (TBranch): Z axis position in table units
| |== temperature (TBranch): Chamber temperature
| |== angle (TBranch): Incidence angle of measurement
| |== laserinfo (TBranch): Additional info for measurement
|
|== meas_data (TTree): Measured values from ADC and TDC (all events)
| |
| |== ADC0 (TBranch): All events from ADC channel 0 saved in order
| |== TDC0 (TBranch): All events from TDC channel 0 saved in order
| |== ADC1 (TBranch): All events from ADC channel 1 saved in order
| |== TDC1 (TBranch): All events from TDC channel 1 saved in order
| |== ... (TBranch): Additional channels up to 8 (0-7) in total
|
|== scope_data (TTree, optional): Measured values from the oscilloscope
|
|== measdata (TBranch): Currently in development
</code></pre></div>
 
<p>The easiest way to get the data is to create structures:</p>
<div class="codeback"><div class="codename">Output file structure</div>
<pre><code>struct EventHeader {
int nrch;
int timestamp;
double biasvolt;
int xpos;
int ypos;
int zpos;
double temperature;
double angle;
char laserinfo[256];
} evtheader;
 
struct EventData {
int adcdata[8];
int tdcdata[8];
} evtdata;
 
struct EventMeas {
double measdata;
} evtmeas;
</code></pre></div>
 
<p>Then opening the file:</p>
<div class="codeback"><pre><code>TFile* inputfile = TFile::Open("filename.root","READ");</code></pre></div>
 
<p>And getting separate information:</p>
<ul>
<li>for instance for reading the bias voltage from header:</li>
<div class="codeback"><pre><code>TTree* sometree;
inputfile->GetObject("header_data", sometree);
sometree->SetBranchAddress("biasvolt", &evtheader.biasvolt);
sometree->GetEntry(0);</code></pre></div>
 
<li>for instance for reading all ADC and TDC events in a file from channel 1 (ADC0):</li>
<div class="codeback"><pre><code>TTree* sometree;
inputfile->GetObject("meas_data", sometree);
char selectedCh[256];
for(int i = 0; i < sometree->GetEntries(); i++)
{
sprintf(selectedCh, "ADC%d", 0);
sometree->SetBranchAddress(selectedCh, &evtdata.adcdata[i]);
sometree->GetEntry(i);
 
sprintf(selectedCh, "TDC%d", 0);
sometree->SetBranchAddress(selectedCh, &evtdata.tdcdata[i]);
sometree->GetEntry(i);
}</code></pre></div>
</ul>
 
<h3 id="fileopen">6b. Opening measurement files</h3>
<p>The sipmscan software has internal handling for saving and opening measurement files. To open these files for an analysis, use the File selection button in the Histogram file selection window (Analysis tab). Once the file or files are opened, it is possible to double click a file on the list to display its histogram. The histogram can then be manipulated by changing ADC or TDC ranges, or changing the type of displayed histogram (ADC, TDC ADC versus TDC).</p>
<p>Each of the selected files has a display of its header below the file list in order to quickly determine at what conditions and when this measurement was taken. If there are any problems with the header, modifications can be performed with the Edit header button.</p>
<p>After that analysis on the measurements can be performed, based on the selected ranges for ADC and TDC (note that each measured event has a ADC and TDC channel value saved to the file).</p>
 
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="analysis">7. Analysis</h2>
<p>The sipmscan software already includes a number of analysis options:</p>
<ul>
<li>Plotting ADC (Analog-to-Digital Converter) spectrum, TDC (Time-to-Digital Converter) spectrum and ADC versus TDC 2D plots.</li>
<li>Fitting of ADC spectrum photon equivalent peaks.</li>
<li>ADC spectrum integration: Single or along X or Y directions (for edge scans).</li>
<li>Relative Photon Detection Efficiency: Efficiency of sample relative to incidence angle.</li>
<li>Breakdown voltage: Determination of silicon detector breakdown voltage through ADC spectrum photon peak separation (gain).</li>
<li>Surface scan: Production of a 2D plot by integrating the ADC spectrum in each laser position.</li>
</ul>
<p>Still to come...</p>
<div class="backtop"><a href="#top">Back to top</a></div>
 
<h2 id="changelog">8. Change log</h2>
<p>4.4.2016 (Current Rev):</p>
<ol type="a">
<li>Complete restructure of the program, so that it now runs seperately, not through ROOT (libraries are constructed pre-run). Program is now split into multiple tabs for easier use, three of which are Measurement, Analysis and Help.</li>
<li>Added support for relative PDE measurements with included sample rotation table.</li>
<li>Improvement of analysis part of the program (includes ADC spectrum integration, breakdown voltage characterization, surface scans, relative PDE characterization,...).</li>
<li>Added tooltips for different parts of the program for quick reference. Use them by hovering over any text entries, number entries, check boxes or buttons.</li>
<li>Connection to temperature data and oscilloscope currently under development.</li>
<li>Older version of program moved to <a href="https://f9pc00.ijs.si/svn/f9daq/lab/sipmscan/trunk_v0.9">https://f9pc00.ijs.si/svn/f9daq/lab/sipmscan/trunk_v0.9</a> and will no longer be in development.</li>
</ol><br/>
 
<p>17.7.2015 (Rev 129):</p>
<ol type="a">
<li>Fixed a problem with ADC peak fitting (peak fitting returning a segmentation fault).</li>
<li>Added support to edit file headers (in case, some were created at an older date and did not include some header information or there was a mistake in writing them).</li>
<li>Temperature data can only be retrieved when connected to the IJS network (IP = 178.172.43.xxx) and is disabled otherwise.</li>
<li>The relative PDE measurement now takes the incidence angle value directly from input files.</li>
<li>Currently, data acquisition only works on 32bit computers.</li>
<li>Fixed issue with program not correctly writting multiple channels.</li>
</ol><br/>
 
<p>5.5.2015 (Rev 128):</p>
<ol type="a">
<li>Added a header display for opened files in the histogram file selection window. This enables a quicker view of the measurement information.</li>
<li>Added an incidence angle input to be able to save sample rotation angle to headers of files.</li>
<li>Added support for the fieldpoint temperature sensor (FP RTD 122). Can now plot and export data from the sensor for a specific channel and specific time range. For now, this option only works if the PC you are using this program on is connected to an internet/ethernet connection at IJS.</li>
<li>Added a limited relative PDE analysis option. At this time, it takes the selected files and calculates the PDE, relative to the first selected file. The first file should be measured at incidence angle 0, with others having an incidence angle shift of +15 (1st file -> 0, 2nd file -> 15, 3rd file -> 30,...).</li>
</ol><br/>
 
<p>9.4.2015 (Rev 127):</p>
<ol type="a">
<li>Added communications panel for connecting to a Tektronix scope.</li>
<li>Added limited support for waveform analysis with a Tektronix scope. For now, it only works when linking it to CAMAC acquisition.</li>
<li>Added a manual chamber temperature entry field.</li>
</ol><br/>
 
<p>16.3.2015 (Rev 117):</p>
<ol type="a">
<li>First version of sipmscan.</li>
<li>Added support for CAMAC, bias voltage settings and table position settings.</li>
<li>Added support for opening measured histograms.</li>
<li>Added support for analysis:</li>
<ul>
<li>making surface plots</li>
<li>fitting the ADC spectrum</li>
<li>creating breakdown voltage plots</li>
<li>integrating the ADC spectrum with changing X or Y direction (edge scans)</li>
</ul>
</ol><br/>
 
<div class="backtop"><a href="#top">Back to top</a></div>
 
</div>
 
</body>
</html>
/lab/sipmscan/trunk/doc/style_sheet.css
0,0 → 1,224
a:link
{
text-decoration: underline;
color: blue;
opacity: 1;
filter: alpha(opacity=100);
}
 
a:visited, a:active
{
text-decoration: none;
color: blue;
opacity: 1;
filter: alpha(opacity=100);
}
 
a:hover
{
text-decoration: none;
color: blue;
opacity: 0.6;
filter: alpha(opacity=60);
}
 
h1
{
font-size: 21pt;
}
 
h2
{
font-size: 18pt;
}
 
p span, li span
{
color: red;
font-weight: bold;
}
 
p tt, li tt, ul tt, ol tt
{
background-color: #FFDDEE;
}
 
.midpic
{
display: block;
margin: 0 auto;
}
 
pre
{
padding-left: 5em;
}
 
.codeback
{
background-color: #FFC;
}
 
.tabindent
{
padding-left: 2em;
}
 
.codename
{
text-align: right;
color: #666;
font-weight: bold;
font-size: 10pt;
padding-right: 1em;
padding-top: 0.5em;
}
 
.backtop
{
text-align: center;
color: #666;
font-size: 10pt;
text-decoration: underline;
}
 
.offhome
{
position: fixed;
top: 5px;
right: 5px;
text-align: right;
color: #141;
font-size: 10pt;
padding: 5px;
border: 2px solid black;
background-color: #EEEEFF;
}
 
.offhome a
{
color: #141;
}
 
#footer
{
position: fixed;
bottom: 0px;
width: 100%;
color: #444;
font-size: 9pt;
background-color: #EEEEFF;
padding: 5px;
}
 
#mod
{
/* border: 1px solid red;*/
float: left;
width: 49%;
text-align: left;
}
 
#contact
{
/* border: 1px solid blue;*/
float: left;
width: 49%;
text-align: right;
}
 
#contact a
{
color: #444;
cursor: pointer;
}
 
#add
{
padding-top: 10pt;
padding-bottom: 10pt;
/* background-color: #EEEEFF;*/
}
 
.indexlist
{
font-size: 14pt;
}
 
.indexlist li
{
padding-top: 3px;
padding-bottom: 3px;
}
 
#date
{
margin-bottom: 5px;
}
 
#cores span
{
font-weight: bold;
}
 
#nodes
{
text-align: center;
border: 3px solid black;
border-collapse: collapse;
margin: 8px 0px;
width: 50%;
cursor: default;
}
 
#nodes td
{
border: 2px solid #555555;
padding: 2px 0px;
}
 
[tooltip]:before
{
position: absolute;
content: attr(tooltip);
opacity: 0;
background-color: #EEEEFF;
border: 2px solid black;
font-weight: normal;
font-size: 10pt;
color: #141;
padding: 5px;
margin-top: -5px;
left: 51%;
width: 20%;
}
 
[tooltip]:hover:before
{
opacity: 1;
}
 
.upnode
{
background-color: #77FF77;
}
 
.downnode
{
background-color: #FF7777;
}
 
.allocnode
{
background-color: #BBBBBB;
}
 
.tableheader
{
background-color: #EEEEFF;
}
 
.tableheader th
{
border: 2px solid black;
}
/lab/sipmscan/trunk/include/daq.h
0,0 → 1,36
#ifndef _daq_h_
#define _daq_h_
 
#define BUFF_L 2048
 
// Number of channels we are using (used only if we run daqusb.C, not the GUI version)
//#define NTDC 1 /* TDC */
//#define NTDCCH 1
//#define NADC 2 /* ADC */
//#define NADCCH 1
 
// Class for measurement process (DAQ for CAMAC)
class daq
{
private:
// Number of channels we are using
int NTDC;
int NTDCCH;
int NADC;
int NADCCH;
 
int devDetect; // variable to tell if we detect any devices
public:
unsigned long stackwrite[BUFF_L],stackdata[10000],stackdump[27000];
int fStop;
int connect();
int init(int);
int start();
int event(unsigned int *, int);
int stop();
int disconnect();
daq();
~daq();
};
 
#endif
/lab/sipmscan/trunk/include/daqscope.h
0,0 → 1,84
#ifndef _daqscope_h_
#define _daqscope_h_
 
#define WAVE_LEN 100000
 
//class VmUsbStack;
class daqscope {
public:
int scopeUseType;
int scopeChanNr;
int scopeChans[8];
char scopeChanstring[256];
int scopeMeasSel;
char eventbuf[WAVE_LEN];
double measubuf;
double tektime, tekvolt;
double choffset;
 
int fStop;
double tekunit(char *prefix);
 
int init();
int event();
int customCommand(char *command, bool query, char *sReturn);
int connect(char* IPaddr);
int disconnect(char* IPaddr);
int lockunlock(bool lockit);
daqscope();
~daqscope();
 
// VmUsbStack * fStack;
// VmUsbStack * fInit;
 
/* int OSrepetition;
int OSmeasu;
int OSmeasuchan;
int OSgating;
int OSsaving;
int OSinf;
int nmeaslc;
char OSchannels[1024];
char IP[1024];
char lecroycmd[1024];
char lecroycmd2[1024];
char lecroywfm[1024];
int lecroystate;
char pch[1024];
char lecroyadd[1024];
char multibuf[WAVE_LEN];
char eventbuf[WAVE_LEN];
double tektime,tekvolt,lctime,lcvolt;
int fastacqstate; // GKM - variable that saves the fastacq state
double choffset; // GKM - position offset for signal
 
int fPoints;
int fStop;
int fMode;
int clear();
int end();
int event();
int lecroyevent();
void measurement(float&);
void measulecroy(float&);
void measumult();
int init();
int initlecroy();
int connect(char* IPaddr);
int disconnect(char* IPaddr);
void fileopen(const char*);
void fileclose();
void countcontrol();
void fastacq(int setting); // GKM - gets tek out of fastacq
void header();
void measuheader();
void lecroyheader();
void lecroywave();
double tekunit(char*);
double lcunit(char*);
daqscope();
// daqscope(const char *);
~daqscope();*/
};
 
#endif
/lab/sipmscan/trunk/include/libxxusb.h
0,0 → 1,111
#include "usb.h"
 
 
#define XXUSB_WIENER_VENDOR_ID 0x16DC /* Wiener, Plein & Baus */
#define XXUSB_VMUSB_PRODUCT_ID 0x000B /* VM-USB */
#define XXUSB_CCUSB_PRODUCT_ID 0x0001 /* CC-USB */
#define XXUSB_ENDPOINT_OUT 2 /* Endpoint 2 Out*/
#define XXUSB_ENDPOINT_IN 0x86 /* Endpoint 6 In */
#define XXUSB_FIRMWARE_REGISTER 0
#define XXUSB_GLOBAL_REGISTER 1
#define XXUSB_ACTION_REGISTER 10
#define XXUSB_DELAYS_REGISTER 2
#define XXUSB_WATCHDOG_REGISTER 3
#define XXUSB_SELLEDA_REGISTER 6
#define XXUSB_SELNIM_REGISTER 7
#define XXUSB_SELLEDB_REGISTER 4
#define XXUSB_SERIAL_REGISTER 15
#define XXUSB_LAMMASK_REGISTER 8
#define XXUSB_LAM_REGISTER 12
#define XXUSB_READOUT_STACK 2
#define XXUSB_SCALER_STACK 3
#define XXUSB_NAF_DIRECT 12
 
struct XXUSB_STACK
{
long Data;
short Hit;
short APatt;
short Num;
short HitMask;
};
 
struct XXUSB_CC_COMMAND_TYPE
{
short Crate;
short F;
short A;
short N;
long Data;
short NoS2;
short LongD;
short HitPatt;
short QStop;
short LAMMode;
short UseHit;
short Repeat;
short AddrScan;
short FastCam;
short NumMod;
short AddrPatt;
long HitMask[4];
long Num;
};
 
struct xxusb_device_typ
{
struct usb_device *usbdev;
char SerialString[7];
};
 
typedef struct xxusb_device_typ xxusb_device_type;
typedef unsigned char UCHAR;
typedef struct usb_bus usb_busx;
 
 
int xxusb_longstack_execute(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_bulk_read(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_bulk_write(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_usbfifo_read(usb_dev_handle *hDev, int *DataBuffer, int lDataLen, int timeout);
 
short xxusb_register_read(usb_dev_handle *hDev, short RegAddr, long *RegData);
short xxusb_stack_read(usb_dev_handle *hDev, short StackAddr, long *StackData);
short xxusb_stack_write(usb_dev_handle *hDev, short StackAddr, long *StackData);
short xxusb_stack_execute(usb_dev_handle *hDev, long *StackData);
short xxusb_register_write(usb_dev_handle *hDev, short RegAddr, long RegData);
short xxusb_reset_toggle(usb_dev_handle *hDev);
 
short xxusb_devices_find(xxusb_device_type *xxusbDev);
short xxusb_device_close(usb_dev_handle *hDev);
usb_dev_handle* xxusb_device_open(struct usb_device *dev);
short xxusb_flash_program(usb_dev_handle *hDev, char *config, short nsect);
short xxusb_flashblock_program(usb_dev_handle *hDev, UCHAR *config);
usb_dev_handle* xxusb_serial_open(char *SerialString);
 
short VME_register_write(usb_dev_handle *hdev, long VME_Address, long Data);
short VME_register_read(usb_dev_handle *hdev, long VME_Address, long *Data);
short VME_LED_settings(usb_dev_handle *hdev, int LED, int code, int invert, int latch);
short VME_DGG(usb_dev_handle *hdev, unsigned short channel, unsigned short trigger,unsigned short output, long delay, unsigned short gate, unsigned short invert, unsigned short latch);
 
short VME_Output_settings(usb_dev_handle *hdev, int Channel, int code, int invert, int latch);
 
short VME_read_16(usb_dev_handle *hdev,short Address_Modifier, long VME_Address, long *Data);
short VME_read_32(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long *Data);
short VME_BLT_read_32(usb_dev_handle *hdev, short Address_Modifier, int count, long VME_Address, long Data[]);
short VME_write_16(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long Data);
short VME_write_32(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long Data);
 
short CAMAC_DGG(usb_dev_handle *hdev, short channel, short trigger, short output, int delay, int gate, short invert, short latch);
short CAMAC_register_read(usb_dev_handle *hdev, int A, long *Data);
short CAMAC_register_write(usb_dev_handle *hdev, int A, long Data);
short CAMAC_LED_settings(usb_dev_handle *hdev, int LED, int code, int invert, int latch);
short CAMAC_Output_settings(usb_dev_handle *hdev, int Channel, int code, int invert, int latch);
short CAMAC_read_LAM_mask(usb_dev_handle *hdev, long *Data);
short CAMAC_write_LAM_mask(usb_dev_handle *hdev, long Data);
 
short CAMAC_write(usb_dev_handle *hdev, int N, int A, int F, long Data, int *Q, int *X);
short CAMAC_read(usb_dev_handle *hdev, int N, int A, int F, long *Data, int *Q, int *X);
short CAMAC_Z(usb_dev_handle *hdev);
short CAMAC_C(usb_dev_handle *hdev);
short CAMAC_I(usb_dev_handle *hdev, int inhibit);
 
/lab/sipmscan/trunk/include/root_include.h
0,0 → 1,237
#ifndef _root_include_h_
#define _root_include_h_
 
// ROOT base includes
#ifndef ROOT_TRootBrowser
#include "TRootBrowser.h"
#endif
#ifndef ROOT_IOstream
#include "Riostream.h"
#endif
#ifndef ROOT_TSystem
#include "TSystem.h"
#endif
#ifndef ROOT_TApplication
#include "TApplication.h"
#endif
#ifndef ROOT_TROOT
#include "TROOT.h"
#endif
#ifndef ROOT_TQObject
#include "TQObject.h"
#endif
#ifndef ROOT_RQ_Object
#include "RQ_OBJECT.h"
#endif
#ifndef ROOT_TGClient
#include "TGClient.h"
#endif
#ifndef ROOT_TGResourcePool
#include "TGResourcePool.h"
#endif
#ifndef ROOT_TEnv
#include "TEnv.h"
#endif
#ifndef ROOT_TObjectTable
#include "TObjectTable.h"
#endif
 
// ROOT GUI frame includes
#ifndef ROOT_TGFrame
#include "TGFrame.h"
#endif
#ifndef ROOT_TGDockableFrame
#include "TGDockableFrame.h"
#endif
#ifndef ROOT_TGMenu
#include "TGMenu.h"
#endif
#ifndef ROOT_TGMdiDecorFrame
#include "TGMdiDecorFrame.h"
#endif
#ifndef ROOT_TGMdiFrame
#include "TGMdiFrame.h"
#endif
#ifndef ROOT_TGMdiMainFrame
#include "TGMdiMainFrame.h"
#endif
#ifndef ROOT_TGMdiMenu
#include "TGMdiMenu.h"
#endif
#ifndef ROOT_TGMdi
#include "TGMdi.h"
#endif
#ifndef ROOT_TG3DLine
#include "TG3DLine.h"
#endif
#ifndef ROOT_TGStatusBar
#include "TGStatusBar.h"
#endif
 
// ROOT GUI builder incudes (not needed)
#ifndef ROOT_TRootGuiBuilder
#include "TRootGuiBuilder.h"
#endif
#ifndef ROOT_TGuiBldHintsButton
#include "TGuiBldHintsButton.h"
#endif
#ifndef ROOT_TGuiBldHintsEditor
#include "TGuiBldHintsEditor.h"
#endif
#ifndef ROOT_TGuiBldEditor
#include "TGuiBldEditor.h"
#endif
#ifndef ROOT_TGuiBldDragManager
#include "TGuiBldDragManager.h"
#endif
 
// ROOT GUI object includes
#ifndef ROOT_TGListBox
#include "TGListBox.h"
#endif
#ifndef ROOT_TGNumberEntry
#include "TGNumberEntry.h"
#endif
#ifndef ROOT_TGScrollBar
#include "TGScrollBar.h"
#endif
#ifndef ROOT_TGFileDialog
#include "TGFileDialog.h"
#endif
#ifndef ROOT_TGShutter
#include "TGShutter.h"
#endif
#ifndef ROOT_TGButtonGroup
#include "TGButtonGroup.h"
#endif
#ifndef ROOT_TGCanvas
#include "TGCanvas.h"
#endif
#ifndef ROOT_TGButton
#include "TGButton.h"
#endif
#ifndef ROOT_TGTextEdit
#include "TGTextEdit.h"
#endif
#ifndef ROOT_TGLabel
#include "TGLabel.h"
#endif
#ifndef ROOT_TGView
#include "TGView.h"
#endif
#ifndef ROOT_TGTab
#include "TGTab.h"
#endif
#ifndef ROOT_TGListView
#include "TGListView.h"
#endif
#ifndef ROOT_TGSplitter
#include "TGSplitter.h"
#endif
#ifndef ROOT_TGListTree
#include "TGListTree.h"
#endif
#ifndef ROOT_TGToolTip
#include "TGToolTip.h"
#endif
#ifndef ROOT_TGToolBar
#include "TGToolBar.h"
#endif
#ifndef ROOT_TRootEmbeddedCanvas
#include "TRootEmbeddedCanvas.h"
#endif
#ifndef ROOT_TCanvas
#include "TCanvas.h"
#endif
#ifndef ROOT_TGComboBox
#include "TGComboBox.h"
#endif
#ifndef ROOT_TGProgressBar
#include "TGProgressBar.h"
#endif
#ifndef ROOT_TGTextEntry
#include "TGTextEntry.h"
#endif
#ifndef ROOT_TGMsgBox
#include "TGMsgBox.h"
#endif
#ifndef ROOT_TGSlider
#include "TGSlider.h"
#endif
#ifndef ROOT_TGFSContainer
#include "TGFSContainer.h"
#endif
#ifndef ROOT_TGFSComboBox
#include "TGFSComboBox.h"
#endif
 
// ROOT File browser includes
#ifndef ROOT_TSystemDir
#include "TSystemDirectory.h"
#endif
#ifndef ROOT_TTree
#include "TTree.h"
#endif
#ifndef ROOT_TFile
#include "TFile.h"
#endif
 
// ROOT plotting includes
#ifndef ROOT_TPaveStats
#include "TPaveStats.h"
#endif
#ifndef ROOT_TGraph2D
#include "TGraph2D.h"
#endif
#ifndef ROOT_TLatex
#include "TLatex.h"
#endif
#ifndef ROOT_TGraphErrors
#include "TGraphErrors.h"
#endif
#ifndef ROOT_TStyle
#include "TStyle.h"
#endif
#ifndef ROOT_TPaletteAxis
#include "TPaletteAxis.h"
#endif
#ifndef ROOT_TGraph
#include "TGraph.h"
#endif
#ifndef ROOT_TH1F
#include "TH1F.h"
#endif
#ifndef ROOT_TH2F
#include "TH2F.h"
#endif
#ifndef ROOT_TF1
#include "TF1.h"
#endif
#ifndef ROOT_TSpectrum
#include "TSpectrum.h"
#endif
#ifndef ROOT_TVirtualFitter
#include "TVirtualFitter.h"
#endif
#ifndef ROOT_TMath
#include "TMath.h"
#endif
#ifndef ROOT_TRandom
#include "TRandom.h"
#endif
#ifndef ROOT_TLatex
#include "TLatex.h"
#endif
 
// ROOT MYSQL includes
#ifndef ROOT_TSQLServer
#include <TSQLServer.h>
#endif
#ifndef ROOT_TSQLResult
#include <TSQLResult.h>
#endif
#ifndef ROOT_TSQLRow
#include <TSQLRow.h>
#endif
 
#endif
/lab/sipmscan/trunk/include/sipmscan.h
0,0 → 1,345
#ifndef __ROOT_APP_H__
#define __ROOT_APP_H__
 
//#define winWidth 1240
//#define winHeight 800
#define WINDOW_NAME "CAMAC/MPOD/4MM DAQ software"
#define measwin 3
#define analysiswin 4
#define BSIZE 10000
 
#include "root_include.h"
#include "substructure.h"
#include "daq.h"
#include "daqscope.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <time.h>
 
enum EMenuIds {
M_FILE_SET_LAYOUT,
M_FILE_SAVE_LAYOUT,
M_FILE_SAVE_MSETTINGS,
M_FILE_SAVE_ASETTINGS,
M_FILE_CHECK_WIDTH,
M_FILE_EXIT,
 
M_ANALYSIS_HISTTYPE_1DADC,
M_ANALYSIS_HISTTYPE_1DTDC,
M_ANALYSIS_HISTTYPE_2D,
M_ANALYSIS_INTEG,
M_ANALYSIS_INTEGX,
M_ANALYSIS_INTEGY,
M_ANALYSIS_PHOTMU,
M_ANALYSIS_BREAKDOWN,
M_ANALYSIS_SURFSCAN,
M_ANALYSIS_TIMING,
 
M_HELP_WEBHELP,
M_HELP_ABOUT
};
 
// Separate functions -----------------------------------------
void GetTime(int intime, char *outtime);
void remove_ext(char *inname, char *outname);
void remove_from_last(char *inname, char search, char *outname);
void remove_before_last(char *inname, char search, char *outname);
void layoutMainWindow(int *w, int *h);
void SeqNumber(int innum, int maxnum, char *outstr);
void TimeEstimate(clock_t stopw0, time_t time0, float progress, char *retEstim, int offset);
void NormateSet(int file, int nrpoint, double *min, double *max, double *setCount, double *setAcc);
double PointEstimate(int nrp, double *points);
// Separate functions -----------------------------------------
 
 
// Window classes ----------------------------------------------------
//class TGWindow;
//class TGMainFrame;
 
// Subwindow layout class
/*class TGMdiSubwindow
{
RQ_OBJECT("TGMdiSubwindow")
 
protected:
TGMdiFrame *fMdiFrame;
 
public:
TGMdiSubwindow(TGMdiMainFrame *main, int w, int h);
TGMdiFrame *GetMdiFrame() const { return fMdiFrame; }
// layoutchange is 0 when we close a subwindow and 1 when we change the layout (close multiple subwindows)
virtual Bool_t CloseWindow(int layoutchange);
 
// unique id is set for each subwindow
// settingsPane->id = 0
int id;
};*/
 
// Main window class
class TGAppMainFrame
{
RQ_OBJECT("TGAppMainFrame")
 
protected:
TGMainFrame *fMain;
// TGMdiMainFrame *fMainFrame;
// TGMdiMenuBar *fMenuBar;
TGMenuBar *fMenuBar;
TGLayoutHints *fMenuBarItemLayout;
TGPopupMenu *fMenuFile, *fMenuAnalysis, *fMenuHelp, *fMenuHisttype;
TGTab *fTab, *analTab;
int winWidth;
int winHeight;
// TGMdiSubwindow *settingsPane;
 
// Variables for frame layouts and titles
TGCompositeFrame *fLayout[2];
TGHorizontalFrame *fTitle;
 
void InitMenu();
void AppLayout();
void OpenWindow(int winid);
void CloseWindow();
Bool_t About();
 
int idtotal;
bool cleanPlots;
int logChange;
int selChannel;
bool acqStarted;
unsigned int gBuf[BSIZE];
clock_t clkt0;
time_t timet0;
bool liveUpdate;
int npeaks;
 
public:
TGAppMainFrame(const TGWindow *p, int w, int h);
virtual ~TGAppMainFrame();
 
void HandleMenu(Int_t id);
 
// Splitter to a set number of frames
bool TGSplitter(TGWindow *parent, const char *majorSplit, int *vertSplits, int *horSplits, const char *frameTitles[512], TGCompositeFrame **frames, int *frameWidth, int *frameHeight);
void TGTitleLabel(TGWindow *parent, TGHorizontalFrame *fTitle, const char *title, Pixel_t foreColor, Pixel_t backColor, const char *font);
 
// Layout setup
void LayoutRead(int nrframes, int *w, int *h);
void LayoutSave();
void LayoutSet();
void ToolTipSet();
 
// Subframes where we display everything
TGCompositeFrame *measLayout[measwin];
TGCompositeFrame *analysisLayout[analysiswin];
 
// Substructures for Settings pane (measurement layout)
TSubStructure *scansOn;
TSubStructure *vHardlimit;
TSubStructure *NCH;
TSubStructure *posUnits;
TSubStructure *rotUnits;
TSubStructure *oscConnect;
TSubStructure *laserInfo;
TSubStructure *chtemp;
TSubStructure *liveDisp;
 
// Substructures for Measurement pane (measurement layout)
TSubStructure *vOutCh;
TSubStructure *vOut;
TSubStructure *vOutOpt;
TSubStructure *vOutButtons;
TSubStructure *vOutStart;
TSubStructure *vOutStop;
TSubStructure *vOutStep;
TSubStructure *xPos;
TSubStructure *yPos;
TSubStructure *zPos;
TSubStructure *zPosMin;
TSubStructure *zPosMax;
TSubStructure *zPosStep;
TSubStructure *posButtons;
TSubStructure *xPosMin;
TSubStructure *xPosMax;
TSubStructure *xPosStep;
TSubStructure *yPosMin;
TSubStructure *yPosMax;
TSubStructure *yPosStep;
TSubStructure *rotPos;
TSubStructure *rotButtons;
TSubStructure *rotPosMin;
TSubStructure *rotPosMax;
TSubStructure *rotPosStep;
TSubStructure *evtNum;
TSubStructure *timeStamp;
TSubStructure *fileName;
TSubStructure *measProgress;
 
// Substructures for Display pane (measurement layout)
TRootEmbeddedCanvas *measCanvas;
 
// Action connections for Settings pane (measurement layout)
void EnableScan(int type);
void VoltageLimit();
void ChangeUnits(int type);
void ChangeUnitsRot(int type);
void EnableLiveUpdate();
 
// Action connections for Measurement pane (measurement layout)
int GetChannel();
void NegativePolarity();
void VoltOut(int opt);
void PositionSet(int opt);
void RotationSet(int opt);
void SaveFile();
void StartAcq();
 
// Substructures for Histogram selection pane (analysis layout)
TSubStructure *selectDir;
TGListBox *fileList;
TSubStructure *multiSelect;
TSubStructure *fileListCtrl;
TSubStructure *dispTime;
TSubStructure *dispBias;
TSubStructure *dispPos;
TSubStructure *dispTemp;
TSubStructure *dispAngle;
TSubStructure *dispLaser;
 
// Substructures for Histogram pane (analysis layout)
TRootEmbeddedCanvas *analysisCanvas;
 
// Substructures for Histogram controls pane (analysis layout)
TSubStructure *adcRange;
TSubStructure *tdcRange;
TSubStructure *yRange;
TSubStructure *selectCh;
TSubStructure *plotType;
TSubStructure *histOpt;
TSubStructure *exportHist;
TSubStructure *editSelHist;
 
// Substructures for analysis pane (analysis layout)
TSubStructure *intSpect;
TSubStructure *resol2d;
TSubStructure *intSpectButtons;
 
TSubStructure *relPde;
TSubStructure *midPeak;
TSubStructure *darkRun;
TSubStructure *zeroAngle;
TSubStructure *relPdeButtons;
 
TSubStructure *minPeak;
TSubStructure *peakSepCalc;
TSubStructure *brDownButtons;
 
TSubStructure *surfScanOpt;
TSubStructure *resolSurf;
TSubStructure *surfButtons;
 
TSubStructure *fitSigma;
TSubStructure *fitTresh;
TSubStructure *fitInter;
TSubStructure *adcOffset;
TSubStructure *accError;
TSubStructure *pedesLow;
TSubStructure *fitChecks;
TSubStructure *analysisProgress;
 
// Action connections for Histogram file selection pane (analysis layout)
void SelectDirectory();
void ListMultiSelect(int opt);
void FileListNavigation(int opt);
void HeaderEdit();
void ClearHistogramList();
// Action connections for Histogram controls pane (analysis layout)
void UpdateHistogram(int opt);
void HistogramOptions(int opt);
void ChangeHisttype(int type);
 
// Action connections for analysis pane (analysis layout)
void SelectDarkHist();
void AnalysisDefaults();
void AnalysisHandle(int type);
void IntegSpectrum(TList *files, int direction, int edit);
void PhotonMu(TList *files, int edit);
void PlotEdgeDistribution(TList *files, int filenr, int points, double *min, double *max, double *xy, double *integAcc, int axis, bool edge2d, int edit);
void BreakdownVolt(TList *files, int edit);
void SurfaceScan(TList *files, int edit);
 
// Substructures for Edit file header window (new tab)
TGListBox *editList;
TSubStructure *timeEditDisplay;
TSubStructure *biasEdit;
TSubStructure *xPosEdit;
TSubStructure *yPosEdit;
TSubStructure *zPosEdit;
TSubStructure *tempEdit;
TSubStructure *angleEdit;
TSubStructure *laserEdit;
TSubStructure *editHead;
TSubStructure *editMulti;
TGLabel *selectWarn;
 
// Action connections for Edit file header window (new tab)
void SetWarnings();
void EditTickToggle(int type);
void StartHeaderEdit();
void ShowHeaderEdit(int id);
void HeaderChange(char *histfile, bool *changetype);
void CloseEditTab(int tabval);
 
// Substructures for temporary analysis edit window (new tab)
TRootEmbeddedCanvas *tempAnalysisCanvas;
TSubStructure *runningAver;
TSubStructure *runningOff;
TSubStructure *secondAxis;
TSubStructure *exportExitAnalysis;
// Action connections for temporary analysis edit window (new tab)
void ApplyRunningAver();
void CloseTempAnalysisTab(int tabval);
 
// Additional functions
void DisplayHistogram(char *histfile, int histtype, int opt);
void HeaderEditTab(TGTab *mainTab, bool create, int *tabid);
void TempAnalysisTab(TGTab *mainTab, bool create, int *tabid, int analtype);
void RunMeas(void *ptr, int runCase, int &scanon);
int MyTimer();
 
// ROOT file variable structure -------------------------------
struct EventHeader {
int nrch;
int timestamp;
double biasvolt;
int xpos;
int ypos;
int zpos;
double temperature;
double angle;
char laserinfo[256];
} evtheader;
 
struct EventData {
int adcdata[8];
int tdcdata[8];
} evtdata;
 
struct EventMeas {
double measdata;
} evtmeas;
 
TFile *inroot;
TFile *outroot;
// ROOT file variable structure -------------------------------
 
daq *gDaq;
daqscope *gScopeDaq;
};
 
// -------------------------------------------------------------------
 
#endif
/lab/sipmscan/trunk/include/substructure.h
0,0 → 1,67
#ifndef __TEST_H__
#define __TEST_H__
 
#include "root_include.h"
#include <string.h>
 
// Format for Number Entry fields:
// [digit space] [num type] [neg-pos] [limit] [min limit], [max limit]
//
// [digit space]: Number of spaces for the entered digits (width)
// [num type]: 0 = Integer, 1 = Real one digit, 2 = Real two digits, 3 = Real three digits, 4 = Real four digits, -1 = Arbitrary real
// [neg-pos]: 0 = Any number, 1 = Positive numbers, 2 = Nonnegative numbers
// [limit]: 0 = No limits, 1 = Maximum limit, 2 = Min and Max limits, -1 = Minimum limit
// [min limit], [max limit]: Min and Max limits, if applicable
 
class TSubStructure
{
RQ_OBJECT("TSubStructure")
 
protected:
TGLabel *lab;
TGHorizontalFrame *fH1;
TGLayoutHints *f0, *f0expandX, *f1, *f2, *f3;
public:
TSubStructure();
virtual ~TSubStructure();
 
// Label + Text Entry -> layout can be "oneline", "twoline"
bool TGLabelTEntry(TGWindow *parent, int w, int h, const char *label, const char *deftext, const char *layout);
// Label + Text Entry + Button -> layout can be "oneline", "twoline"
bool TGLabelTEntryButton(TGWindow *parent, int w, int h, const char *label, const char *deftext, const char *buttext, const char *layout);
// Label + Button
bool TGLabelButton(TGWindow *parent, int w, int h, const char *label, const char *buttext, const char *pos);
// Label + Number Entry
bool TGLabelNEntry(TGWindow *parent, int w, int h, const char *label, double defval, double *format, const char *pos);
// Text Entry + Button
bool TGTEntryButton(TGWindow *parent, int w, int h, const char *deftext, const char *buttext);
// Label + Dropdown menu
bool TGLabelDrop(TGWindow *parent, int w, int h, const char *label, int nrentries, const char *entrytext[512], const char *selecttext);
// 2 or more buttons
bool TGMultiButton(TGWindow *parent, int w, int h, int nrbuttons, const char *buttext[512], const char *pos);
// Label + 2 Number Entries
bool TGLabelDoubleNEntry(TGWindow *parent, int w, int h, const char *label, double defval1, double *format1, double defval2, double *format2, const char *pos);
// Checkbutton list (1 - 9) -> layout can be "horizontal", "vertical", "twoline", "threeline"
bool TGCheckList(TGWindow *parent, int w, int h, int nrchecks, const char *labels[512], int *onoff, const char *layout, const char *pos);
// Button + Horizontal progress bar
bool TGButtonProgress(TGWindow *parent, int w, int h, const char *buttext);
// Label + Horizontal progress bar
bool TGLabelProgress(TGWindow *parent, int w, int h, const char *label);
// Button + Horizontal progress bar + Text Entry
bool TGButtonProgressTEntry(TGWindow *parent, int w, int h, const char *buttext, const char *deftext);
// Checkbutton + Number entry
bool TGCheckNEntry(TGWindow *parent, int w, int h, const char *label, int onoff, double defval, double *format, const char *pos);
// Checkbutton + Text entry
bool TGCheckTEntry(TGWindow *parent, int w, int h, const char *label, int onoff, const char *deftext, const char *layout);
 
TGTextEntry *widgetTE;
TGTextButton *widgetTB[6];
TGNumberEntry *widgetNE[2];
TGComboBox *widgetCB;
TGCompositeFrame *outsidebox;
TGCheckButton *widgetChBox[9];
TGHProgressBar *widgetPB;
int id;
};
 
#endif
/lab/sipmscan/trunk/include/usb.h
0,0 → 1,344
/*
* Prototypes, structure definitions and macros.
*
* Copyright (c) 2000-2003 Johannes Erdfelt <johannes@erdfelt.com>
*
* This library is covered by the LGPL, read LICENSE for details.
*
* This file (and only this file) may alternatively be licensed under the
* BSD license as well, read LICENSE for details.
*/
#ifndef __USB_H__
#define __USB_H__
 
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
 
#include <sys/param.h>
#include <dirent.h>
 
/*
* USB spec information
*
* This is all stuff grabbed from various USB specs and is pretty much
* not subject to change
*/
 
/*
* Device and/or Interface Class codes
*/
#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */
#define USB_CLASS_AUDIO 1
#define USB_CLASS_COMM 2
#define USB_CLASS_HID 3
#define USB_CLASS_PRINTER 7
#define USB_CLASS_PTP 6
#define USB_CLASS_MASS_STORAGE 8
#define USB_CLASS_HUB 9
#define USB_CLASS_DATA 10
#define USB_CLASS_VENDOR_SPEC 0xff
 
/*
* Descriptor types
*/
#define USB_DT_DEVICE 0x01
#define USB_DT_CONFIG 0x02
#define USB_DT_STRING 0x03
#define USB_DT_INTERFACE 0x04
#define USB_DT_ENDPOINT 0x05
 
#define USB_DT_HID 0x21
#define USB_DT_REPORT 0x22
#define USB_DT_PHYSICAL 0x23
#define USB_DT_HUB 0x29
 
/*
* Descriptor sizes per descriptor type
*/
#define USB_DT_DEVICE_SIZE 18
#define USB_DT_CONFIG_SIZE 9
#define USB_DT_INTERFACE_SIZE 9
#define USB_DT_ENDPOINT_SIZE 7
#define USB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */
#define USB_DT_HUB_NONVAR_SIZE 7
 
/* All standard descriptors have these 2 fields in common */
struct usb_descriptor_header {
uint8_t bLength;
uint8_t bDescriptorType;
} __attribute__ ((packed));
 
/* String descriptor */
struct usb_string_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wData[1];
} __attribute__ ((packed));
 
/* HID descriptor */
struct usb_hid_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdHID;
uint8_t bCountryCode;
uint8_t bNumDescriptors;
/* uint8_t bReportDescriptorType; */
/* uint16_t wDescriptorLength; */
/* ... */
} __attribute__ ((packed));
 
/* Endpoint descriptor */
#define USB_MAXENDPOINTS 32
struct usb_endpoint_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
uint8_t bRefresh;
uint8_t bSynchAddress;
 
unsigned char *extra; /* Extra descriptors */
int extralen;
};
 
#define USB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */
#define USB_ENDPOINT_DIR_MASK 0x80
 
#define USB_ENDPOINT_TYPE_MASK 0x03 /* in bmAttributes */
#define USB_ENDPOINT_TYPE_CONTROL 0
#define USB_ENDPOINT_TYPE_ISOCHRONOUS 1
#define USB_ENDPOINT_TYPE_BULK 2
#define USB_ENDPOINT_TYPE_INTERRUPT 3
 
/* Interface descriptor */
#define USB_MAXINTERFACES 32
struct usb_interface_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
 
struct usb_endpoint_descriptor *endpoint;
 
unsigned char *extra; /* Extra descriptors */
int extralen;
};
 
#define USB_MAXALTSETTING 128 /* Hard limit */
struct usb_interface {
struct usb_interface_descriptor *altsetting;
 
int num_altsetting;
};
 
/* Configuration descriptor information.. */
#define USB_MAXCONFIG 8
struct usb_config_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t MaxPower;
 
struct usb_interface *interface;
 
unsigned char *extra; /* Extra descriptors */
int extralen;
};
 
/* Device descriptor */
struct usb_device_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} __attribute__ ((packed));
 
struct usb_ctrl_setup {
uint8_t bRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} __attribute__ ((packed));
 
/*
* Standard requests
*/
#define USB_REQ_GET_STATUS 0x00
#define USB_REQ_CLEAR_FEATURE 0x01
/* 0x02 is reserved */
#define USB_REQ_SET_FEATURE 0x03
/* 0x04 is reserved */
#define USB_REQ_SET_ADDRESS 0x05
#define USB_REQ_GET_DESCRIPTOR 0x06
#define USB_REQ_SET_DESCRIPTOR 0x07
#define USB_REQ_GET_CONFIGURATION 0x08
#define USB_REQ_SET_CONFIGURATION 0x09
#define USB_REQ_GET_INTERFACE 0x0A
#define USB_REQ_SET_INTERFACE 0x0B
#define USB_REQ_SYNCH_FRAME 0x0C
 
#define USB_TYPE_STANDARD (0x00 << 5)
#define USB_TYPE_CLASS (0x01 << 5)
#define USB_TYPE_VENDOR (0x02 << 5)
#define USB_TYPE_RESERVED (0x03 << 5)
 
#define USB_RECIP_DEVICE 0x00
#define USB_RECIP_INTERFACE 0x01
#define USB_RECIP_ENDPOINT 0x02
#define USB_RECIP_OTHER 0x03
 
/*
* Various libusb API related stuff
*/
 
#define USB_ENDPOINT_IN 0x80
#define USB_ENDPOINT_OUT 0x00
 
/* Error codes */
#define USB_ERROR_BEGIN 500000
 
/*
* This is supposed to look weird. This file is generated from autoconf
* and I didn't want to make this too complicated.
*/
#if 0
#define USB_LE16_TO_CPU(x) do { x = ((x & 0xff) << 8) | ((x & 0xff00) >> 8); } while(0)
#else
#define USB_LE16_TO_CPU(x)
#endif
 
/* Data types */
struct usb_device;
struct usb_bus;
 
/*
* To maintain compatibility with applications already built with libusb,
* we must only add entries to the end of this structure. NEVER delete or
* move members and only change types if you really know what you're doing.
*/
#ifdef PATH_MAX
#define LIBUSB_PATH_MAX PATH_MAX
#else
#define LIBUSB_PATH_MAX 4096
#endif
struct usb_device {
struct usb_device *next, *prev;
 
char filename[LIBUSB_PATH_MAX + 1];
 
struct usb_bus *bus;
 
struct usb_device_descriptor descriptor;
struct usb_config_descriptor *config;
 
void *dev; /* Darwin support */
 
uint8_t devnum;
 
unsigned char num_children;
struct usb_device **children;
};
 
struct usb_bus {
struct usb_bus *next, *prev;
 
char dirname[LIBUSB_PATH_MAX + 1];
 
struct usb_device *devices;
uint32_t location;
 
struct usb_device *root_dev;
};
 
struct usb_dev_handle;
typedef struct usb_dev_handle usb_dev_handle;
 
/* Variables */
extern struct usb_bus *usb_busses;
 
#ifdef __cplusplus
extern "C" {
#endif
 
/* Function prototypes */
 
/* usb.c */
usb_dev_handle *usb_open(struct usb_device *dev);
int usb_close(usb_dev_handle *dev);
int usb_get_string(usb_dev_handle *dev, int index, int langid, char *buf,
size_t buflen);
int usb_get_string_simple(usb_dev_handle *dev, int index, char *buf,
size_t buflen);
 
/* descriptors.c */
int usb_get_descriptor_by_endpoint(usb_dev_handle *udev, int ep,
unsigned char type, unsigned char index, void *buf, int size);
int usb_get_descriptor(usb_dev_handle *udev, unsigned char type,
unsigned char index, void *buf, int size);
 
/* <arch>.c */
int usb_bulk_write(usb_dev_handle *dev, int ep, const char *bytes, int size,
int timeout);
int usb_bulk_read(usb_dev_handle *dev, int ep, char *bytes, int size,
int timeout);
int usb_interrupt_write(usb_dev_handle *dev, int ep, const char *bytes, int size,
int timeout);
int usb_interrupt_read(usb_dev_handle *dev, int ep, char *bytes, int size,
int timeout);
int usb_control_msg(usb_dev_handle *dev, int requesttype, int request,
int value, int index, char *bytes, int size, int timeout);
int usb_set_configuration(usb_dev_handle *dev, int configuration);
int usb_claim_interface(usb_dev_handle *dev, int interface);
int usb_release_interface(usb_dev_handle *dev, int interface);
int usb_set_altinterface(usb_dev_handle *dev, int alternate);
int usb_resetep(usb_dev_handle *dev, unsigned int ep);
int usb_clear_halt(usb_dev_handle *dev, unsigned int ep);
int usb_reset(usb_dev_handle *dev);
 
#if 1
#define LIBUSB_HAS_GET_DRIVER_NP 1
int usb_get_driver_np(usb_dev_handle *dev, int interface, char *name,
unsigned int namelen);
#define LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP 1
int usb_detach_kernel_driver_np(usb_dev_handle *dev, int interface);
#endif
 
char *usb_strerror(void);
 
void usb_init(void);
void usb_set_debug(int level);
int usb_find_busses(void);
int usb_find_devices(void);
struct usb_device *usb_device(usb_dev_handle *dev);
struct usb_bus *usb_get_busses(void);
 
#ifdef __cplusplus
}
#endif
 
#endif /* __USB_H__ */
 
/lab/sipmscan/trunk/include/vxi11_i686/CHANGELOG.txt
0,0 → 1,199
------------------------------------------------------------------------------
vxi11_1.08 - 3/09/2009
 
Added a sanity check for link->maxRecvSize to make sure it's >0. This gets
around a bug in some versions of the Agilent Infiniium scope software.
 
Changed the erroneous strncpy() to memcpy() in vxi11_send, as we could be
sending binary data (not just strings).
 
Changed a lot of char *'s to const char *'s in an attempt to get rid of
pedantic gcc compiler warnings.
 
------------------------------------------------------------------------------
vxi11_1.07 - 9/10/2007
 
Minor change to vxi11_receive_data_block(), this fn now copes with instruments
that return just "#0" (for whatever reason). Suggestion by Jarek Sadowski,
gratefully received.
 
------------------------------------------------------------------------------
vxi11_1.06 - 31/08/2007
 
Bug fix in vxi11_receive(), to ensure that no more than "len" bytes are ever
received (and so avoiding a segmentation fault). This was a bug introduced in
release 1.04 whilst making some other changes to the vxi11_receive() fn.
 
Many thanks to Rob Penny for spotting the bug and providing a patch.
 
------------------------------------------------------------------------------
vxi11_1.05 - 11/07/2007
 
Added the ability to specify a "device name" when calling vxi11_open_device().
For regular VXI11-based instruments, such as scopes and AFGs, the device name
is usually "hard wired" to be "inst0", and up to now this has been hard wired
into the vxi11_user code. However, devices such as LAN to GPIB gateways need
some way of distinguishing between different devices... they are a single
client (one IP address), with multiple devices.
 
The vxi11_user fn, vxi11_open_device(), now takes a third argument
(char *device).
This gets passed to the core vxi11_open_device() fn (the one that deals with
separate clients and links), and the core vxi11_open_link() fn; these two
core functions have also had an extra parameter added accordingly. In order
to not break the API, a wrapper function is provided in the form of the
original vxi11_open_device() fn, that just takes 2 arguments
(char *ip, CLINK *clink), this then passes "inst0" as the device argument.
Backwards-compatible wrappers for the core functions have NOT been provided.
These are generally not used from userland anyway. Hopefully this won't
upset anyone!
 
vxi11_cmd, the simple test utility, has also been updated. You can now,
optionally, pass the device_name as a second argument (after the ip
address). The source has been renamed to vxi11_cmd.cc (from vxi11_cmd.c), as
it is C++ code not C.
 
Some minor tidying up in vxi11_user.h
 
With thanks to Oliver Schulz for bringing LAN to GPIB gateways to my
attention, for suggesting changes to the vxi11_user library to allow them to
be accommodated, and for tidying some things up.
 
------------------------------------------------------------------------------
vxi11_1.04 - 10/07/2007
 
Patch applied, which was kindly provided by Robert Larice. This sorts out
the confusion (on my part) about the structures returned by the rpcgen
generated *_1() functions... these are statically allocated temporary structs,
apparently. In the words of Robert Larice:
 
******
Hello Dr. Sharples,
 
I'm sending some patches for your nice gem "vxi11_1.03"
 
In the source code there were some strange comments, concerning
a commented free() around ... Manfred S. ...
and some notes, suggesting you had trouble to get more than one link
working.
 
I think thats caused by some misuse of the rpcgen generated subroutines.
1) those rpcgen generated *_1 functions returned pointers to
statically allocated temporary structs.
those where meant to be instantly copied to the user's space,
which wasn't done
thus instead of
Device_ReadResp *read_resp;
read_resp = device_read_1(...)
one should have written someting like:
Device_ReadResp *read_resp;
read_resp = malloc(...)
memcpy(read_resp, device_read_1(...), ...)
2) but a better fix is to use the rpcgen -M Flag
which allows to pass the memory space as a third argument
so one can write
Device_ReadResp *read_resp;
read_resp = malloc(...)
device_read_1(..., read_resp, ...)
furthermore this is now automatically thread save
3) the rpcgen function device_read_1
expects a target buffer to be passed via read_resp
which was not done.
4) the return value of vxi11_receive() was computed incorrectly
5) minor, Makefile typo's
CFLAGS versus
CLFAGS
 
******
 
Robert didn't have more than one device to try the patch with, but I've just
tried it and everything seems fine. So I've removed all references to the
VXI11_ENABLE_MULTIPLE_CLIENTS global variable, and removed the call to
vxi11_open_link() from the vxi11_send() fn. There has been an associated
tidying of functions, and removal of some comments.
 
Thanks once again to Robert Larice for the patch and the explanation!
 
------------------------------------------------------------------------------
vxi11_1.03 - 29/01/2007
 
Some bug-fixes (thanks to Manfred S.), and extra awareness of the
possibility that instruments could time out after receiving a query WITHOUT
causing an error condition. In some cases (prior to these changes) this
could have resulted in a segmentation fault.
 
Specifically:
 
(1) removed call to ANSI free() fn in vxi11_receive, which according to
Manfred S. "is not necessary and wrong (crashes)".
 
(2) added extra check in vxi11_receive() to see if read_resp==NULL.
read_resp can apparently be NULL if (eg) you send an instrument a
query, but the instrument is so busy with something else for so long
that it forgets the original query. So this extra check is for that
situation, and vxi11_receive returns -VXI11_NULL_READ_RESP to the
calling function.
 
(3) vxi11_send_and_receive() is now aware of the possibility of being
returned -VXI11_NULL_READ_RESP. If so, it re-sends the query, until
either getting a "regular" read error (read_resp->error!=0) or a
successful read.
 
(4) Similar to (2)... added extra check in vxi11_send() to see if
write_resp==NULL. If so, return -VXI11_NULL_WRITE_RESP. As with (3),
send_and_receive() is now aware of this possibility.
 
------------------------------------------------------------------------------
vxi11_1.02 - 25/08/2006
 
Important changes to the core vxi11_send() function, which should be
invisible to the user.
 
For those interested, the function now takes note of the value of
link->maxRecvSize, which is the maximum number of bytes that the vxi11
intrument you're talking to can receive in one go. For many instruments
this may be a few kB, which isn't a problem for sending short commands;
however, sending large chunks of data (for example sending waveforms
to instruments) may exceed this maxRecvSize. The core vxi11_send() function
has been re-written to ensure that only a maximum of [maxRecvSize] bytes are
written in one go... the function sits in a loop until all the message/
data is written.
 
Also tidied up some of the return values (specifically with regard to
vxi11_send() and vxi11_send_data_block() ).
 
------------------------------------------------------------------------------
vxi11_1.01 - 06/07/2006
 
Fair few changes since v1.00, all in vxi11_user.c and vxi11_user.h
 
Found I was having problems talking to multiple links on the same
client, if I created a different client for each one. So introduced
a few global variables to keep track of all the ip addresses of
clients that the library is asked to create, and only creating new
clients if the ip address is different. This puts a limit of how
many unique ip addresses (clients) a single process can connect to.
Set this value at 256 (should hopefully be enough!).
 
Next I found that talking to different clients on different ip
addresses didn't work. It turns out that create_link_1() creates
a static structure. This this link is associated with a given
client (and hence a given IP address), then the only way I could
think of making things work was to add a call to an
vxi11_open_link() function before each send command (no idea what
this adds to overheads and it's very messy!) - at least I was
able to get this to only happen when we are using more than one
client/ip address.
 
Also, while I was at it, I re-ordered the functions a little -
starts with core user functions, extra user functions, then core
library functions at the end. Added a few more comments. Tidied
up. Left some debugging info in, but commented out.
 
------------------------------------------------------------------------------
vxi11_1.00 - 23/06/2006
 
Initial release.
 
------------------------------------------------------------------------------
 
/lab/sipmscan/trunk/include/vxi11_i686/GNU_General_Public_License.txt
0,0 → 1,340
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
 
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
 
Preamble
 
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
 
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
 
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
 
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
 
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
 
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
 
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
 
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
 
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
 
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
 
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
 
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
 
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
 
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
 
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
 
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
 
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
 
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
 
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
 
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
 
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
 
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
 
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
 
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
 
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
 
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
 
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
 
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
 
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
 
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
 
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
 
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
 
NO WARRANTY
 
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
 
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
 
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
 
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
 
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
 
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 
Also add information on how to contact you by electronic and paper mail.
 
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
 
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
 
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
 
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
 
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
 
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
 
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
/lab/sipmscan/trunk/include/vxi11_i686/Makefile
0,0 → 1,18
VERSION=1.08
 
#CFLAGS = -Wall -g
CFLAGS = -g
CXX = g++
 
.PHONY: clean objs
 
objs: vxi11.h
$(CXX) -c -fPIC $(CFLAGS) vxi11_user.cc
$(CXX) -c -fPIC $(CFLAGS) vxi11_clnt.c
$(CXX) -c -fPIC $(CFLAGS) vxi11_xdr.c
 
vxi11.h: vxi11.x
rpcgen -M vxi11.x
 
clean:
rm -f *.o vxi11_cmd vxi11.h vxi11_svc.c vxi11_xdr.c vxi11_clnt.c #TAGS
/lab/sipmscan/trunk/include/vxi11_i686/vxi11.x
0,0 → 1,317
/* This file, vxi11.x, is the amalgamation of vxi11core.rpcl and vxi11intr.rpcl
* which are part of the asynDriver (R4-5) EPICS module, which, at time of
* writing, is available from:
* http://www.aps.anl.gov/epics/modules/soft/asyn/index.html
* More general information about EPICS is available from:
* http://www.aps.anl.gov/epics/
* This code is open source, and is covered under the copyright notice and
* software license agreement shown below, and also at:
* http://www.aps.anl.gov/epics/license/open.php
*
* In order to comply with section 4.3 of the software license agreement, here
* is a PROMINENT NOTICE OF CHNAGES TO THE SOFTWARE
* ===========================================
* (1) This file, vxi11.x, is the concatenation of the files vxi11core.rpcl and
* vxi11intr.rpcl
* (2) Tab spacing has been tidied up
*
* It is intended as a lightweight base for the vxi11 rpc protocol. If you
* run rpcgen on this file, it will generate C files and headers, from which
* it is relatively simple to write C programs to communicate with a range
* of ethernet-enabled instruments, such as oscilloscopes and function
* generated by manufacturers such as Agilent and Tektronix (amongst many
* others).
*
* For what it's worth, this concatenation was done by Steve Sharples at
* the University of Nottingham, UK, on 1 June 2006.
*
* Copyright notice and software license agreement follow, then the
* original comments from vxi11core.rpcl etc.
*
******************************************************************************
* Copyright © 2006 <University of Chicago and other copyright holders>. All
* rights reserved.
******************************************************************************
*
******************************************************************************
* vxi11.x is distributed subject to the following license conditions:
* SOFTWARE LICENSE AGREEMENT
* Software: vxi11.x
*
* 1. The "Software", below, refers to vxi11.x (in either source code, or
* binary form and accompanying documentation). Each licensee is addressed
* as "you" or "Licensee."
*
* 2. The copyright holders shown above and their third-party licensors hereby
* grant Licensee a royalty-free nonexclusive license, subject to the
* limitations stated herein and U.S. Government license rights.
*
* 3. You may modify and make a copy or copies of the Software for use within
* your organization, if you meet the following conditions:
* 1. Copies in source code must include the copyright notice and this
* Software License Agreement.
* 2. Copies in binary form must include the copyright notice and this
* Software License Agreement in the documentation and/or other
* materials provided with the copy.
*
* 4. You may modify a copy or copies of the Software or any portion of it,
* thus forming a work based on the Software, and distribute copies of such
* work outside your organization, if you meet all of the following
* conditions:
* 1. Copies in source code must include the copyright notice and this
* Software License Agreement;
* 2. Copies in binary form must include the copyright notice and this
* Software License Agreement in the documentation and/or other
* materials provided with the copy;
* 3. Modified copies and works based on the Software must carry
* prominent notices stating that you changed specified portions of
* the Software.
*
* 5. Portions of the Software resulted from work developed under a U.S.
* Government contract and are subject to the following license: the
* Government is granted for itself and others acting on its behalf a
* paid-up, nonexclusive, irrevocable worldwide license in this computer
* software to reproduce, prepare derivative works, and perform publicly
* and display publicly.
*
* 6. WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF
* ANY KIND. THE COPYRIGHT HOLDERS, THEIR THIRD PARTY LICENSORS, THE UNITED
* STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND THEIR EMPLOYEES: (1)
* DISCLAIM ANY WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, TITLE OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY
* OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR USEFULNESS OF THE
* SOFTWARE, (3) DO NOT REPRESENT THAT USE OF THE SOFTWARE WOULD NOT INFRINGE
* PRIVATELY OWNED RIGHTS, (4) DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION
* UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL BE CORRECTED.
*
* 7. LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT HOLDERS, THEIR
* THIRD PARTY LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF
* ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
* CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF ANY KIND OR NATURE,
* INCLUDING BUT NOT LIMITED TO LOSS OF PROFITS OR LOSS OF DATA, FOR ANY
* REASON WHATSOEVER, WHETHER SUCH LIABILITY IS ASSERTED ON THE BASIS OF
* CONTRACT, TORT (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE,
* EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE POSSIBILITY OF SUCH
* LOSS OR DAMAGES.
******************************************************************************
*/
 
/******************************************************************************
*
* vxi11core.rpcl
*
* This file is best viewed with a tabwidth of 4
*
******************************************************************************
*
* TODO:
*
******************************************************************************
*
* Original Author: someone from VXIbus Consortium
* Current Author: Benjamin Franksen
* Date: 03-06-97
*
* RPCL description of the core- and abort-channel of the TCP/IP Instrument
* Protocol Specification.
*
*
* Modification Log:
* -----------------
* .00 03-06-97 bfr created this file
*
******************************************************************************
*
* Notes:
*
* This stuff is literally from
*
* VXI-11, Ref 1.0 : TCP/IP Instrument Protocol Specification
*
*/
 
typedef long Device_Link;
 
enum Device_AddrFamily
{
DEVICE_TCP,
DEVICE_UDP
};
 
typedef long Device_Flags;
 
typedef long Device_ErrorCode;
 
struct Device_Error
{
Device_ErrorCode error;
};
 
struct Create_LinkParms
{
long clientId; /* implementation specific value */
bool lockDevice; /* attempt to lock the device */
unsigned long lock_timeout; /* time to wait for lock */
string device<>; /* name of device */
};
struct Create_LinkResp
{
Device_ErrorCode error;
Device_Link lid;
unsigned short abortPort; /* for the abort RPC */
unsigned long maxRecvSize; /* max # of bytes accepted on write */
};
struct Device_WriteParms
{
Device_Link lid; /* link id from create_link */
unsigned long io_timeout; /* time to wait for I/O */
unsigned long lock_timeout; /* time to wait for lock */
Device_Flags flags; /* flags with options */
opaque data<>; /* the data length and the data itself */
};
struct Device_WriteResp
{
Device_ErrorCode error;
unsigned long size; /* # of bytes written */
};
struct Device_ReadParms
{
Device_Link lid; /* link id from create_link */
unsigned long requestSize; /* # of bytes requested */
unsigned long io_timeout; /* time to wait for I/O */
unsigned long lock_timeout; /* time to wait for lock */
Device_Flags flags; /* flags with options */
char termChar; /* valid if flags & termchrset */
};
struct Device_ReadResp
{
Device_ErrorCode error;
long reason; /* why read completed */
opaque data<>; /* the data length and the data itself */
};
struct Device_ReadStbResp
{
Device_ErrorCode error;
unsigned char stb; /* the returned status byte */
};
struct Device_GenericParms
{
Device_Link lid; /* link id from create_link */
Device_Flags flags; /* flags with options */
unsigned long lock_timeout; /* time to wait for lock */
unsigned long io_timeout; /* time to wait for I/O */
};
struct Device_RemoteFunc
{
unsigned long hostAddr; /* host servicing interrupt */
unsigned long hostPort; /* valid port # on client */
unsigned long progNum; /* DEVICE_INTR */
unsigned long progVers; /* DEVICE_INTR_VERSION */
Device_AddrFamily progFamily; /* DEVICE_UDP | DEVICE_TCP */
};
struct Device_EnableSrqParms
{
Device_Link lid; /* link id from create_link */
bool enable; /* enable or disable intr's */
opaque handle<40>; /* host specific data */
};
struct Device_LockParms
{
Device_Link lid; /* link id from create_link */
Device_Flags flags; /* contains the waitlock flag */
unsigned long lock_timeout; /* time to wait for lock */
};
struct Device_DocmdParms
{
Device_Link lid; /* link id from create_link */
Device_Flags flags; /* flags with options */
unsigned long io_timeout; /* time to wait for I/O */
unsigned long lock_timeout; /* time to wait for lock */
long cmd; /* which command to execute */
bool network_order; /* client's byte order */
long datasize; /* size of individual data elements */
opaque data_in<>; /* docmd data parameters */
};
struct Device_DocmdResp
{
Device_ErrorCode error;
opaque data_out<>; /* returned data parameters */
};
 
program DEVICE_ASYNC
{
version DEVICE_ASYNC_VERSION
{
Device_Error device_abort (Device_Link) = 1;
} = 1;
} = 0x0607B0;
 
program DEVICE_CORE
{
version DEVICE_CORE_VERSION
{
Create_LinkResp create_link (Create_LinkParms) = 10;
Device_WriteResp device_write (Device_WriteParms) = 11;
Device_ReadResp device_read (Device_ReadParms) = 12;
Device_ReadStbResp device_readstb (Device_GenericParms) = 13;
Device_Error device_trigger (Device_GenericParms) = 14;
Device_Error device_clear (Device_GenericParms) = 15;
Device_Error device_remote (Device_GenericParms) = 16;
Device_Error device_local (Device_GenericParms) = 17;
Device_Error device_lock (Device_LockParms) = 18;
Device_Error device_unlock (Device_Link) = 19;
Device_Error device_enable_srq (Device_EnableSrqParms) = 20;
Device_DocmdResp device_docmd (Device_DocmdParms) = 22;
Device_Error destroy_link (Device_Link) = 23;
Device_Error create_intr_chan (Device_RemoteFunc) = 25;
Device_Error destroy_intr_chan (void) = 26;
} = 1;
} = 0x0607AF;
 
/******************************************************************************
*
* vxi11intr.rpcl
*
* This file is best viewed with a tabwidth of 4
*
******************************************************************************
*
* TODO:
*
******************************************************************************
*
* Original Author: someone from VXIbus Consortium
* Current Author: Benjamin Franksen
* Date: 03-06-97
*
* RPCL description of the intr-channel of the TCP/IP Instrument Protocol
* Specification.
*
*
* Modification Log:
* -----------------
* .00 03-06-97 bfr created this file
*
******************************************************************************
*
* Notes:
*
* This stuff is literally from
*
* "VXI-11, Ref 1.0 : TCP/IP Instrument Protocol Specification"
*
*/
 
struct Device_SrqParms
{
opaque handle<>;
};
 
program DEVICE_INTR
{
version DEVICE_INTR_VERSION
{
void device_intr_srq (Device_SrqParms) = 30;
} = 1;
} = 0x0607B1;
/lab/sipmscan/trunk/include/vxi11_i686/vxi11_cmd.cc
0,0 → 1,237
/*Predelava vmesnika vxi11 za lastne potrebe IJS F9*/
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "vxi11_user.h"
#define BUF_LEN 100000
 
CLINK *clink;
FILE *test,*test1;
 
int query(char *mycmd){
char buf[BUF_LEN];
 
memset(buf, 0, BUF_LEN);
vxi11_send(clink, mycmd);
int bytes_returned = vxi11_receive(clink, buf, BUF_LEN);
if (bytes_returned > 0) {
printf("%s\n",buf);
} else if (bytes_returned == -15) printf("*** [ NOTHING RECEIVED ] ***\n");
 
return 0;
}
 
int command(char *mycmd){
char buf[BUF_LEN];
 
memset(buf, 0, BUF_LEN);
vxi11_send(clink, mycmd);
 
return 0;
}
 
int queryrep(char *mycmd,char *mycmp,int i){
char buf[BUF_LEN];
 
memset(buf, 0, BUF_LEN);
vxi11_send(clink, mycmd);
int bytes_returned = vxi11_receive(clink, buf, BUF_LEN);
 
if(strcmp(buf,mycmp)!=0){
if (bytes_returned > 0) fprintf(test1,"%d %s",i,buf);
else if (bytes_returned == -15) printf("*** [ NOTHING RECEIVED ] ***\n");
}
strcpy(mycmp,buf);
 
return 0;
}
 
/*float *fbuf;
fbuf= (float *) buf;
if (bytes_returned > 0){
for (int j=1;j<3;j++) printf("%f\n",fbuf[j]);
}
*/
 
int main(void) {
 
static char *device_ip;
static char *device_name;
char cmd[256],ukaz[256],end[256];
char buf[BUF_LEN],pr1[BUF_LEN],pr2[BUF_LEN];
int ret;
long bytes_returned;
 
int i,m,vnos;
 
clink = new CLINK;
time_t t1,t2;
 
/*
fread(buf,1,size,fp);
float *fbuf=(float *) buf;
fbuf[0]
 
*/
memset(ukaz, 0, 256);
printf("\nIJS F9 - September 2010 - Pripravil: Jaka Mur - Beta verzija\n\nProgram za povezavo in nadzor Tektronix ali LeCroy osciloskopa.\nAvtomatsko se program poveze z IP naslovom 194.249.156.91.\nVnesi 'a' za nadaljevanje, 'q' za izhod ali IP za drugo napravo: ");
while(1){
scanf("%s",&ukaz);
if (strncasecmp(ukaz, "q",1) == 0) return 0;
 
else if (strncasecmp(ukaz, "a",1) != 0) ret=vxi11_open_device(ukaz,clink);
else ret=vxi11_open_device("194.249.156.91",clink); //privzeti IP naprave
printf("\nPovezan z ");
memset(buf, 0, BUF_LEN);
vxi11_send(clink, "*IDN?");
bytes_returned = vxi11_receive(clink, buf, BUF_LEN);
if (bytes_returned > 0) {
printf("%s",buf);
break;}
else if (bytes_returned == -15) {
printf("Error.");
if (strncasecmp(ukaz, "a",1) == 0) ret=vxi11_close_device("194.249.156.91",clink);
else ret=vxi11_close_device(ukaz,clink);
return 0;
}
}
 
printf("\nNekatere pomembnejse nastavitve:\n");
command("HEADER ON");
command("DATA:SOURCE CH1");
query("DAT?");
char odg[256];
printf("Zelite spreminjati nastavitve? y/n/q: ");
scanf("%s",&odg);
fgets(cmd,256,stdin);
 
if (strncasecmp(odg, "q",1) == 0) {
if (strncasecmp(ukaz, "a",1) == 0) ret=vxi11_close_device("194.249.156.91",clink);
else ret=vxi11_close_device(ukaz,clink);
return 0;
}
else if (strncasecmp(odg, "y",1) == 0){
printf("\nSpisek komand je v Programmer Manualu!\n");
while(1){
memset(cmd, 0, 256);
memset(buf, 0, BUF_LEN);
 
printf("Vnesi ukaz, vprasanje, 'q' za izhod ali 'x' za nadaljevanje: ");
fgets(cmd,256,stdin);
cmd[strlen(cmd)-1] = 0;
if (strncasecmp(cmd, "q",1) == 0) {
if (strncasecmp(ukaz, "a",1) == 0) ret=vxi11_close_device("194.249.156.91",clink);
else ret=vxi11_close_device(ukaz,clink);
return 0;
}
if (strncasecmp(cmd, "x",1) == 0) break;
 
if (vxi11_send(clink, cmd) < 0) break;
if (strstr(cmd, "?") != 0) {
bytes_returned = vxi11_receive(clink, buf, BUF_LEN);
if (bytes_returned > 0) {
printf("%s\n",buf);
}
else if (bytes_returned == -15) {
printf("*** [ NOTHING RECEIVED ] ***\n");
}
else break;
}
}
}
 
command("HEADER OFF");
 
printf("\nIzbor serije meritev\n1 = za zapis waveformov v binarnem formatu\n2 = MEASU:IMM test\n3 = Shenanigans\nVnesi #: ");
scanf("%d",&vnos);
//prva opcija
if (vnos==1){
 
printf("\nTrenutno je nastavljeno zapisovanje celotnih waveformov iz CH1 v datoteko 'test.txt'. Vnesite zeljeno stevilo ponovitev: ");
scanf("%d",&m);
test=fopen("/media/disk/vxi11_1.08/test.txt","w");
command("DATA:SOURCE CH1");
command("DATA:START 1");
command("DATA:STOP 1000");
command("DATA:ENCDG RPBINARY");
 
(void) time(&t1);
query("ACQUIRE:NUMFRAMESACQUIRED?");
for(i=1;i<m+1;i++) { //zajem binarnih podatkov
memset(buf, 0, BUF_LEN);
vxi11_send(clink, "CURVE?");
int bytes_returned = vxi11_receive(clink, buf, BUF_LEN);
 
if (bytes_returned > 0) fwrite(buf,1,bytes_returned,test);
if(strcmp(buf,pr1)!=0){
if (bytes_returned > 0) fwrite(buf,1,1000,test);
else if (bytes_returned == -15) printf("*** [ NOTHING RECEIVED ] ***\n");
}
strcpy(pr1,buf);
}
 
query("ACQUIRE:NUMFRAMESACQUIRED?");
(void) time(&t2);
printf("Koncano!\n");
printf("Trajanje: %ld s\n",(int)t2-t1);
fclose(test);
 
}
//druga opcija
else if (vnos==2){
 
test1=fopen("/media/disk/vxi11_1.08/test1.txt","w");
 
printf("Vnesi zeljeno stevilo meritev minimuma LeCroy: ");
scanf("%d",&m);
 
for (i=0;i<m;i++) queryrep("C1:PAVA? MIN",pr2,i);
 
fclose(test1);
}
//tretja opcija
else if (vnos==3){
 
test1=fopen("/media/disk/vxi11_1.08/test1.txt","w");
 
printf("Vnesi zeljeno stevilo zajemov: ");
scanf("%d",&m);
command("DATA:SOURCE CH1, CH2");
command("DATA:START 1");
command("DATA:STOP 1000");
command("DATA:ENCDG ASCII");
query("ACQUIRE:NUMFRAMESACQUIRED?");
 
for (i=0;i<m;i++) queryrep("CURVE?",pr2,i);
 
query("ACQUIRE:NUMFRAMESACQUIRED?");
 
fclose(test1);
}
 
if (strncasecmp(ukaz, "a",1) == 0) ret=vxi11_close_device("194.249.156.91",clink);
else ret=vxi11_close_device(ukaz,clink);
printf("Meritve opravljene!\nZa zakljucek pritisni 'q'! ");
scanf("%s",&end);
 
if (strcmp(end,"q")==0);
 
return 0;
}
 
/lab/sipmscan/trunk/include/vxi11_i686/vxi11_user.cc
0,0 → 1,728
/* Revision history: */
/* $Id: vxi11_user.cc,v 1.17 2008/10/20 07:59:54 sds Exp $ */
/*
* $Log: vxi11_user.cc,v $
* Revision 1.17 2008/10/20 07:59:54 sds
* Removed Manfred's surname at his request from the comments/acknowledgments.
*
* Revision 1.16 2008/09/03 14:30:13 sds
* added sanity check for link->maxRecvSize to make sure it's >0.
* This got around a bug in some versions of the Agilent Infiniium
* scope software.
*
* Revision 1.15 2007/10/30 12:55:15 sds
* changed the erroneous strncpy() to memcpy() in vxi11_send,
* as we could be sending binary data (not just strings).
*
* Revision 1.14 2007/10/30 12:46:48 sds
* changed a lot of char *'s to const char *'s in an attempt to get
* rid of pedantic gcc compiler warnings.
*
* Revision 1.13 2007/10/09 08:42:57 sds
* Minor change to vxi11_receive_data_block(), this fn now
* copes with instruments that return just "#0" (for whatever
* reason). Suggestion by Jarek Sadowski.
*
* Revision 1.12 2007/08/31 10:32:39 sds
* Bug fix in vxi11_receive(), to ensure that no more than "len"
* bytes are ever received (and so avoiding a segmentation fault).
* This was a bug introduced in release 1.04 (RCS 1.10) whilst
* making some other changes to the vxi11_receive() fn. Many thanks
* to Rob Penny for spotting the bug and providing a patch.
*
* Revision 1.11 2007/07/10 13:49:18 sds
* Changed the vxi11_open_device() fn to accept a third argument, char *device.
* This gets passed to the core vxi11_open_device() fn (the one that deals with
* separate clients and links), and the core vxi11_open_link() fn; these two
* core functions have also had an extra parameter added accordingly. In order
* to not break the API, a wrapper function is provided in the form of the
* original vxi11_open_device() fn, that just takes 2 arguments
* (char *ip, CLINK *clink), this then passes "inst0" as the device argument.
* Backwards-compatible wrappers for the core functions have NOT been provided.
* These are generally not used from userland anyway. Hopefully this won't
* upset anyone!
*
* Revision 1.10 2007/07/10 11:12:12 sds
* Patches provided by Robert Larice. This basically solves the problem
* of having to recreate a link each time you change client. In the words
* of Robert:
*
* ---------
* In the source code there were some strange comments, suggesting
* you had trouble to get more than one link working.
*
* I think thats caused by some misuse of the rpcgen generated subroutines.
* 1) those rpcgen generated *_1 functions returned pointers to
* statically allocated temporary structs.
* those where meant to be instantly copied to the user's space,
* which wasn't done, thus instead of
* Device_ReadResp *read_resp;
* read_resp = device_read_1(...)
* one should have written someting like:
* Device_ReadResp *read_resp;
* read_resp = malloc(...)
* memcpy(read_resp, device_read_1(...), ...)
* 2) but a better fix is to use the rpcgen -M Flag
* which allows to pass the memory space as a third argument
* so one can write
* Device_ReadResp *read_resp;
* read_resp = malloc(...)
* device_read_1(..., read_resp, ...)
* furthermore this is now automatically thread save
* 3) the rpcgen function device_read_1
* expects a target buffer to be passed via read_resp
* which was not done.
* 4) the return value of vxi11_receive() was computed incorrectly
* 5) minor, Makefile typo's
* ---------
* So big thanks to Robert Larice for the patch! I've tested it
* (briefly) on more than one scope, and with multiple links per
* client, and it seems to work fine. I've thus removed all references
* to VXI11_ENABLE_MULTIPLE_CLIENTS, and deleted the vxi11_open_link()
* function that WASN'T passed an ip address (that was only called
* from the vxi11_send() fn, when there was more than one client).
*
* Revision 1.9 2006/12/08 12:06:58 ijc
* Basically the same changes as revision 1.8, except replace all
* references to "vxi11_receive" with "vxi11_send" and all references
* to "-VXI11_NULL_READ_RESP" with "-VXI11_NULL_WRITE_RESP".
*
* Revision 1.8 2006/12/07 12:22:20 sds
* Couple of changes, related.
* (1) added extra check in vxi11_receive() to see if read_resp==NULL.
* read_resp can apparently be NULL if (eg) you send an instrument a
* query, but the instrument is so busy with something else for so long
* that it forgets the original query. So this extra check is for that
* situation, and vxi11_receive returns -VXI11_NULL_READ_RESP to the
* calling function.
* (2) vxi11_send_and_receive() is now aware of the possibility of
* being returned -VXI11_NULL_READ_RESP. If so, it re-sends the query,
* until either getting a "regular" read error (read_resp->error!=0) or
* a successful read.
*
* Revision 1.7 2006/12/06 16:27:47 sds
* removed call to ANSI free() fn in vxi11_receive, which according to
* Manfred S. "is not necessary and wrong (crashes)".
*
* Revision 1.6 2006/08/25 13:45:12 sds
* Major improvements to the vxi11_send function. Now takes
* link->maxRecvSize into account, and writes a chunk at a time
* until the entire message is sent. Important for sending large
* data sets, because the data you want to send may be larger than
* the instrument's "input buffer."
*
* Revision 1.5 2006/08/25 13:06:44 sds
* tidied up some of the return values, and made sure that if a
* sub-function returned an error value, this would also be
* returned by the calling function.
*
* Revision 1.4 2006/07/06 13:04:59 sds
* Lots of changes this revision.
* Found I was having problems talking to multiple links on the same
* client, if I created a different client for each one. So introduced
* a few global variables to keep track of all the ip addresses of
* clients that the library is asked to create, and only creating new
* clients if the ip address is different. This puts a limit of how
* many unique ip addresses (clients) a single process can connect to.
* Set this value at 256 (should hopefully be enough!).
* Next I found that talking to different clients on different ip
* addresses didn't work. It turns out that create_link_1() creates
* a static structure. This this link is associated with a given
* client (and hence a given IP address), then the only way I could
* think of making things work was to add a call to an
* vxi11_open_link() function before each send command (no idea what
* this adds to overheads and it's very messy!) - at least I was
* able to get this to only happen when we are using more than one
* client/ip address.
* Also, while I was at it, I re-ordered the functions a little -
* starts with core user functions, extra user functions, then core
* library functions at the end. Added a few more comments. Tidied
* up. Left some debugging info in, but commented out.
*
* Revision 1.3 2006/06/26 12:40:56 sds
* Introduced a new CLINK structure, to reduce the number of arguments
* passed to functions. Wrote wrappers for open(), close(), send()
* and receieve() functions, then adjusted all the other functions built
* on those to make use of the CLINK structure.
*
* Revision 1.2 2006/06/26 10:29:48 sds
* Added GNU GPL and copyright notices.
*
*/
 
/* vxi11_user.cc
* Copyright (C) 2006 Steve D. Sharples
*
* User library for opening, closing, sending to and receiving from
* a device enabled with the VXI11 RPC ethernet protocol. Uses the files
* generated by rpcgen vxi11.x.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The author's email address is steve.sharples@nottingham.ac.uk
*/
 
#include "vxi11_user.h"
 
/*****************************************************************************
* GENERAL NOTES
*****************************************************************************
*
* There are four functions at the heart of this library:
*
* int vxi11_open_device(char *ip, CLIENT **client, VXI11_LINK **link)
* int vxi11_close_device(char *ip, CLIENT *client, VXI11_LINK *link)
* int vxi11_send(CLIENT *client, VXI11_LINK *link, char *cmd, unsigned long len)
* long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len, unsigned long timeout)
*
* Note that all 4 of these use separate client and link structures. All the
* other functions are built on these four core functions, and the first layer
* of abstraction is to combine the CLIENT and VXI11_LINK structures into a
* single entity, which I've called a CLINK. For the send and receive
* functions, this is just a simple wrapper. For the open and close functions
* it's a bit more complicated, because we somehow have to keep track of
* whether we've already opened a device with the same IP address before (in
* which case we need to recycle a previously created client), or whether
* we've still got any other links to a given IP address left when we are
* asked to close a clink (in which case we can sever the link, but have to
* keep the client open). This is so the person using this library from
* userland does not have to keep track of whether they are talking to a
* different physical instrument or not each time they establish a connection.
*
* So the base functions that the user will probably want to use are:
*
* int vxi11_open_device(char *ip, CLINK *clink)
* int vxi11_close_device(char *ip, CLINK *clink)
* int vxi11_send(CLINK *clink, char *cmd, unsigned long len)
* --- or --- (if sending just text)
* int vxi11_send(CLINK *clink, char *cmd)
* long vxi11_receive(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout)
*
* There are then useful (to me, anyway) more specific functions built on top
* of these:
*
* int vxi11_send_data_block(CLINK *clink, char *cmd, char *buffer, unsigned long len)
* long vxi11_receive_data_block(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout)
* long vxi11_send_and_receive(CLINK *clink, char *cmd, char *buf, unsigned long buf_len, unsigned long timeout)
* long vxi11_obtain_long_value(CLINK *clink, char *cmd, unsigned long timeout)
* double vxi11_obtain_double_value(CLINK *clink, char *cmd, unsigned long timeout)
*
* (then there are some shorthand wrappers for the above without specifying
* the timeout due to sheer laziness---explore yourself)
*/
 
 
/* Global variables. Keep track of multiple links per client. We need this
* because:
* - we'd like the library to be able to cope with multiple links to a given
* client AND multiple links to multiple clients
* - we'd like to just refer to a client/link ("clink") as a single
* entity from user land, we don't want to worry about different
* initialisation procedures, depending on whether it's an instrument
* with the same IP address or not
*/
char VXI11_IP_ADDRESS[VXI11_MAX_CLIENTS][20];
CLIENT *VXI11_CLIENT_ADDRESS[VXI11_MAX_CLIENTS];
int VXI11_DEVICE_NO = 0;
int VXI11_LINK_COUNT[VXI11_MAX_CLIENTS];
 
/*****************************************************************************
* KEY USER FUNCTIONS - USE THESE FROM YOUR PROGRAMS OR INSTRUMENT LIBRARIES *
*****************************************************************************/
 
/* OPEN FUNCTIONS *
* ============== */
 
/* Use this function from user land to open a device and create a link. Can be
* used multiple times for the same device (the library will keep track).*/
int vxi11_open_device(const char *ip, CLINK *clink, char *device) {
int ret;
int l;
int device_no=-1;
 
// printf("before doing anything, clink->link = %ld\n", clink->link);
/* Have a look to see if we've already initialised an instrument with
* this IP address */
for (l=0; l<VXI11_MAX_CLIENTS; l++){
if (strcmp(ip,VXI11_IP_ADDRESS[l]) == 0 ) {
device_no=l;
// printf("Open function, search, found ip address %s, device no %d\n",ip,device_no);
}
}
 
/* Couldn't find a match, must be a new IP address */
if (device_no < 0) {
/* Uh-oh, we're out of storage space. Increase the #define
* for VXI11_MAX_CLIENTS in vxi11_user.h */
if (VXI11_DEVICE_NO >= VXI11_MAX_CLIENTS) {
printf("Error: maximum of %d clients allowed\n",VXI11_MAX_CLIENTS);
ret = -VXI11_MAX_CLIENTS;
}
/* Create a new client, keep a note of where the client pointer
* is, for this IP address. Because it's a new client, this
* must be link number 1. Keep track of how many devices we've
* opened so we don't run out of storage space. */
else {
ret = vxi11_open_device(ip, &(clink->client), &(clink->link), device);
strncpy(VXI11_IP_ADDRESS[VXI11_DEVICE_NO],ip,20);
VXI11_CLIENT_ADDRESS[VXI11_DEVICE_NO] = clink->client;
VXI11_LINK_COUNT[VXI11_DEVICE_NO]=1;
// printf("Open function, could not find ip address %s.\n",ip);
// printf("So now, VXI11_IP_ADDRESS[%d]=%s,\n",VXI11_DEVICE_NO,VXI11_IP_ADDRESS[VXI11_DEVICE_NO]);
// printf("VXI11_CLIENT_ADDRESS[%d]=%ld,\n",VXI11_DEVICE_NO,VXI11_CLIENT_ADDRESS[VXI11_DEVICE_NO]);
// printf(" clink->client=%ld,\n",clink->client);
// printf("VXI11_LINK_COUNT[%d]=%d.\n",VXI11_DEVICE_NO,VXI11_LINK_COUNT[VXI11_DEVICE_NO]);
VXI11_DEVICE_NO++;
}
}
/* already got a client for this IP address */
else {
/* Copy the client pointer address. Just establish a new link
* (not a new client). Add one to the link count */
clink->client = VXI11_CLIENT_ADDRESS[device_no];
ret = vxi11_open_link(ip, &(clink->client), &(clink->link), device);
// printf("Found an ip address, copying client from VXI11_CLIENT_ADDRESS[%d]\n",device_no);
VXI11_LINK_COUNT[device_no]++;
// printf("Have just incremented VXI11_LINK_COUNT[%d], it's now %d\n",device_no,VXI11_LINK_COUNT[device_no]);
}
// printf("after creating link, clink->link = %ld\n", clink->link);
return ret;
}
 
/* This is a wrapper function, used for the situations where there is only one
* "device" per client. This is the case for most (if not all) VXI11
* instruments; however, it is _not_ the case for devices such as LAN to GPIB
* gateways. These are single clients that communicate to many instruments
* (devices). In order to differentiate between them, we need to pass a device
* name. This gets used in the vxi11_open_link() fn, as the link_parms.device
* value. */
int vxi11_open_device(const char *ip, CLINK *clink) {
char device[6];
strncpy(device,"inst0",6);
return vxi11_open_device(ip, clink, device);
}
 
 
 
/* CLOSE FUNCTION *
* ============== */
 
/* Use this function from user land to close a device and/or sever a link. Can
* be used multiple times for the same device (the library will keep track).*/
int vxi11_close_device(const char *ip, CLINK *clink) {
int l,ret;
int device_no = -1;
 
/* Which instrument are we referring to? */
for (l=0; l<VXI11_MAX_CLIENTS; l++){
if (strcmp(ip,VXI11_IP_ADDRESS[l]) == 0 ) {
device_no=l;
}
}
/* Something's up if we can't find the IP address! */
if (device_no == -1) {
printf("vxi11_close_device: error: I have no record of you ever opening device\n");
printf(" with IP address %s\n",ip);
ret = -4;
}
else { /* Found the IP, there's more than one link to that instrument,
* so keep track and just close the link */
if (VXI11_LINK_COUNT[device_no] > 1 ) {
ret = vxi11_close_link(ip,clink->client, clink->link);
VXI11_LINK_COUNT[device_no]--;
}
/* Found the IP, it's the last link, so close the device (link
* AND client) */
else {
ret = vxi11_close_device(ip, clink->client, clink->link);
}
}
return ret;
}
 
 
/* SEND FUNCTIONS *
* ============== */
 
/* A _lot_ of the time we are sending text strings, and can safely rely on
* strlen(cmd). */
int vxi11_send(CLINK *clink, const char *cmd) {
return vxi11_send(clink, cmd, strlen(cmd));
}
 
/* We still need the version of the function where the length is set explicitly
* though, for when we are sending fixed length data blocks. */
int vxi11_send(CLINK *clink, const char *cmd, unsigned long len) {
return vxi11_send(clink->client, clink->link, cmd, len);
}
 
 
/* RECEIVE FUNCTIONS *
* ================= */
 
/* Lazy wrapper for when I can't be bothered to specify a read timeout */
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len) {
return vxi11_receive(clink, buffer, len, VXI11_READ_TIMEOUT);
}
 
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout) {
return vxi11_receive(clink->client, clink->link, buffer, len, timeout);
}
 
 
 
/*****************************************************************************
* USEFUL ADDITIONAL HIGHER LEVER USER FUNCTIONS - USE THESE FROM YOUR *
* PROGRAMS OR INSTRUMENT LIBRARIES *
*****************************************************************************/
 
/* SEND FIXED LENGTH DATA BLOCK FUNCTION *
* ===================================== */
int vxi11_send_data_block(CLINK *clink, const char *cmd, char *buffer, unsigned long len) {
char *out_buffer;
int cmd_len=strlen(cmd);
int ret;
 
out_buffer=new char[cmd_len+10+len];
sprintf(out_buffer,"%s#8%08lu",cmd,len);
memcpy(out_buffer+cmd_len+10,buffer,(unsigned long) len);
ret = vxi11_send(clink, out_buffer, (unsigned long) (cmd_len+10+len));
delete[] out_buffer;
return ret;
}
 
/* RECEIVE FIXED LENGTH DATA BLOCK FUNCTION *
* ======================================== */
 
/* This function reads a response in the form of a definite-length block, such
* as when you ask for waveform data. The data is returned in the following
* format:
* #800001000<1000 bytes of data>
* ||\______/
* || |
* || \---- number of bytes of data
* |\--------- number of digits that follow (in this case 8, with leading 0's)
* \---------- always starts with #
*/
long vxi11_receive_data_block(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout) {
/* I'm not sure what the maximum length of this header is, I'll assume it's
* 11 (#9 + 9 digits) */
unsigned long necessary_buffer_size;
char *in_buffer;
int ret;
int ndigits;
unsigned long returned_bytes;
int l;
char scan_cmd[20];
necessary_buffer_size=len+12;
in_buffer=new char[necessary_buffer_size];
ret=vxi11_receive(clink, in_buffer, necessary_buffer_size, timeout);
if (ret < 0) return ret;
if (in_buffer[0] != '#') {
printf("vxi11_user: data block error: data block does not begin with '#'\n");
printf("First 20 characters received were: '");
for(l=0;l<20;l++) {
printf("%c",in_buffer[l]);
}
printf("'\n");
return -3;
}
 
/* first find out how many digits */
sscanf(in_buffer,"#%1d",&ndigits);
/* some instruments, if there is a problem acquiring the data, return only "#0" */
if (ndigits > 0) {
/* now that we know, we can convert the next <ndigits> bytes into an unsigned long */
sprintf(scan_cmd,"#%%1d%%%dlu",ndigits);
sscanf(in_buffer,scan_cmd,&ndigits,&returned_bytes);
memcpy(buffer, in_buffer+(ndigits+2), returned_bytes);
delete[] in_buffer;
return (long) returned_bytes;
}
else return 0;
}
 
 
/* SEND AND RECEIVE FUNCTION *
* ========================= */
 
/* This is mainly a useful function for the overloaded vxi11_obtain_value()
* fn's, but is also handy and useful for user and library use */
long vxi11_send_and_receive(CLINK *clink, const char *cmd, char *buf, unsigned long buf_len, unsigned long timeout) {
int ret;
long bytes_returned;
do {
ret = vxi11_send(clink, cmd);
if (ret != 0) {
if (ret != -VXI11_NULL_WRITE_RESP) {
printf("Error: vxi11_send_and_receive: could not send cmd.\n");
printf(" The function vxi11_send returned %d. ",ret);
return -1;
}
else printf("(Info: VXI11_NULL_WRITE_RESP in vxi11_send_and_receive, resending query)\n");
}
 
bytes_returned = vxi11_receive(clink, buf, buf_len, timeout);
if (bytes_returned <= 0) {
if (bytes_returned >-VXI11_NULL_READ_RESP) {
printf("Error: vxi11_send_and_receive: problem reading reply.\n");
printf(" The function vxi11_receive returned %ld. ",bytes_returned);
return -2;
}
else printf("(Info: VXI11_NULL_READ_RESP in vxi11_send_and_receive, resending query)\n");
}
} while (bytes_returned == -VXI11_NULL_READ_RESP || ret == -VXI11_NULL_WRITE_RESP);
return 0;
}
 
 
/* FUNCTIONS TO RETURN A LONG INTEGER VALUE SENT AS RESPONSE TO A QUERY *
* ==================================================================== */
long vxi11_obtain_long_value(CLINK *clink, const char *cmd, unsigned long timeout) {
char buf[50]; /* 50=arbitrary length... more than enough for one number in ascii */
memset(buf, 0, 50);
if (vxi11_send_and_receive(clink, cmd, buf, 50, timeout) != 0) {
printf("Returning 0\n");
return 0;
}
return strtol(buf, (char **)NULL, 10);
}
 
/* Lazy wrapper function with default read timeout */
long vxi11_obtain_long_value(CLINK *clink, const char *cmd) {
return vxi11_obtain_long_value(clink, cmd, VXI11_READ_TIMEOUT);
}
 
 
/* FUNCTIONS TO RETURN A DOUBLE FLOAT VALUE SENT AS RESPONSE TO A QUERY *
* ==================================================================== */
double vxi11_obtain_double_value(CLINK *clink, const char *cmd, unsigned long timeout) {
char buf[50]; /* 50=arbitrary length... more than enough for one number in ascii */
double val;
memset(buf, 0, 50);
if (vxi11_send_and_receive(clink, cmd, buf, 50, timeout) != 0) {
printf("Returning 0.0\n");
return 0.0;
}
val = strtod(buf, (char **)NULL);
return val;
}
 
/* Lazy wrapper function with default read timeout */
double vxi11_obtain_double_value(CLINK *clink, const char *cmd) {
return vxi11_obtain_double_value(clink, cmd, VXI11_READ_TIMEOUT);
}
 
 
/*****************************************************************************
* CORE FUNCTIONS - YOU SHOULDN'T NEED TO USE THESE FROM YOUR PROGRAMS OR *
* INSTRUMENT LIBRARIES *
*****************************************************************************/
 
/* OPEN FUNCTIONS *
* ============== */
int vxi11_open_device(const char *ip, CLIENT **client, VXI11_LINK **link, char *device) {
 
*client = clnt_create(ip, DEVICE_CORE, DEVICE_CORE_VERSION, "tcp");
 
if (*client == NULL) {
clnt_pcreateerror(ip);
return -1;
}
 
return vxi11_open_link(ip, client, link, device);
}
 
int vxi11_open_link(const char *ip, CLIENT **client, VXI11_LINK **link, char *device) {
 
Create_LinkParms link_parms;
 
/* Set link parameters */
link_parms.clientId = (long) *client;
link_parms.lockDevice = 0;
link_parms.lock_timeout = VXI11_DEFAULT_TIMEOUT;
link_parms.device = device;
 
*link = (Create_LinkResp *) calloc(1, sizeof(Create_LinkResp));
 
if (create_link_1(&link_parms, *link, *client) != RPC_SUCCESS) {
clnt_perror(*client, ip);
return -2;
}
return 0;
}
 
 
/* CLOSE FUNCTIONS *
* =============== */
int vxi11_close_device(const char *ip, CLIENT *client, VXI11_LINK *link) {
int ret;
 
ret = vxi11_close_link(ip, client, link);
 
clnt_destroy(client);
 
return ret;
}
 
int vxi11_close_link(const char *ip, CLIENT *client, VXI11_LINK *link) {
Device_Error dev_error;
memset(&dev_error, 0, sizeof(dev_error));
 
if (destroy_link_1(&link->lid, &dev_error, client) != RPC_SUCCESS) {
clnt_perror(client,ip);
return -1;
}
 
return 0;
}
 
 
/* SEND FUNCTIONS *
* ============== */
 
/* A _lot_ of the time we are sending text strings, and can safely rely on
* strlen(cmd). */
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd) {
return vxi11_send(client, link, cmd, strlen(cmd));
}
 
/* We still need the version of the function where the length is set explicitly
* though, for when we are sending fixed length data blocks. */
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd, unsigned long len) {
Device_WriteParms write_parms;
int bytes_left = (int)len;
char *send_cmd;
 
send_cmd = new char[len];
memcpy(send_cmd, cmd, len);
 
write_parms.lid = link->lid;
write_parms.io_timeout = VXI11_DEFAULT_TIMEOUT;
write_parms.lock_timeout = VXI11_DEFAULT_TIMEOUT;
 
/* We can only write (link->maxRecvSize) bytes at a time, so we sit in a loop,
* writing a chunk at a time, until we're done. */
 
do {
Device_WriteResp write_resp;
memset(&write_resp, 0, sizeof(write_resp));
 
if (bytes_left <= link->maxRecvSize) {
write_parms.flags = 8;
write_parms.data.data_len = bytes_left;
}
else {
write_parms.flags = 0;
/* We need to check that maxRecvSize is a sane value (ie >0). Believe it
* or not, on some versions of Agilent Infiniium scope firmware the scope
* returned "0", which breaks Rule B.6.3 of the VXI-11 protocol. Nevertheless
* we need to catch this, otherwise the program just hangs. */
if (link->maxRecvSize > 0) {
write_parms.data.data_len = link->maxRecvSize;
}
else {
write_parms.data.data_len = 4096; /* pretty much anything should be able to cope with 4kB */
}
}
write_parms.data.data_val = send_cmd + (len - bytes_left);
if(device_write_1(&write_parms, &write_resp, client) != RPC_SUCCESS) {
delete[] send_cmd;
return -VXI11_NULL_WRITE_RESP; /* The instrument did not acknowledge the write, just completely
dropped it. There was no vxi11 comms error as such, the
instrument is just being rude. Usually occurs when the instrument
is busy. If we don't check this first, then the following
line causes a seg fault */
}
if (write_resp . error != 0) {
printf("vxi11_user: write error: %d\n",write_resp . error);
delete[] send_cmd;
return -(write_resp . error);
}
bytes_left -= write_resp . size;
} while (bytes_left > 0);
 
delete[] send_cmd;
return 0;
}
 
 
/* RECEIVE FUNCTIONS *
* ================= */
 
// It appeared that this function wasn't correctly dealing with more data available than specified in len.
// This patch attempts to fix this issue. RDP 2007/8/13
 
/* wrapper, for default timeout */ long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len) { return vxi11_receive(client, link, buffer, len, VXI11_READ_TIMEOUT);
}
 
#define RCV_END_BIT 0x04 // An end indicator has been read
#define RCV_CHR_BIT 0x02 // A termchr is set in flags and a character which matches termChar is transferred
#define RCV_REQCNT_BIT 0x01 // requestSize bytes have been transferred. This includes a request size of zero.
 
long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len, unsigned long timeout) {
Device_ReadParms read_parms;
Device_ReadResp read_resp;
long curr_pos = 0;
 
read_parms.lid = link->lid;
read_parms.requestSize = len;
read_parms.io_timeout = timeout; /* in ms */
read_parms.lock_timeout = timeout; /* in ms */
read_parms.flags = 0;
read_parms.termChar = 0;
 
do {
memset(&read_resp, 0, sizeof(read_resp));
 
read_resp.data.data_val = buffer + curr_pos;
read_parms.requestSize = len - curr_pos; // Never request more total data than originally specified in len
 
if(device_read_1(&read_parms, &read_resp, client) != RPC_SUCCESS) {
return -VXI11_NULL_READ_RESP; /* there is nothing to read. Usually occurs after sending a query
which times out on the instrument. If we don't check this first,
then the following line causes a seg fault */
}
if (read_resp . error != 0) {
/* Read failed for reason specified in error code.
* 0 no error
* 4 invalid link identifier
* 11 device locked by another link
* 15 I/O timeout
* 17 I/O error
* 23 abort
*/
 
printf("vxi11_user: read error: %d\n",read_resp . error);
return -(read_resp . error);
}
 
if((curr_pos + read_resp . data.data_len) <= len) {
curr_pos += read_resp . data.data_len;
}
if( (read_resp.reason & RCV_END_BIT) || (read_resp.reason & RCV_CHR_BIT) ) {
break;
}
else if( curr_pos == len ) {
printf("xvi11_user: read error: buffer too small. Read %d bytes without hitting terminator.\n", curr_pos );
return -100;
}
} while(1);
return (curr_pos); /*actual number of bytes received*/
 
}
 
/lab/sipmscan/trunk/include/vxi11_i686/vxi11_user.h
0,0 → 1,136
/* Revision history: */
/* $Id: vxi11_user.h,v 1.10 2007/10/30 12:47:33 sds Exp $ */
/*
* $Log: vxi11_user.h,v $
* Revision 1.10 2007/10/30 12:47:33 sds
* changed a lot of char *'s to const char *'s in an attempt to get
* rid of pedantic gcc compiler warnings.
*
* Revision 1.9 2007/07/11 14:20:56 sds
* removed #include <iostream> as not needed
* removed using namespace std
*
* Revision 1.8 2007/07/10 13:54:11 sds
* Added extra function:
* int vxi11_open_device(char *ip, CLINK *clink, char *device);
* This replaces the original vxi11_open_device fn, which did not pass
* a char *device. Wrapper fn used for backwards compatibility.
*
* Revision 1.7 2007/07/10 11:20:43 sds
* removed the following function:
* int vxi11_open_link(CLIENT **client, VXI11_LINK **link);
* ...since it was no longer needed, following the patch by
* Robert Larice.
*
* Revision 1.6 2006/12/08 11:47:14 ijc
* error on last ci, sorted.
*
* Revision 1.5 2006/12/08 11:45:29 ijc
* added #define VXI11_NULL_READ_RESP
*
* Revision 1.4 2006/12/07 12:26:17 sds
* added VXI11_NULL_READ_RESP #define
*
* Revision 1.3 2006/07/06 13:03:28 sds
* Surrounded the whole header with #ifndef __VXI11_USER__.
* Added a couple of vxi11_open_link() fns and a vxi11_close_link() fn, to
* separate the link stuff from the client stuff.
*
* Revision 1.2 2006/06/26 12:42:54 sds
* Introduced a new CLINK structure, to reduce the number of arguments
* passed to functions. Wrote wrappers for open(), close(), send()
* and receieve() functions, then adjusted all the other functions built
* on those to make use of the CLINK structure.
*
* Revision 1.1 2006/06/26 10:36:02 sds
* Initial revision
*
*/
 
/* vxi11_user.h
* Copyright (C) 2006 Steve D. Sharples
*
* User library for opening, closing, sending to and receiving from
* a device enabled with the VXI11 RPC ethernet protocol. Uses the files
* generated by rpcgen vxi11.x.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The author's email address is steve.sharples@nottingham.ac.uk
*/
 
#ifndef __VXI11_USER__
#define __VXI11_USER__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include <rpc/rpc.h>
#include "vxi11.h"
 
#define VXI11_DEFAULT_TIMEOUT 10000 /* in ms */
#define VXI11_READ_TIMEOUT 2000 /* in ms */
#define VXI11_CLIENT CLIENT
#define VXI11_LINK Create_LinkResp
#define VXI11_MAX_CLIENTS 256 /* maximum no of unique IP addresses/clients */
#define VXI11_NULL_READ_RESP 50 /* vxi11_receive() return value if a query
* times out ON THE INSTRUMENT (and so we have
* to resend the query again) */
#define VXI11_NULL_WRITE_RESP 51 /* vxi11_send() return value if a sent command
* times out ON THE INSTURMENT. */
 
struct CLINK {
VXI11_CLIENT *client;
VXI11_LINK *link;
} ;
typedef struct CLINK CLINK;
 
/* The four main functions: open, close, send, receieve (plus a couple of wrappers) */
/* In fact all 6 of these are wrappers to the original functions listed at the
* bottom, that use separate CLIENT and VXI11_LINK structures. It was easier to
* write wrappers for these functions than to re-write the original functions
* themselves. These are the 4 (or 6 if you like) key user functions that you
* should probably be using. They all use the CLINK structure. */
int vxi11_open_device(const char *ip, CLINK *clink);
int vxi11_open_device(const char *ip, CLINK *clink, char *device);
int vxi11_close_device(const char *ip, CLINK *clink);
int vxi11_send(CLINK *clink, const char *cmd);
int vxi11_send(CLINK *clink, const char *cmd, unsigned long len);
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len);
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout);
int vxi11_queryxx(CLINK *clink, char *mycmd);
/* Utility functions, that use send() and receive(). Use these too. */
int vxi11_send_data_block(CLINK *clink, const char *cmd, char *buffer, unsigned long len);
long vxi11_receive_data_block(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout);
long vxi11_send_and_receive(CLINK *clink, const char *cmd, char *buf, unsigned long buf_len, unsigned long timeout);
long vxi11_obtain_long_value(CLINK *clink, const char *cmd, unsigned long timeout);
double vxi11_obtain_double_value(CLINK *clink, const char *cmd, unsigned long timeout);
long vxi11_obtain_long_value(CLINK *clink, const char *cmd);
double vxi11_obtain_double_value(CLINK *link, const char *cmd);
 
/* When I first wrote this library I used separate client and links. I've
* retained the original functions and just written clink wrappers for them
* (see above) as it's perhaps a little clearer this way. Probably not worth
* delving this deep in use, but it's where the real nitty gritty is. */
int vxi11_open_device(const char *ip, CLIENT **client, VXI11_LINK **link, char *device);
int vxi11_open_link(const char *ip, CLIENT **client, VXI11_LINK **link, char *device);
int vxi11_close_device(const char *ip, CLIENT *client, VXI11_LINK *link);
int vxi11_close_link(const char *ip, CLIENT *client, VXI11_LINK *link);
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd);
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd, unsigned long len);
long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len);
long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len, unsigned long timeout);
 
#endif
/lab/sipmscan/trunk/include/vxi11_x86_64/CHANGELOG.txt
0,0 → 1,218
------------------------------------------------------------------------------
vxi11_1.10 - 9/09/2010
 
Bug fix (thanks to Stephan Mahr): in vxi11_close(), remove the IP address
from the global array that keeps track of them so that if the same device
is opened again, then a new client is created, rather than it attempting
to use the old one (which was destroyed on the previous close).
 
------------------------------------------------------------------------------
vxi11_1.09 - 7/06/2010
 
Moved over to bazaar VCS (from RCS).
 
Makefile cleanups. Fixed signed/unsigned comparisons. Use consistent (and
sane) struct separator spacing in code.
 
Fix int casting on printf statements to fix new compiler warnings/errors
(thanks to Shouri Chatterjee for pointing this out).
 
------------------------------------------------------------------------------
vxi11_1.08 - 3/09/2009
 
Added a sanity check for link->maxRecvSize to make sure it's >0. This gets
around a bug in some versions of the Agilent Infiniium scope software.
 
Changed the erroneous strncpy() to memcpy() in vxi11_send, as we could be
sending binary data (not just strings).
 
Changed a lot of char *'s to const char *'s in an attempt to get rid of
pedantic gcc compiler warnings.
 
------------------------------------------------------------------------------
vxi11_1.07 - 9/10/2007
 
Minor change to vxi11_receive_data_block(), this fn now copes with instruments
that return just "#0" (for whatever reason). Suggestion by Jarek Sadowski,
gratefully received.
 
------------------------------------------------------------------------------
vxi11_1.06 - 31/08/2007
 
Bug fix in vxi11_receive(), to ensure that no more than "len" bytes are ever
received (and so avoiding a segmentation fault). This was a bug introduced in
release 1.04 whilst making some other changes to the vxi11_receive() fn.
 
Many thanks to Rob Penny for spotting the bug and providing a patch.
 
------------------------------------------------------------------------------
vxi11_1.05 - 11/07/2007
 
Added the ability to specify a "device name" when calling vxi11_open_device().
For regular VXI11-based instruments, such as scopes and AFGs, the device name
is usually "hard wired" to be "inst0", and up to now this has been hard wired
into the vxi11_user code. However, devices such as LAN to GPIB gateways need
some way of distinguishing between different devices... they are a single
client (one IP address), with multiple devices.
 
The vxi11_user fn, vxi11_open_device(), now takes a third argument
(char *device).
This gets passed to the core vxi11_open_device() fn (the one that deals with
separate clients and links), and the core vxi11_open_link() fn; these two
core functions have also had an extra parameter added accordingly. In order
to not break the API, a wrapper function is provided in the form of the
original vxi11_open_device() fn, that just takes 2 arguments
(char *ip, CLINK *clink), this then passes "inst0" as the device argument.
Backwards-compatible wrappers for the core functions have NOT been provided.
These are generally not used from userland anyway. Hopefully this won't
upset anyone!
 
vxi11_cmd, the simple test utility, has also been updated. You can now,
optionally, pass the device_name as a second argument (after the ip
address). The source has been renamed to vxi11_cmd.cc (from vxi11_cmd.c), as
it is C++ code not C.
 
Some minor tidying up in vxi11_user.h
 
With thanks to Oliver Schulz for bringing LAN to GPIB gateways to my
attention, for suggesting changes to the vxi11_user library to allow them to
be accommodated, and for tidying some things up.
 
------------------------------------------------------------------------------
vxi11_1.04 - 10/07/2007
 
Patch applied, which was kindly provided by Robert Larice. This sorts out
the confusion (on my part) about the structures returned by the rpcgen
generated *_1() functions... these are statically allocated temporary structs,
apparently. In the words of Robert Larice:
 
******
Hello Dr. Sharples,
 
I'm sending some patches for your nice gem "vxi11_1.03"
 
In the source code there were some strange comments, concerning
a commented free() around ... Manfred S. ...
and some notes, suggesting you had trouble to get more than one link
working.
 
I think thats caused by some misuse of the rpcgen generated subroutines.
1) those rpcgen generated *_1 functions returned pointers to
statically allocated temporary structs.
those where meant to be instantly copied to the user's space,
which wasn't done
thus instead of
Device_ReadResp *read_resp;
read_resp = device_read_1(...)
one should have written someting like:
Device_ReadResp *read_resp;
read_resp = malloc(...)
memcpy(read_resp, device_read_1(...), ...)
2) but a better fix is to use the rpcgen -M Flag
which allows to pass the memory space as a third argument
so one can write
Device_ReadResp *read_resp;
read_resp = malloc(...)
device_read_1(..., read_resp, ...)
furthermore this is now automatically thread save
3) the rpcgen function device_read_1
expects a target buffer to be passed via read_resp
which was not done.
4) the return value of vxi11_receive() was computed incorrectly
5) minor, Makefile typo's
CFLAGS versus
CLFAGS
 
******
 
Robert didn't have more than one device to try the patch with, but I've just
tried it and everything seems fine. So I've removed all references to the
VXI11_ENABLE_MULTIPLE_CLIENTS global variable, and removed the call to
vxi11_open_link() from the vxi11_send() fn. There has been an associated
tidying of functions, and removal of some comments.
 
Thanks once again to Robert Larice for the patch and the explanation!
 
------------------------------------------------------------------------------
vxi11_1.03 - 29/01/2007
 
Some bug-fixes (thanks to Manfred S.), and extra awareness of the
possibility that instruments could time out after receiving a query WITHOUT
causing an error condition. In some cases (prior to these changes) this
could have resulted in a segmentation fault.
 
Specifically:
 
(1) removed call to ANSI free() fn in vxi11_receive, which according to
Manfred S. "is not necessary and wrong (crashes)".
 
(2) added extra check in vxi11_receive() to see if read_resp==NULL.
read_resp can apparently be NULL if (eg) you send an instrument a
query, but the instrument is so busy with something else for so long
that it forgets the original query. So this extra check is for that
situation, and vxi11_receive returns -VXI11_NULL_READ_RESP to the
calling function.
 
(3) vxi11_send_and_receive() is now aware of the possibility of being
returned -VXI11_NULL_READ_RESP. If so, it re-sends the query, until
either getting a "regular" read error (read_resp->error!=0) or a
successful read.
 
(4) Similar to (2)... added extra check in vxi11_send() to see if
write_resp==NULL. If so, return -VXI11_NULL_WRITE_RESP. As with (3),
send_and_receive() is now aware of this possibility.
 
------------------------------------------------------------------------------
vxi11_1.02 - 25/08/2006
 
Important changes to the core vxi11_send() function, which should be
invisible to the user.
 
For those interested, the function now takes note of the value of
link->maxRecvSize, which is the maximum number of bytes that the vxi11
intrument you're talking to can receive in one go. For many instruments
this may be a few kB, which isn't a problem for sending short commands;
however, sending large chunks of data (for example sending waveforms
to instruments) may exceed this maxRecvSize. The core vxi11_send() function
has been re-written to ensure that only a maximum of [maxRecvSize] bytes are
written in one go... the function sits in a loop until all the message/
data is written.
 
Also tidied up some of the return values (specifically with regard to
vxi11_send() and vxi11_send_data_block() ).
 
------------------------------------------------------------------------------
vxi11_1.01 - 06/07/2006
 
Fair few changes since v1.00, all in vxi11_user.c and vxi11_user.h
 
Found I was having problems talking to multiple links on the same
client, if I created a different client for each one. So introduced
a few global variables to keep track of all the ip addresses of
clients that the library is asked to create, and only creating new
clients if the ip address is different. This puts a limit of how
many unique ip addresses (clients) a single process can connect to.
Set this value at 256 (should hopefully be enough!).
 
Next I found that talking to different clients on different ip
addresses didn't work. It turns out that create_link_1() creates
a static structure. This this link is associated with a given
client (and hence a given IP address), then the only way I could
think of making things work was to add a call to an
vxi11_open_link() function before each send command (no idea what
this adds to overheads and it's very messy!) - at least I was
able to get this to only happen when we are using more than one
client/ip address.
 
Also, while I was at it, I re-ordered the functions a little -
starts with core user functions, extra user functions, then core
library functions at the end. Added a few more comments. Tidied
up. Left some debugging info in, but commented out.
 
------------------------------------------------------------------------------
vxi11_1.00 - 23/06/2006
 
Initial release.
 
------------------------------------------------------------------------------
 
/lab/sipmscan/trunk/include/vxi11_x86_64/GNU_General_Public_License.txt
0,0 → 1,340
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
 
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
 
Preamble
 
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
 
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
 
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
 
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
 
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
 
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
 
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
 
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
 
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
 
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
 
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
 
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
 
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
 
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
 
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
 
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
 
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
 
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
 
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
 
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
 
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
 
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
 
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
 
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
 
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
 
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
 
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
 
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
 
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
 
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
 
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
 
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
 
NO WARRANTY
 
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
 
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
 
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
 
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
 
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
 
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 
Also add information on how to contact you by electronic and paper mail.
 
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
 
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
 
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
 
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
 
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
 
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
 
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
/lab/sipmscan/trunk/include/vxi11_x86_64/Makefile
0,0 → 1,18
VERSION=1.08
 
#CFLAGS = -Wall -g
CFLAGS = -g
CXX = g++
 
.PHONY: clean objs
 
objs: vxi11.h
$(CXX) -c -fPIC $(CFLAGS) vxi11_user.cc
$(CXX) -c -fPIC $(CFLAGS) vxi11_clnt.c
$(CXX) -c -fPIC $(CFLAGS) vxi11_xdr.c
 
vxi11.h: vxi11.x
rpcgen -M vxi11.x
 
clean:
rm -f *.o vxi11_cmd vxi11.h vxi11_svc.c vxi11_xdr.c vxi11_clnt.c #TAGS
/lab/sipmscan/trunk/include/vxi11_x86_64/README.txt
0,0 → 1,98
RPC PROTOCOL FOR COMMUNICATING WITH VXI11-ENABLED DEVICES OVER ETHERNET FROM LINUX
==================================================================================
(including instruments such as oscilloscopes, by manufacturers such as
Agilent and Tektronix, amongst others).
 
By Steve D. Sharples, June 2006.
 
This is a collection of source code that will allow you to talk to ethernet-
enabled instruments that use the VXI11 protocol, from Linux. This includes
a wide range of instruments (including oscilloscopes, logic analysers,
function generators etc) by a wide range of manufacturers (including
Tektronix and Agilent to name just a couple). An interactive "send and
receive" utility is included as an example.
 
You may want to build on to this libraries for your specific instruments -
I'm currently working on libraries for talking to Agilent Infiniium scopes,
and will probably do the same for Tektronix scopes too. Basically if you've
got a Programmer's Reference for your instrument, and this code, you should
be able to cobble something together.
 
This collection of code has been produced because I grew frustrated at how
difficult it seemed to be to do a relatively simple task. None of the
major manufacturers had any "out of the box" Linux solutions to talking to
their instruments (although often I would talk to technical folks who would
try their best to help). One of the solutions offered was to use something
called NI VISA; parts of this are closed source, it was enormous, and I had
worries about legacy issues with changing PC hardware.
 
Via Guy McBride at Agilent, I obtained a copy of a vxi11.x RPC file similar
to the one included here (although no-one at Agilent seemed to know or care
where it came from). After lots of searching on the information superhighway
I located what I believe is the original source (or something like it); see
the section on vxi11.x below. This source seems to have literally been written
from the published VXI11 protocol. I also received from Agilent a simple
example program that showed you how to use the protocol; working from this
and the (open) source that uses the vxi11.x that is included here, I wrote
vxi11_cmd and the user libraries.
 
This collection of source code consists of:
 
(1) vxi11.x
This file, vxi11.x, is the amalgamation of vxi11core.rpcl and vxi11intr.rpcl
which are part of the asynDriver (R4-5) EPICS module, which, at time of
writing, is available from:
http://www.aps.anl.gov/epics/modules/soft/asyn/index.html
More general information about EPICS is available from:
http://www.aps.anl.gov/epics/
This code is open source, and is covered under the copyright notice and
software license agreement shown below, and also at:
http://www.aps.anl.gov/epics/license/open.php
 
It is intended as a lightweight base for the vxi11 rpc protocol. If you
run rpcgen on this file, it will generate C files and headers, from which
it is relatively simple to write C programs to communicate with a range
of ethernet-enabled instruments, such as oscilloscopes and function
generators by manufacturers such as Agilent and Tektronix (amongst many
others).
 
(2) vxi11_user.cc (and vxi11_user.h)
These are (fairly) friendly user libraries. At the core are 4 key functions:
vxi11_open(), vxi11_close(), vxi11_send() and vxi11_receive(). These allow
you to talk to your device. There are also some other functions that I
considered to be generally useful (send_and_receive, functions for sending
and receiving fixed length data blocks etc) that are all non-instrument-
specific.
 
(3) vxi11_cmd.c
This is a fairly simple interactive utility that allows you to send
commands and queries to your vxi11-enabled instrument, which you
locate by way of IP address. I recommend you start with *IDN? It shows you
how the vxi11_user library works
 
(4) Makefile
Type "make" to compile the source above. Type "make clean" to remove
old object files and ./vxi11_cmd. Type "make install" to copy
./vxi11_cmd to /usr/local/bin/
 
(5) GNU_General_Public_License.txt
Fairly obvious. All programs, source, readme files etc NOT covered by any
other license (e.g. vxi11.x, which is covered by its own open source
license) are covered by this license.
 
These programs are free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
 
These programs are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
The author's email address is steve.no.spam.sharples@nottingham.ac.uk
(you can work it out!)
/lab/sipmscan/trunk/include/vxi11_x86_64/vxi11.x
0,0 → 1,317
/* This file, vxi11.x, is the amalgamation of vxi11core.rpcl and vxi11intr.rpcl
* which are part of the asynDriver (R4-5) EPICS module, which, at time of
* writing, is available from:
* http://www.aps.anl.gov/epics/modules/soft/asyn/index.html
* More general information about EPICS is available from:
* http://www.aps.anl.gov/epics/
* This code is open source, and is covered under the copyright notice and
* software license agreement shown below, and also at:
* http://www.aps.anl.gov/epics/license/open.php
*
* In order to comply with section 4.3 of the software license agreement, here
* is a PROMINENT NOTICE OF CHNAGES TO THE SOFTWARE
* ===========================================
* (1) This file, vxi11.x, is the concatenation of the files vxi11core.rpcl and
* vxi11intr.rpcl
* (2) Tab spacing has been tidied up
*
* It is intended as a lightweight base for the vxi11 rpc protocol. If you
* run rpcgen on this file, it will generate C files and headers, from which
* it is relatively simple to write C programs to communicate with a range
* of ethernet-enabled instruments, such as oscilloscopes and function
* generated by manufacturers such as Agilent and Tektronix (amongst many
* others).
*
* For what it's worth, this concatenation was done by Steve Sharples at
* the University of Nottingham, UK, on 1 June 2006.
*
* Copyright notice and software license agreement follow, then the
* original comments from vxi11core.rpcl etc.
*
******************************************************************************
* Copyright © 2006 <University of Chicago and other copyright holders>. All
* rights reserved.
******************************************************************************
*
******************************************************************************
* vxi11.x is distributed subject to the following license conditions:
* SOFTWARE LICENSE AGREEMENT
* Software: vxi11.x
*
* 1. The "Software", below, refers to vxi11.x (in either source code, or
* binary form and accompanying documentation). Each licensee is addressed
* as "you" or "Licensee."
*
* 2. The copyright holders shown above and their third-party licensors hereby
* grant Licensee a royalty-free nonexclusive license, subject to the
* limitations stated herein and U.S. Government license rights.
*
* 3. You may modify and make a copy or copies of the Software for use within
* your organization, if you meet the following conditions:
* 1. Copies in source code must include the copyright notice and this
* Software License Agreement.
* 2. Copies in binary form must include the copyright notice and this
* Software License Agreement in the documentation and/or other
* materials provided with the copy.
*
* 4. You may modify a copy or copies of the Software or any portion of it,
* thus forming a work based on the Software, and distribute copies of such
* work outside your organization, if you meet all of the following
* conditions:
* 1. Copies in source code must include the copyright notice and this
* Software License Agreement;
* 2. Copies in binary form must include the copyright notice and this
* Software License Agreement in the documentation and/or other
* materials provided with the copy;
* 3. Modified copies and works based on the Software must carry
* prominent notices stating that you changed specified portions of
* the Software.
*
* 5. Portions of the Software resulted from work developed under a U.S.
* Government contract and are subject to the following license: the
* Government is granted for itself and others acting on its behalf a
* paid-up, nonexclusive, irrevocable worldwide license in this computer
* software to reproduce, prepare derivative works, and perform publicly
* and display publicly.
*
* 6. WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF
* ANY KIND. THE COPYRIGHT HOLDERS, THEIR THIRD PARTY LICENSORS, THE UNITED
* STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND THEIR EMPLOYEES: (1)
* DISCLAIM ANY WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, TITLE OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY
* OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR USEFULNESS OF THE
* SOFTWARE, (3) DO NOT REPRESENT THAT USE OF THE SOFTWARE WOULD NOT INFRINGE
* PRIVATELY OWNED RIGHTS, (4) DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION
* UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL BE CORRECTED.
*
* 7. LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT HOLDERS, THEIR
* THIRD PARTY LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF
* ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
* CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF ANY KIND OR NATURE,
* INCLUDING BUT NOT LIMITED TO LOSS OF PROFITS OR LOSS OF DATA, FOR ANY
* REASON WHATSOEVER, WHETHER SUCH LIABILITY IS ASSERTED ON THE BASIS OF
* CONTRACT, TORT (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE,
* EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE POSSIBILITY OF SUCH
* LOSS OR DAMAGES.
******************************************************************************
*/
 
/******************************************************************************
*
* vxi11core.rpcl
*
* This file is best viewed with a tabwidth of 4
*
******************************************************************************
*
* TODO:
*
******************************************************************************
*
* Original Author: someone from VXIbus Consortium
* Current Author: Benjamin Franksen
* Date: 03-06-97
*
* RPCL description of the core- and abort-channel of the TCP/IP Instrument
* Protocol Specification.
*
*
* Modification Log:
* -----------------
* .00 03-06-97 bfr created this file
*
******************************************************************************
*
* Notes:
*
* This stuff is literally from
*
* VXI-11, Ref 1.0 : TCP/IP Instrument Protocol Specification
*
*/
 
typedef long Device_Link;
 
enum Device_AddrFamily
{
DEVICE_TCP,
DEVICE_UDP
};
 
typedef long Device_Flags;
 
typedef long Device_ErrorCode;
 
struct Device_Error
{
Device_ErrorCode error;
};
 
struct Create_LinkParms
{
long clientId; /* implementation specific value */
bool lockDevice; /* attempt to lock the device */
unsigned long lock_timeout; /* time to wait for lock */
string device<>; /* name of device */
};
struct Create_LinkResp
{
Device_ErrorCode error;
Device_Link lid;
unsigned short abortPort; /* for the abort RPC */
unsigned long maxRecvSize; /* max # of bytes accepted on write */
};
struct Device_WriteParms
{
Device_Link lid; /* link id from create_link */
unsigned long io_timeout; /* time to wait for I/O */
unsigned long lock_timeout; /* time to wait for lock */
Device_Flags flags; /* flags with options */
opaque data<>; /* the data length and the data itself */
};
struct Device_WriteResp
{
Device_ErrorCode error;
unsigned long size; /* # of bytes written */
};
struct Device_ReadParms
{
Device_Link lid; /* link id from create_link */
unsigned long requestSize; /* # of bytes requested */
unsigned long io_timeout; /* time to wait for I/O */
unsigned long lock_timeout; /* time to wait for lock */
Device_Flags flags; /* flags with options */
char termChar; /* valid if flags & termchrset */
};
struct Device_ReadResp
{
Device_ErrorCode error;
long reason; /* why read completed */
opaque data<>; /* the data length and the data itself */
};
struct Device_ReadStbResp
{
Device_ErrorCode error;
unsigned char stb; /* the returned status byte */
};
struct Device_GenericParms
{
Device_Link lid; /* link id from create_link */
Device_Flags flags; /* flags with options */
unsigned long lock_timeout; /* time to wait for lock */
unsigned long io_timeout; /* time to wait for I/O */
};
struct Device_RemoteFunc
{
unsigned long hostAddr; /* host servicing interrupt */
unsigned long hostPort; /* valid port # on client */
unsigned long progNum; /* DEVICE_INTR */
unsigned long progVers; /* DEVICE_INTR_VERSION */
Device_AddrFamily progFamily; /* DEVICE_UDP | DEVICE_TCP */
};
struct Device_EnableSrqParms
{
Device_Link lid; /* link id from create_link */
bool enable; /* enable or disable intr's */
opaque handle<40>; /* host specific data */
};
struct Device_LockParms
{
Device_Link lid; /* link id from create_link */
Device_Flags flags; /* contains the waitlock flag */
unsigned long lock_timeout; /* time to wait for lock */
};
struct Device_DocmdParms
{
Device_Link lid; /* link id from create_link */
Device_Flags flags; /* flags with options */
unsigned long io_timeout; /* time to wait for I/O */
unsigned long lock_timeout; /* time to wait for lock */
long cmd; /* which command to execute */
bool network_order; /* client's byte order */
long datasize; /* size of individual data elements */
opaque data_in<>; /* docmd data parameters */
};
struct Device_DocmdResp
{
Device_ErrorCode error;
opaque data_out<>; /* returned data parameters */
};
 
program DEVICE_ASYNC
{
version DEVICE_ASYNC_VERSION
{
Device_Error device_abort (Device_Link) = 1;
} = 1;
} = 0x0607B0;
 
program DEVICE_CORE
{
version DEVICE_CORE_VERSION
{
Create_LinkResp create_link (Create_LinkParms) = 10;
Device_WriteResp device_write (Device_WriteParms) = 11;
Device_ReadResp device_read (Device_ReadParms) = 12;
Device_ReadStbResp device_readstb (Device_GenericParms) = 13;
Device_Error device_trigger (Device_GenericParms) = 14;
Device_Error device_clear (Device_GenericParms) = 15;
Device_Error device_remote (Device_GenericParms) = 16;
Device_Error device_local (Device_GenericParms) = 17;
Device_Error device_lock (Device_LockParms) = 18;
Device_Error device_unlock (Device_Link) = 19;
Device_Error device_enable_srq (Device_EnableSrqParms) = 20;
Device_DocmdResp device_docmd (Device_DocmdParms) = 22;
Device_Error destroy_link (Device_Link) = 23;
Device_Error create_intr_chan (Device_RemoteFunc) = 25;
Device_Error destroy_intr_chan (void) = 26;
} = 1;
} = 0x0607AF;
 
/******************************************************************************
*
* vxi11intr.rpcl
*
* This file is best viewed with a tabwidth of 4
*
******************************************************************************
*
* TODO:
*
******************************************************************************
*
* Original Author: someone from VXIbus Consortium
* Current Author: Benjamin Franksen
* Date: 03-06-97
*
* RPCL description of the intr-channel of the TCP/IP Instrument Protocol
* Specification.
*
*
* Modification Log:
* -----------------
* .00 03-06-97 bfr created this file
*
******************************************************************************
*
* Notes:
*
* This stuff is literally from
*
* "VXI-11, Ref 1.0 : TCP/IP Instrument Protocol Specification"
*
*/
 
struct Device_SrqParms
{
opaque handle<>;
};
 
program DEVICE_INTR
{
version DEVICE_INTR_VERSION
{
void device_intr_srq (Device_SrqParms) = 30;
} = 1;
} = 0x0607B1;
/lab/sipmscan/trunk/include/vxi11_x86_64/vxi11_cmd.cc
0,0 → 1,83
/* vxi11_cmd.c
* Copyright (C) 2006 Steve D. Sharples
*
* A simple interactive utility that allows you to send commands and queries to
* a device enabled with the VXI11 RPC ethernet protocol. Uses the files
* generated by rpcgen vxi11.x, and the vxi11_user.h user libraries.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The author's email address is steve.sharples@nottingham.ac.uk
*/
 
#include "vxi11_user.h"
#define BUF_LEN 100000
 
int main(int argc, char *argv[]) {
 
static char *device_ip;
static char *device_name;
char cmd[256];
char buf[BUF_LEN];
int ret;
long bytes_returned;
CLINK *clink;
 
clink = new CLINK;
 
if (argc < 2) {
printf("usage: %s your.inst.ip.addr [device_name]\n",argv[0]);
exit(1);
}
 
device_ip = argv[1];
if (argc > 2) {
device_name = argv[2];
ret=vxi11_open_device(device_ip,clink,device_name);
}
else {
ret=vxi11_open_device(device_ip,clink);
}
 
if (ret != 0) {
printf("Error: could not open device %s, quitting\n",device_ip);
exit(2);
}
 
while(1){
memset(cmd, 0, 256); // initialize command string
memset(buf, 0, BUF_LEN); // initialize buffer
printf("Input command or query ('q' to exit): ");
fgets(cmd,256,stdin);
cmd[strlen(cmd)-1] = 0; // just gets rid of the \n
if (strncasecmp(cmd, "q",1) == 0) break;
 
if (vxi11_send(clink, cmd) < 0) break;
if (strstr(cmd, "?") != 0) {
bytes_returned = vxi11_receive(clink, buf, BUF_LEN);
if (bytes_returned > 0) {
printf("%s\n",buf);
}
else if (bytes_returned == -15) {
printf("*** [ NOTHING RECEIVED ] ***\n");
}
else break;
}
}
 
ret=vxi11_close_device(device_ip,clink);
return 0;
}
 
/lab/sipmscan/trunk/include/vxi11_x86_64/vxi11_user.cc
0,0 → 1,589
/* vxi11_user.cc
* Copyright (C) 2006 Steve D. Sharples
*
* User library for opening, closing, sending to and receiving from
* a device enabled with the VXI11 RPC ethernet protocol. Uses the files
* generated by rpcgen vxi11.x.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The author's email address is steve.sharples@nottingham.ac.uk
*/
 
#include "vxi11_user.h"
 
/*****************************************************************************
* GENERAL NOTES
*****************************************************************************
*
* There are four functions at the heart of this library:
*
* int vxi11_open_device(char *ip, CLIENT **client, VXI11_LINK **link)
* int vxi11_close_device(char *ip, CLIENT *client, VXI11_LINK *link)
* int vxi11_send(CLIENT *client, VXI11_LINK *link, char *cmd, unsigned long len)
* long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len, unsigned long timeout)
*
* Note that all 4 of these use separate client and link structures. All the
* other functions are built on these four core functions, and the first layer
* of abstraction is to combine the CLIENT and VXI11_LINK structures into a
* single entity, which I've called a CLINK. For the send and receive
* functions, this is just a simple wrapper. For the open and close functions
* it's a bit more complicated, because we somehow have to keep track of
* whether we've already opened a device with the same IP address before (in
* which case we need to recycle a previously created client), or whether
* we've still got any other links to a given IP address left when we are
* asked to close a clink (in which case we can sever the link, but have to
* keep the client open). This is so the person using this library from
* userland does not have to keep track of whether they are talking to a
* different physical instrument or not each time they establish a connection.
*
* So the base functions that the user will probably want to use are:
*
* int vxi11_open_device(char *ip, CLINK *clink)
* int vxi11_close_device(char *ip, CLINK *clink)
* int vxi11_send(CLINK *clink, char *cmd, unsigned long len)
* --- or --- (if sending just text)
* int vxi11_send(CLINK *clink, char *cmd)
* long vxi11_receive(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout)
*
* There are then useful (to me, anyway) more specific functions built on top
* of these:
*
* int vxi11_send_data_block(CLINK *clink, char *cmd, char *buffer, unsigned long len)
* long vxi11_receive_data_block(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout)
* long vxi11_send_and_receive(CLINK *clink, char *cmd, char *buf, unsigned long buf_len, unsigned long timeout)
* long vxi11_obtain_long_value(CLINK *clink, char *cmd, unsigned long timeout)
* double vxi11_obtain_double_value(CLINK *clink, char *cmd, unsigned long timeout)
*
* (then there are some shorthand wrappers for the above without specifying
* the timeout due to sheer laziness---explore yourself)
*/
 
 
/* Global variables. Keep track of multiple links per client. We need this
* because:
* - we'd like the library to be able to cope with multiple links to a given
* client AND multiple links to multiple clients
* - we'd like to just refer to a client/link ("clink") as a single
* entity from user land, we don't want to worry about different
* initialisation procedures, depending on whether it's an instrument
* with the same IP address or not
*/
char VXI11_IP_ADDRESS[VXI11_MAX_CLIENTS][20];
CLIENT *VXI11_CLIENT_ADDRESS[VXI11_MAX_CLIENTS];
int VXI11_DEVICE_NO = 0;
int VXI11_LINK_COUNT[VXI11_MAX_CLIENTS];
 
/*****************************************************************************
* KEY USER FUNCTIONS - USE THESE FROM YOUR PROGRAMS OR INSTRUMENT LIBRARIES *
*****************************************************************************/
 
/* OPEN FUNCTIONS *
* ============== */
 
/* Use this function from user land to open a device and create a link. Can be
* used multiple times for the same device (the library will keep track).*/
int vxi11_open_device(const char *ip, CLINK *clink, char *device) {
int ret;
int l;
int device_no=-1;
 
// printf("before doing anything, clink->link = %ld\n", clink->link);
/* Have a look to see if we've already initialised an instrument with
* this IP address */
for (l=0; l<VXI11_MAX_CLIENTS; l++){
if (strcmp(ip,VXI11_IP_ADDRESS[l]) == 0 ) {
device_no=l;
// printf("Open function, search, found ip address %s, device no %d\n",ip,device_no);
}
}
 
/* Couldn't find a match, must be a new IP address */
if (device_no < 0) {
/* Uh-oh, we're out of storage space. Increase the #define
* for VXI11_MAX_CLIENTS in vxi11_user.h */
if (VXI11_DEVICE_NO >= VXI11_MAX_CLIENTS) {
printf("Error: maximum of %d clients allowed\n",VXI11_MAX_CLIENTS);
ret = -VXI11_MAX_CLIENTS;
}
/* Create a new client, keep a note of where the client pointer
* is, for this IP address. Because it's a new client, this
* must be link number 1. Keep track of how many devices we've
* opened so we don't run out of storage space. */
else {
ret = vxi11_open_device(ip, &(clink->client), &(clink->link), device);
strncpy(VXI11_IP_ADDRESS[VXI11_DEVICE_NO],ip,20);
VXI11_CLIENT_ADDRESS[VXI11_DEVICE_NO] = clink->client;
VXI11_LINK_COUNT[VXI11_DEVICE_NO]=1;
// printf("Open function, could not find ip address %s.\n",ip);
// printf("So now, VXI11_IP_ADDRESS[%d]=%s,\n",VXI11_DEVICE_NO,VXI11_IP_ADDRESS[VXI11_DEVICE_NO]);
// printf("VXI11_CLIENT_ADDRESS[%d]=%ld,\n",VXI11_DEVICE_NO,VXI11_CLIENT_ADDRESS[VXI11_DEVICE_NO]);
// printf(" clink->client=%ld,\n",clink->client);
// printf("VXI11_LINK_COUNT[%d]=%d.\n",VXI11_DEVICE_NO,VXI11_LINK_COUNT[VXI11_DEVICE_NO]);
VXI11_DEVICE_NO++;
}
}
/* already got a client for this IP address */
else {
/* Copy the client pointer address. Just establish a new link
* (not a new client). Add one to the link count */
clink->client = VXI11_CLIENT_ADDRESS[device_no];
ret = vxi11_open_link(ip, &(clink->client), &(clink->link), device);
// printf("Found an ip address, copying client from VXI11_CLIENT_ADDRESS[%d]\n",device_no);
VXI11_LINK_COUNT[device_no]++;
// printf("Have just incremented VXI11_LINK_COUNT[%d], it's now %d\n",device_no,VXI11_LINK_COUNT[device_no]);
}
// printf("after creating link, clink->link = %ld\n", clink->link);
return ret;
}
 
/* This is a wrapper function, used for the situations where there is only one
* "device" per client. This is the case for most (if not all) VXI11
* instruments; however, it is _not_ the case for devices such as LAN to GPIB
* gateways. These are single clients that communicate to many instruments
* (devices). In order to differentiate between them, we need to pass a device
* name. This gets used in the vxi11_open_link() fn, as the link_parms.device
* value. */
int vxi11_open_device(const char *ip, CLINK *clink) {
char device[6];
strncpy(device,"inst0",6);
return vxi11_open_device(ip, clink, device);
}
 
 
 
/* CLOSE FUNCTION *
* ============== */
 
/* Use this function from user land to close a device and/or sever a link. Can
* be used multiple times for the same device (the library will keep track).*/
int vxi11_close_device(const char *ip, CLINK *clink) {
int l,ret;
int device_no = -1;
 
/* Which instrument are we referring to? */
for (l=0; l<VXI11_MAX_CLIENTS; l++){
if (strcmp(ip,VXI11_IP_ADDRESS[l]) == 0 ) {
device_no=l;
}
}
/* Something's up if we can't find the IP address! */
if (device_no == -1) {
printf("vxi11_close_device: error: I have no record of you ever opening device\n");
printf(" with IP address %s\n",ip);
ret = -4;
}
else { /* Found the IP, there's more than one link to that instrument,
* so keep track and just close the link */
if (VXI11_LINK_COUNT[device_no] > 1 ) {
ret = vxi11_close_link(ip,clink->client, clink->link);
VXI11_LINK_COUNT[device_no]--;
}
/* Found the IP, it's the last link, so close the device (link
* AND client) */
else {
ret = vxi11_close_device(ip, clink->client, clink->link);
/* Remove the IP address, so that if we re-open the same device
* we do it properly */
memset(VXI11_IP_ADDRESS[device_no], 0, 20);
}
}
return ret;
}
 
 
/* SEND FUNCTIONS *
* ============== */
 
/* A _lot_ of the time we are sending text strings, and can safely rely on
* strlen(cmd). */
int vxi11_send(CLINK *clink, const char *cmd) {
return vxi11_send(clink, cmd, strlen(cmd));
}
 
/* We still need the version of the function where the length is set explicitly
* though, for when we are sending fixed length data blocks. */
int vxi11_send(CLINK *clink, const char *cmd, unsigned long len) {
return vxi11_send(clink->client, clink->link, cmd, len);
}
 
 
/* RECEIVE FUNCTIONS *
* ================= */
 
/* Lazy wrapper for when I can't be bothered to specify a read timeout */
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len) {
return vxi11_receive(clink, buffer, len, VXI11_READ_TIMEOUT);
}
 
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout) {
return vxi11_receive(clink->client, clink->link, buffer, len, timeout);
}
 
 
 
/*****************************************************************************
* USEFUL ADDITIONAL HIGHER LEVER USER FUNCTIONS - USE THESE FROM YOUR *
* PROGRAMS OR INSTRUMENT LIBRARIES *
*****************************************************************************/
 
/* SEND FIXED LENGTH DATA BLOCK FUNCTION *
* ===================================== */
int vxi11_send_data_block(CLINK *clink, const char *cmd, char *buffer, unsigned long len) {
char *out_buffer;
int cmd_len=strlen(cmd);
int ret;
 
out_buffer=new char[cmd_len+10+len];
sprintf(out_buffer,"%s#8%08lu",cmd,len);
memcpy(out_buffer+cmd_len+10,buffer,(unsigned long) len);
ret = vxi11_send(clink, out_buffer, (unsigned long) (cmd_len+10+len));
delete[] out_buffer;
return ret;
}
 
/* RECEIVE FIXED LENGTH DATA BLOCK FUNCTION *
* ======================================== */
 
/* This function reads a response in the form of a definite-length block, such
* as when you ask for waveform data. The data is returned in the following
* format:
* #800001000<1000 bytes of data>
* ||\______/
* || |
* || \---- number of bytes of data
* |\--------- number of digits that follow (in this case 8, with leading 0's)
* \---------- always starts with #
*/
long vxi11_receive_data_block(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout) {
/* I'm not sure what the maximum length of this header is, I'll assume it's
* 11 (#9 + 9 digits) */
unsigned long necessary_buffer_size;
char *in_buffer;
int ret;
int ndigits;
unsigned long returned_bytes;
int l;
char scan_cmd[20];
necessary_buffer_size=len+12;
in_buffer=new char[necessary_buffer_size];
ret=vxi11_receive(clink, in_buffer, necessary_buffer_size, timeout);
if (ret < 0) return ret;
if (in_buffer[0] != '#') {
printf("vxi11_user: data block error: data block does not begin with '#'\n");
printf("First 20 characters received were: '");
for(l=0;l<20;l++) {
printf("%c",in_buffer[l]);
}
printf("'\n");
return -3;
}
 
/* first find out how many digits */
sscanf(in_buffer,"#%1d",&ndigits);
/* some instruments, if there is a problem acquiring the data, return only "#0" */
if (ndigits > 0) {
/* now that we know, we can convert the next <ndigits> bytes into an unsigned long */
sprintf(scan_cmd,"#%%1d%%%dlu",ndigits);
sscanf(in_buffer,scan_cmd,&ndigits,&returned_bytes);
memcpy(buffer, in_buffer+(ndigits+2), returned_bytes);
delete[] in_buffer;
return (long) returned_bytes;
}
else return 0;
}
 
 
/* SEND AND RECEIVE FUNCTION *
* ========================= */
 
/* This is mainly a useful function for the overloaded vxi11_obtain_value()
* fn's, but is also handy and useful for user and library use */
long vxi11_send_and_receive(CLINK *clink, const char *cmd, char *buf, unsigned long buf_len, unsigned long timeout) {
int ret;
long bytes_returned;
do {
ret = vxi11_send(clink, cmd);
if (ret != 0) {
if (ret != -VXI11_NULL_WRITE_RESP) {
printf("Error: vxi11_send_and_receive: could not send cmd.\n");
printf(" The function vxi11_send returned %d. ",ret);
return -1;
}
else printf("(Info: VXI11_NULL_WRITE_RESP in vxi11_send_and_receive, resending query)\n");
}
 
bytes_returned = vxi11_receive(clink, buf, buf_len, timeout);
if (bytes_returned <= 0) {
if (bytes_returned >-VXI11_NULL_READ_RESP) {
printf("Error: vxi11_send_and_receive: problem reading reply.\n");
printf(" The function vxi11_receive returned %ld. ",bytes_returned);
return -2;
}
else printf("(Info: VXI11_NULL_READ_RESP in vxi11_send_and_receive, resending query)\n");
}
} while (bytes_returned == -VXI11_NULL_READ_RESP || ret == -VXI11_NULL_WRITE_RESP);
return 0;
}
 
 
/* FUNCTIONS TO RETURN A LONG INTEGER VALUE SENT AS RESPONSE TO A QUERY *
* ==================================================================== */
long vxi11_obtain_long_value(CLINK *clink, const char *cmd, unsigned long timeout) {
char buf[50]; /* 50=arbitrary length... more than enough for one number in ascii */
memset(buf, 0, 50);
if (vxi11_send_and_receive(clink, cmd, buf, 50, timeout) != 0) {
printf("Returning 0\n");
return 0;
}
return strtol(buf, (char **)NULL, 10);
}
 
/* Lazy wrapper function with default read timeout */
long vxi11_obtain_long_value(CLINK *clink, const char *cmd) {
return vxi11_obtain_long_value(clink, cmd, VXI11_READ_TIMEOUT);
}
 
 
/* FUNCTIONS TO RETURN A DOUBLE FLOAT VALUE SENT AS RESPONSE TO A QUERY *
* ==================================================================== */
double vxi11_obtain_double_value(CLINK *clink, const char *cmd, unsigned long timeout) {
char buf[50]; /* 50=arbitrary length... more than enough for one number in ascii */
double val;
memset(buf, 0, 50);
if (vxi11_send_and_receive(clink, cmd, buf, 50, timeout) != 0) {
printf("Returning 0.0\n");
return 0.0;
}
val = strtod(buf, (char **)NULL);
return val;
}
 
/* Lazy wrapper function with default read timeout */
double vxi11_obtain_double_value(CLINK *clink, const char *cmd) {
return vxi11_obtain_double_value(clink, cmd, VXI11_READ_TIMEOUT);
}
 
 
/*****************************************************************************
* CORE FUNCTIONS - YOU SHOULDN'T NEED TO USE THESE FROM YOUR PROGRAMS OR *
* INSTRUMENT LIBRARIES *
*****************************************************************************/
 
/* OPEN FUNCTIONS *
* ============== */
int vxi11_open_device(const char *ip, CLIENT **client, VXI11_LINK **link, char *device) {
 
*client = clnt_create(ip, DEVICE_CORE, DEVICE_CORE_VERSION, "tcp");
 
if (*client == NULL) {
clnt_pcreateerror(ip);
return -1;
}
 
return vxi11_open_link(ip, client, link, device);
}
 
int vxi11_open_link(const char *ip, CLIENT **client, VXI11_LINK **link, char *device) {
 
Create_LinkParms link_parms;
 
/* Set link parameters */
link_parms.clientId = (long) *client;
link_parms.lockDevice = 0;
link_parms.lock_timeout = VXI11_DEFAULT_TIMEOUT;
link_parms.device = device;
 
*link = (Create_LinkResp *) calloc(1, sizeof(Create_LinkResp));
 
if (create_link_1(&link_parms, *link, *client) != RPC_SUCCESS) {
clnt_perror(*client, ip);
return -2;
}
return 0;
}
 
 
/* CLOSE FUNCTIONS *
* =============== */
int vxi11_close_device(const char *ip, CLIENT *client, VXI11_LINK *link) {
int ret;
 
ret = vxi11_close_link(ip, client, link);
 
clnt_destroy(client);
 
return ret;
}
 
int vxi11_close_link(const char *ip, CLIENT *client, VXI11_LINK *link) {
Device_Error dev_error;
memset(&dev_error, 0, sizeof(dev_error));
 
if (destroy_link_1(&link->lid, &dev_error, client) != RPC_SUCCESS) {
clnt_perror(client,ip);
return -1;
}
 
return 0;
}
 
 
/* SEND FUNCTIONS *
* ============== */
 
/* A _lot_ of the time we are sending text strings, and can safely rely on
* strlen(cmd). */
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd) {
return vxi11_send(client, link, cmd, strlen(cmd));
}
 
/* We still need the version of the function where the length is set explicitly
* though, for when we are sending fixed length data blocks. */
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd, unsigned long len) {
Device_WriteParms write_parms;
unsigned int bytes_left = len;
char *send_cmd;
 
send_cmd = new char[len];
memcpy(send_cmd, cmd, len);
 
write_parms.lid = link->lid;
write_parms.io_timeout = VXI11_DEFAULT_TIMEOUT;
write_parms.lock_timeout = VXI11_DEFAULT_TIMEOUT;
 
/* We can only write (link->maxRecvSize) bytes at a time, so we sit in a loop,
* writing a chunk at a time, until we're done. */
 
do {
Device_WriteResp write_resp;
memset(&write_resp, 0, sizeof(write_resp));
 
if (bytes_left <= link->maxRecvSize) {
write_parms.flags = 8;
write_parms.data.data_len = bytes_left;
}
else {
write_parms.flags = 0;
/* We need to check that maxRecvSize is a sane value (ie >0). Believe it
* or not, on some versions of Agilent Infiniium scope firmware the scope
* returned "0", which breaks Rule B.6.3 of the VXI-11 protocol. Nevertheless
* we need to catch this, otherwise the program just hangs. */
if (link->maxRecvSize > 0) {
write_parms.data.data_len = link->maxRecvSize;
}
else {
write_parms.data.data_len = 4096; /* pretty much anything should be able to cope with 4kB */
}
}
write_parms.data.data_val = send_cmd + (len - bytes_left);
if(device_write_1(&write_parms, &write_resp, client) != RPC_SUCCESS) {
delete[] send_cmd;
return -VXI11_NULL_WRITE_RESP; /* The instrument did not acknowledge the write, just completely
dropped it. There was no vxi11 comms error as such, the
instrument is just being rude. Usually occurs when the instrument
is busy. If we don't check this first, then the following
line causes a seg fault */
}
if (write_resp.error != 0) {
printf("vxi11_user: write error: %d\n", (int)write_resp.error);
delete[] send_cmd;
return -(write_resp.error);
}
bytes_left -= write_resp.size;
} while (bytes_left > 0);
 
delete[] send_cmd;
return 0;
}
 
 
/* RECEIVE FUNCTIONS *
* ================= */
 
// It appeared that this function wasn't correctly dealing with more data available than specified in len.
// This patch attempts to fix this issue. RDP 2007/8/13
 
/* wrapper, for default timeout */ long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len) { return vxi11_receive(client, link, buffer, len, VXI11_READ_TIMEOUT);
}
 
#define RCV_END_BIT 0x04 // An end indicator has been read
#define RCV_CHR_BIT 0x02 // A termchr is set in flags and a character which matches termChar is transferred
#define RCV_REQCNT_BIT 0x01 // requestSize bytes have been transferred. This includes a request size of zero.
 
long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len, unsigned long timeout) {
Device_ReadParms read_parms;
Device_ReadResp read_resp;
unsigned long curr_pos = 0;
 
read_parms.lid = link->lid;
read_parms.requestSize = len;
read_parms.io_timeout = timeout; /* in ms */
read_parms.lock_timeout = timeout; /* in ms */
read_parms.flags = 0;
read_parms.termChar = 0;
 
do {
memset(&read_resp, 0, sizeof(read_resp));
 
read_resp.data.data_val = buffer + curr_pos;
read_parms.requestSize = len - curr_pos; // Never request more total data than originally specified in len
 
if(device_read_1(&read_parms, &read_resp, client) != RPC_SUCCESS) {
return -VXI11_NULL_READ_RESP; /* there is nothing to read. Usually occurs after sending a query
which times out on the instrument. If we don't check this first,
then the following line causes a seg fault */
}
if (read_resp.error != 0) {
/* Read failed for reason specified in error code.
* (From published VXI-11 protocol, section B.5.2)
* 0 no error
* 1 syntax error
* 3 device not accessible
* 4 invalid link identifier
* 5 parameter error
* 6 channel not established
* 8 operation not supported
* 9 out of resources
* 11 device locked by another link
* 12 no lock held by this link
* 15 I/O timeout
* 17 I/O error
* 21 invalid address
* 23 abort
* 29 channel already established
*/
 
printf("vxi11_user: read error: %d\n", (int)read_resp.error);
return -(read_resp.error);
}
 
if((curr_pos + read_resp.data.data_len) <= len) {
curr_pos += read_resp.data.data_len;
}
if( (read_resp.reason & RCV_END_BIT) || (read_resp.reason & RCV_CHR_BIT) ) {
break;
}
else if( curr_pos == len ) {
printf("xvi11_user: read error: buffer too small. Read %d bytes without hitting terminator.\n", (int)curr_pos );
return -100;
}
} while(1);
return (curr_pos); /*actual number of bytes received*/
 
}
 
/lab/sipmscan/trunk/include/vxi11_x86_64/vxi11_user.h
0,0 → 1,87
/* vxi11_user.h
* Copyright (C) 2006 Steve D. Sharples
*
* User library for opening, closing, sending to and receiving from
* a device enabled with the VXI11 RPC ethernet protocol. Uses the files
* generated by rpcgen vxi11.x.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The author's email address is steve.sharples@nottingham.ac.uk
*/
 
#ifndef __VXI11_USER__
#define __VXI11_USER__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include <rpc/rpc.h>
#include "vxi11.h"
 
#define VXI11_DEFAULT_TIMEOUT 10000 /* in ms */
#define VXI11_READ_TIMEOUT 2000 /* in ms */
#define VXI11_CLIENT CLIENT
#define VXI11_LINK Create_LinkResp
#define VXI11_MAX_CLIENTS 256 /* maximum no of unique IP addresses/clients */
#define VXI11_NULL_READ_RESP 50 /* vxi11_receive() return value if a query
* times out ON THE INSTRUMENT (and so we have
* to resend the query again) */
#define VXI11_NULL_WRITE_RESP 51 /* vxi11_send() return value if a sent command
* times out ON THE INSTURMENT. */
 
struct CLINK {
VXI11_CLIENT *client;
VXI11_LINK *link;
} ;
typedef struct CLINK CLINK;
 
/* The four main functions: open, close, send, receieve (plus a couple of wrappers) */
/* In fact all 6 of these are wrappers to the original functions listed at the
* bottom, that use separate CLIENT and VXI11_LINK structures. It was easier to
* write wrappers for these functions than to re-write the original functions
* themselves. These are the 4 (or 6 if you like) key user functions that you
* should probably be using. They all use the CLINK structure. */
int vxi11_open_device(const char *ip, CLINK *clink);
int vxi11_open_device(const char *ip, CLINK *clink, char *device);
int vxi11_close_device(const char *ip, CLINK *clink);
int vxi11_send(CLINK *clink, const char *cmd);
int vxi11_send(CLINK *clink, const char *cmd, unsigned long len);
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len);
long vxi11_receive(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout);
 
/* Utility functions, that use send() and receive(). Use these too. */
int vxi11_send_data_block(CLINK *clink, const char *cmd, char *buffer, unsigned long len);
long vxi11_receive_data_block(CLINK *clink, char *buffer, unsigned long len, unsigned long timeout);
long vxi11_send_and_receive(CLINK *clink, const char *cmd, char *buf, unsigned long buf_len, unsigned long timeout);
long vxi11_obtain_long_value(CLINK *clink, const char *cmd, unsigned long timeout);
double vxi11_obtain_double_value(CLINK *clink, const char *cmd, unsigned long timeout);
long vxi11_obtain_long_value(CLINK *clink, const char *cmd);
double vxi11_obtain_double_value(CLINK *link, const char *cmd);
 
/* When I first wrote this library I used separate client and links. I've
* retained the original functions and just written clink wrappers for them
* (see above) as it's perhaps a little clearer this way. Probably not worth
* delving this deep in use, but it's where the real nitty gritty is. */
int vxi11_open_device(const char *ip, CLIENT **client, VXI11_LINK **link, char *device);
int vxi11_open_link(const char *ip, CLIENT **client, VXI11_LINK **link, char *device);
int vxi11_close_device(const char *ip, CLIENT *client, VXI11_LINK *link);
int vxi11_close_link(const char *ip, CLIENT *client, VXI11_LINK *link);
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd);
int vxi11_send(CLIENT *client, VXI11_LINK *link, const char *cmd, unsigned long len);
long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len);
long vxi11_receive(CLIENT *client, VXI11_LINK *link, char *buffer, unsigned long len, unsigned long timeout);
 
#endif
/lab/sipmscan/trunk/include/workstation.h
0,0 → 1,33
#ifndef _workstation_h_
#define _workstation_h_
 
// Debug signal (0 = no debug, 1 = printout debug, 2 = structure + printout debug)
#define DBGSIG 0
 
// Define the working computer (O=offline, S=offline with scope, I=IJS/online) and the base directory
#define WORKSTAT 'O'
 
// Define if working computer is connected to IJS ethernet network (for fieldpoint)
#define IJSNET 0
 
#ifdef WORKSTAT
#define rootdir "/home/gasper/Gasper/Delo/ijs_sipm/sipmscan_standalone"
#endif
 
// Title colors and font
#define FORECOLOR 0xfcfcfc
#define BACKCOLOR 0x2e5a86
#define FONT "-*-helvetica-bold-r-normal-*-13-*-*-*-*-*-iso8859-"
#define HELPFONT "-*-courier-bold-r-normal-*-13-*-*-*-*-*-iso8859-"
 
// Global variables
#define histext ".root"
#define histextall "*.root"
#define tdctimeconversion 45.0909
#define lenconversion 0.3595
#define rotconversion (6.3281/3600.)
#define histname "hdata"
#define singlewait 3
#define doublewait 2
 
#endif
/lab/sipmscan/trunk/include/wusbcc.h
0,0 → 1,15
#ifndef _WUSBCC_H
#define _WUSBCC_H
 
#define NAF(N,A,F) 0x4000+(N)*0x200+(A)*0x20+(F)
#define NAFS(N,A,F) (N)*0x200+(A)*0x20+(F)
 
#define CSSA_RQX(N,A,F,DATA,Q,X) CAMAC_read(udev,(N),(A),(F),(DATA),(Q),(X))
#define CSSA_WQX(N,A,F,DATA,Q,X) CAMAC_write(udev,(N),(A),(F),(DATA),(Q),(X))
 
#define CCCZ CAMAC_Z(udev)
#define CCCC CAMAC_C(udev)
#define CSET_I CAMAC_I(udev,1)
#define CREM_I CAMAC_I(udev,0)
 
#endif
/lab/sipmscan/trunk/include/wusbxx_dll.h
0,0 → 1,19
#ifndef _WUSBXX_DLL_H
#define _WUSBXX_DLL_H
 
#include <stdlib.h>
#include <stdio.h>
 
#include "libxxusb.h"
#include "wusbcc.h"
#define _VI_FUNC
extern usb_dev_handle *udev;
 
void _VI_FUNC WUSBXX_load (char *module_path);
void _VI_FUNC WUSBXX_open (char *serial);
void _VI_FUNC WUSBXX_close (void);
int _VI_FUNC WUSBXX_CCread (int n, int a, int f, unsigned long *data);
int _VI_FUNC WUSBXX_CCwrite (int n, int a, int f, unsigned long data);
 
#endif
 
/lab/sipmscan/trunk/input/Makefile.in
0,0 → 1,149
# Makefile tutorial: https://www.gnu.org/software/make/manual/html_node/index.html#SEC_Contents
# Make variables ----------------------------------------------------
 
# ROOT include and libraries
ROOTINC=$(shell root-config --incdir)
ROOTLIB=$(shell root-config --libs)
GRROOTLIB=$(shell root-config --cflags --glibs)
 
# Source and debug directories
SRC=./src
DBG=./dbg
IDIR=./include
BIN=./bin
DICT=./dict
LDIR=./lib
 
# Includes and libraries, 32 vs. 64 bit type, libraries
INC=-I. -I$(ROOTINC)
OSTYPE=none
LIBS=$(ROOTLIB) -L. -lm
 
# Compiler options
COMPOPT=-fPIC -g -Wno-unused-value
#COMPOPT=-fPIC -g -Wall
 
# CAMAC DAQ library variables
OBJ_FILES = $(SRC)/wusbxx_dll.o $(SRC)/libxxusb.o
LIBFILE = $(LDIR)/libdaqusb.a
 
# Specific variables for the main program
TARGET=sipmscan
#FILES=$(SRC)/sipmscan.cpp $(SRC)/substructure.cpp $(SRC)/connections.cpp $(SRC)/window_layout.cpp $(SRC)/separate_functions.cpp $(SRC)/tooltips.cpp
DAQFILE = $(SRC)/daqusb.C
#FILES=$(wildcard $(SRC)/*.cpp) $(SRC)/daqusb.C $(SRC)/daqscope.C
FILES=$(shell find $(SRC)/ ! -name "libxxusb.cpp" -name "*.cpp") $(SRC)/daqusb.C $(SRC)/daqscope.C
HEADER=$(IDIR)/daq.h $(IDIR)/workstation.h $(IDIR)/sipmscan.h $(IDIR)/root_include.h
CAMLIB = $(LIBFILE)
SHLIB = $(LIBFILE) $(LDIR)/libvxi11.a
 
# VXI scope connection variables, Scope DAQ library variables
VXIDIR = $(IDIR)/vxi11_$(OSTYPE)
#VXI_FILES = $(VXIDIR)/vxi11_user.o $(VXIDIR)/vxi11.h $(VXIDIR)/vxi11_clnt.c $(VXIDIR)/vxi11_xdr.c
VXI_OBJECT = $(VXIDIR)/vxi11_user.o $(VXIDIR)/vxi11_clnt.o $(VXIDIR)/vxi11_xdr.o
 
# -------------------------------------------------------------------
 
# Base rules --------------------------------------------------------
 
# Make the main program and libraries
all: libsubstr.so $(LDIR)/libdaqusb.so $(LDIR)/libvxi11.so $(TARGET)
 
# Rules for making the main program
$(TARGET): $(FILES) library
@echo "\n# Generating dictionary GuiDict.C ---------------------------"
rootcint -f $(DICT)/GuiDict.C -c -p $(INC) $(CPPFLAGS) $(IDIR)/sipmscan.h $(DICT)/GuiLinkDef.h
@echo "\n# Checking to see if bin directory already exists -----------"
if [ ! -d "$(BIN)" ];then mkdir $(BIN); fi
@echo "\n# Compiling main program ------------------------------------"
$(CXX) $(INC) $(COMPOPT) $(FILES) $(DICT)/GuiDict.C $(CPPFLAGS) $(VXI_OBJECT) -o $(BIN)/$(TARGET) $(SHLIB) $(GRROOTLIB) -lstdc++ -lSpectrum -L$(LDIR)/libsubstr.so -L$(LDIR)/libdaqusb.so -L$(LDIR)/libvxi11.so
@echo "\n# Compilation successful ------------------------------------"
@echo "# Use ./start.sh to run the program -------------------------"
 
# -------------------------------------------------------------------
 
# CAMAC DAQ library rules -----------------------------------------------------
 
# Rules for making CAMAC DAQ library source files (wusbxx_dll and libxxusb)
library: $(OBJ_FILES)
 
$(OBJ_FILES): $(SRC)/wusbxx_dll.c $(IDIR)/wusbxx_dll.h $(SRC)/libxxusb.cpp $(IDIR)/libxxusb.h
@echo "\n# Compiling CAMAC USB source files --------------------------"
$(CXX) $(CPPFLAGS) $(INC) -c $(SRC)/wusbxx_dll.c -o $(SRC)/wusbxx_dll.o
$(CXX) $(CPPFLAGS) $(INC) -c $(SRC)/libxxusb.cpp -o $(SRC)/libxxusb.o
 
.cc.o:
@echo "\n# Creating a static CAMAC USB library (libdaqusb.a) ---------"
$(CXX) -fPIC -c $<
ar r $(LIBFILE) $@
 
.cpp.o:
@echo "\n# Creating a static CAMAC USB library (libdaqusb.a) ---------"
$(CXX) -fPIC -c $<
ar r $(LIBFILE) $@
 
.c.o:
@echo "\n# Creating a static CAMAC USB library (libdaqusb.a) ---------"
$(CXX) -fPIC -c $<
ar r $(LIBFILE) $@
 
# Rule for making the CAMAC DAQ library (libdaqusb.so)
$(LDIR)/libdaqusb.so: $(LIBFILE) $(DAQFILE)
@echo "\n# Generating dictionary Dict.C ------------------------------"
rootcint -f $(DICT)/Dict.C -c $(INC) $(CPPFLAGS) $(HEADER) $(DICT)/LibLinkDef.h
@echo "\n# Checking to see if lib directory already exists -----------"
if [ ! -d "$(LDIR)" ];then mkdir $(LDIR); fi
@echo "\n# Compiling CAMAC DAQ library (libdaqusb.so) ----------------"
$(CXX) $(CPPFLAGS) $(INC) -fPIC -g -Wall $(DAQFILE) $(DICT)/Dict.C $(CAMLIB) -shared -o $@
 
# Rule for making the CAMAC DAQ library (libdaqusb.a)
$(LIBFILE): $(OBJ_FILES)
@echo "\n# Creating a static CAMAC USB library (libdaqusb.a) ---------"
ar r $@ $^
# -----------------------------------------------------------------------------
 
# Scope DAQ library rules -----------------------------------------------------
 
$(LDIR)/libvxi11.so: $(LDIR)/libvxi11.a
@echo "\n# Generating dictionary VxiDict.C ---------------------------"
rootcint -f $(DICT)/VxiDict.C -c $(INC) $(CPPFLAGS) $(IDIR)/daqscope.h $(DICT)/LibLinkDef.h
@echo "\n# Checking to see if lib directory already exists -----------"
if [ ! -d "$(LDIR)" ];then mkdir $(LDIR); fi
@echo "\n# Compiling scope VXI library (libvxi11.so) -----------------"
$(CXX) $(CPPFLAGS) $(INC) -fPIC -g -Wall $(SRC)/daqscope.C $(DICT)/VxiDict.C -L. $(LDIR)/libvxi11.a -shared -o $@
 
$(LDIR)/libvxi11.a: $(VXI_OBJECT)
ar r $@ $^
# -----------------------------------------------------------------------------
 
# Substructue library rules ---------------------------------------------------
 
# Rules for making user defined libraries
libsubstr.so: libsubstr.a
@echo "\n# Creating a shared testing library -------------------------"
rootcint -f $(DICT)/TestDict.C -c $(INC) $(CPPFLAGS) $(IDIR)/substructure.h $(DICT)/TestLinkDef.h
$(CXX) $(CPPFLAGS) $(INC) $(COMPOPT) $(SRC)/substructure.cpp $(DICT)/TestDict.C libsubstr.a -shared -o $@
@echo "\n# Checking to see if lib directory already exists -----------"
if [ ! -d "$(LDIR)" ];then mkdir $(LDIR); fi
mv $@ $^ $(LDIR)/
 
libsubstr.a: $(SRC)/substructure.o
@echo "\n# Creating a static testing library -------------------------"
ar r $@ $^
 
$(SRC)/substructure.o: $(SRC)/substructure.cpp $(IDIR)/substructure.h
@echo "\n# Compiling separate source files ---------------------------"
$(CXX) $(CPPFLAGS) $(INC) -c $(SRC)/substructure.cpp -o $(SRC)/substructure.o
 
# -------------------------------------------------------------------
 
# Cleaning rules ----------------------------------------------------
 
# Rules for cleaning the installation
clean:
@echo "# Cleaning the installation directory -------------------------"
rm -fr $(DICT)/*Dict.C $(DICT)/*Dict.h $(BIN) $(LDIR) start.sh *.o $(SRC)/*.o
rm -fr $(IDIR)/workstation.h $(SRC)/daqscope.C $(SRC)/daqusb.C $(IDIR)/usb.h $(IDIR)/libxxusb.h $(DBG)/finish_sig.txt
 
# -------------------------------------------------------------------
/lab/sipmscan/trunk/input/daqscope.C.in
0,0 → 1,390
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include "vxi11_user.h"
#include "../include/daqscope.h"
#include "../include/workstation.h"
 
CLINK *clink;
char *savedIP;
const char *allChans[8] = {"CH1","CH2","CH3","CH4","MATH1","MATH2","MATH3","MATH4"};
const char *measType[11] = {"AMP","ARE","DEL","FALL","FREQ","MAX","MEAN","MINI","PK2P","PWI","RIS"};
char *bbq;
 
// Query and command functions to simplify analysis --------------
int vxi11_query(CLINK *clink, const char *mycmd)
{
char buf[WAVE_LEN];
memset(buf, 0, WAVE_LEN);
vxi11_send(clink, mycmd);
int bytes_returned = vxi11_receive(clink, buf, WAVE_LEN);
if (bytes_returned > 0)
{
printf("%s\n", buf);
}
else if (bytes_returned == -15)
printf("*** [ NOTHING RECEIVED ] ***\n");
 
return 0;
}
 
void vxi11_command(CLINK *clink,char *mycmd)
{
char buf[WAVE_LEN];
memset(buf, 0, WAVE_LEN);
vxi11_send(clink, mycmd);
}
// ---------------------------------------------------------------
 
// Tektronix unit conversion -------------------------------------
double daqscope::tekunit(char *prefix)
{
if (strcmp(prefix,"m")==0) return 0.001;
else if (strcmp(prefix,"u")==0) return 0.000001;
else if (strcmp(prefix,"n")==0) return 0.000000001;
else return 1;
}
// ---------------------------------------------------------------
 
// Connect to a scope through IP address IPaddr ------------------
int daqscope::connect(char *IPaddr)
{
int iTemp;
char buf[WAVE_LEN];
printf("daqscope::connect(%s)\n", IPaddr);
clink = new CLINK;
iTemp = vxi11_open_device(IPaddr, clink);
if(iTemp == 0)
{
vxi11_send(clink, "*IDN?");
vxi11_receive(clink, buf, WAVE_LEN);
printf("Connected to device (%s): %s\n", IPaddr, buf);
savedIP = IPaddr;
return iTemp;
}
else
return iTemp;
}
// ---------------------------------------------------------------
 
// Disconnect from scope with IP address IPaddr ------------------
int daqscope::disconnect(char *IPaddr)
{
int iTemp;
printf("daqscope::disconnect(%s)\n", IPaddr);
iTemp = vxi11_close_device(IPaddr, clink);
if(iTemp == 0)
{
printf("Disconnected from device (%s).\n", IPaddr);
delete clink;
}
return iTemp;
}
// ---------------------------------------------------------------
 
// Initialize the scope for waveform or measurement --------------
int daqscope::init()
{
int iTemp;
char cmd[512];
char cTemp[256];
printf("daqscope::init()\n");
 
printf("Measurement type is: %d\n", scopeUseType);
 
// For measurements, only one channel can be used (rise, fall, period,...)
if(scopeUseType == 2) scopeChanNr = 1;
printf("Nr. of channels selected: %d\n", scopeChanNr);
 
// Only use scope if measurement is different than 0
if(scopeUseType == 0)
return 0;
else
{
// Combine all selected channels into a comma separated string
for(int i = 0; i < scopeChanNr; i++)
{
if(i == scopeChanNr-1)
{
if(i == 0) sprintf(scopeChanstring, "%s", allChans[scopeChans[i]]);
else sprintf(cTemp, "%s", allChans[scopeChans[i]]);
}
else
{
if(i == 0) sprintf(scopeChanstring, "%s,", allChans[scopeChans[i]]);
else sprintf(cTemp, "%s,", allChans[scopeChans[i]]);
}
if(i > 0)
strcat(scopeChanstring, cTemp);
}
printf("Selected channels: %s\n", scopeChanstring);
 
// Check scope ID and turn the header display on
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_query(clink, "*IDN?");
vxi11_command(clink,(char*)"HEADER ON");
#else
printf("Identify Tek (*IDN?, HEADER ON)\n");
#endif
 
// Set the scope data sources
sprintf(cmd, "DATA:SOURCE %s", scopeChanstring);
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink,cmd);
#else
printf("Set data source (DATA:SOURCE): %s\n", cmd);
#endif
 
// Set to fast acquisition and set encoding
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink,(char*)"FASTACQ:STATE 0");
vxi11_command(clink,(char*)"DATA:ENCDG SRIBINARY");
vxi11_command(clink,(char*)"WFMO:BYT_N 2");
 
// Set gating (currently not used)
vxi11_command(clink,(char*)"GAT OFF");
#else
printf("Set fastacq, encoding and gating (FASTACQ:STATE 0, DATA:ENCDG SRIBINARY, WFMO:BYT_N 2, MEASU:GAT OFF).\n");
#endif
 
// Check scale on each of selected channels (is this even needed?)
bbq = strtok(scopeChanstring,",");
while(bbq != NULL)
{
sprintf(cmd,"%s:SCALE?",bbq);
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_query(clink,cmd);
#else
printf("Return the scale of channel: %s\n", cmd);
#endif
bbq = strtok(NULL, ",");
}
 
// Check waveform and data options/settings
char buf[WAVE_LEN];
memset(buf, 0, WAVE_LEN);
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_send(clink, "WFMO:WFID?");
iTemp = vxi11_receive(clink, buf, WAVE_LEN);
printf("Init out (length = %d): %s\n", iTemp, buf);
#else
printf("Get acquisition parameters (WFMOUTPRE:WFID?).\n");
sprintf(buf, ":WFMOUTPRE:WFID \"Ch1, DC coupling, 20.0mV/div, 10.0ns/div, 500 points, Sample mode\"");
iTemp = strlen(buf);
#endif
if (iTemp == -15)
printf("\n*** [ NOTHING RECEIVED ] ***\n");
else
{
bbq = strtok(buf,","); // break WFID out into substrings
for (int k = 0; k < 5; k++)
{
// info on voltage per division setting
if (k == 2)
{
memcpy(cTemp, &bbq[1], 5);
cTemp[5] = 0;
bbq[7] = 0;
tekvolt = atoi(cTemp)*tekunit(&bbq[6]);
printf("Voltage per division: %lf\n", tekvolt);
}
// info on time per division setting
if (k == 3)
{
memcpy(cTemp, &bbq[1], 5);
cTemp[5] = 0;
bbq[7] = 0;
tektime = atoi(cTemp)*tekunit(&bbq[6]);
printf("Time per division: %lf\n", tektime);
}
// info on last point to be transfered by CURVE?
if (k == 4)
{
bbq[strlen(bbq)-7] = 0;
sprintf(cmd, "DATA:STOP %d", atoi(bbq));
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink, cmd);
#else
printf("Stop data collection (DATA:STOP): %s\n", cmd);
#endif
}
// printf("bbq = %s\n",bbq);
bbq = strtok (NULL, ",");
}
}
 
// Recheck waveform and data options/settings, turn off header
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_query(clink,"WFMO:WFID?");
vxi11_query(clink,"DATA?");
vxi11_command(clink,(char*)"HEADER OFF");
#else
printf("Data format query (WFMOUTPRE:WFID?, DATA?, HEADER OFF).\n");
#endif
 
// Get the channel y-axis offset (only for one CH so far)
char posoff[WAVE_LEN];
#if WORKSTAT == 'I' || WORKSTAT == 'S'
sprintf(cmd, "%s:POS?", allChans[scopeChans[0]]);
vxi11_command(clink, cmd);
vxi11_receive(clink, posoff, WAVE_LEN);
choffset = (double)atof(posoff);
#else
sprintf(posoff, "Just some temporary string info.");
printf("Check for channel position offset (CHx:POS?)\n");
#endif
 
// If measurements are to be performed
if(scopeUseType == 2)
{
sprintf(cmd, "MEASU:IMM:SOURCE1 %s", scopeChanstring);
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink, cmd);
#else
printf("Set immediate measurement source (MEASU:IMM:SOURCE1): %s\n", cmd);
#endif
 
sprintf(cmd, "MEASU:IMM:TYP %s", measType[scopeMeasSel]);
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink, cmd);
#else
printf("Set immediate measurement type (MEASU:IMM:TYP): %s\n", cmd);
#endif
}
 
return 0;
}
}
// ---------------------------------------------------------------
 
// Send a custom command to the scope ----------------------------
int daqscope::customCommand(char *command, bool query, char *sReturn)
{
if(query)
{
char buf[WAVE_LEN];
memset(buf, 0, WAVE_LEN);
vxi11_send(clink, command);
int bytes_returned = vxi11_receive(clink, buf, WAVE_LEN);
if (bytes_returned > 0)
{
printf("%s\n", buf);
sprintf(sReturn, "%s", buf);
 
// For testing purposes
/* if( strcmp(command, "CURVE?") == 0 )
{
FILE *fp;
char tst[2];
fp = fopen("./curve_return.txt","w");
for(int i = 6; i < bytes_returned; i++)
{
if(i%2 == 1)
{
tst[0] = buf[i];
tst[1] = buf[i-1];
fprintf(fp, "bytes returned = %d\tbyte %d = %d\treturn = %s\n", bytes_returned, i, buf[i], tst);
}
else
fprintf(fp, "bytes returned = %d\tbyte %d = %d\n", bytes_returned, i, buf[i]);
}
fclose(fp);
}*/
}
else if (bytes_returned == -15)
{
printf("*** [ NOTHING RECEIVED ] ***\n");
sprintf(sReturn, "*** [ NOTHING RECEIVED ] ***");
}
}
else
{
vxi11_command(clink, command);
sprintf(sReturn, "*** [ COMMAND NOT QUERY - NO RETURN ] ***");
}
 
return 0;
}
// ---------------------------------------------------------------
 
// Get a measuring event (either waveform or measure) ------------
int daqscope::lockunlock(bool lockit)
{
// Lock the scope front panel for measurements
if(lockit)
{
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink,(char*)"LOCK ALL");
return 0;
#else
// printf("Locking the front panel (LOCK ALL).\n");
return -1;
#endif
}
// Unlock the scope front panel after measurements
else
{
#if WORKSTAT == 'I' || WORKSTAT == 'S'
vxi11_command(clink,(char*)"LOCK NONE");
return 0;
#else
// printf("Unlocking the front panel (LOCK ALL).\n");
return -1;
#endif
}
}
// ---------------------------------------------------------------
 
// Get a measuring event (either waveform or measure) ------------
int daqscope::event()
{
int bytes_returned;
 
if(scopeUseType == 0)
return -1;
else if(scopeUseType == 1)
{
#if WORKSTAT == 'I' || WORKSTAT == 'S'
memset(eventbuf, 0, WAVE_LEN);
vxi11_send(clink, "CURVE?");
bytes_returned = vxi11_receive(clink, eventbuf, WAVE_LEN);
#else
printf("Ask to return the waveform (CURVE?)\n");
bytes_returned = 0;
#endif
 
if(bytes_returned > 0) return 0;
else return -1;
}
else if(scopeUseType == 2)
{
#if WORKSTAT == 'I' || WORKSTAT == 'S'
char buf[WAVE_LEN];
memset(buf, 0, WAVE_LEN);
vxi11_send(clink, "MEASU:IMMED:VALUE?");
bytes_returned = vxi11_receive(clink, buf, WAVE_LEN);
measubuf = (double)atof(buf);
#else
// printf("Ask to return the measurement (MEASU:IMMED:VALUE?)\n");
bytes_returned = 0;
measubuf = (double)rand()/(double)RAND_MAX;
#endif
 
if(bytes_returned > 0) return 0;
else return -1;
}
else
return -1;
}
// ---------------------------------------------------------------
 
// daqscope class constructor and destructor ---------------------
daqscope::daqscope() {
fStop=0;
}
 
daqscope::~daqscope() {
disconnect(savedIP);
}
// ---------------------------------------------------------------
/lab/sipmscan/trunk/input/daqusb.C.offline
0,0 → 1,258
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <time.h>
//#include "../include/wusbxx_dll.h" /* the header of the shared library */
#include "../include/daq.h"
 
//#define DEBUG /* vkljuci dodatni izpis */
#ifdef DEBUG
#define DBG(X) X
#define DBGFUNI(X) printf(">>> %s -> %d\n",#X,(X))
#else
#define DBG(X)
#define DBGFUNI(X) X
#endif
 
/* definiram lokacije enot*/
//#define NTDC 1 /* TDC */
//#define NTDCCH 8
//#define NADC 2 /* ADC */
//#define NADCCH 8
int ctrlc=0;
char *ccserial=(char*)"CC0126";
int devDetect; // variable to tell if we detect any devices
 
int daq::connect(){
// odpri daq
/* xxusb_device_type devices[100];
//struct usb_device *dev;
devDetect = xxusb_devices_find(devices);
// printf("Detected devices: %d\n", devDetect);
//dev = devices[0].usbdev;
//udev = xxusb_device_open(dev);
 
if(devDetect > 0)
{
WUSBXX_load(NULL);
WUSBXX_open(ccserial);
printf("daq::connect()\n");
}
else
*/ printf("daq::connect() - No devices were detected!\n");
return 0;
}
 
int daq::init(int chan = 0){
 
// int i;
// long k;
 
/* DBGFUNI(xxusb_register_write(udev,1,0x0)); // Stop DAQ mode
while (xxusb_usbfifo_read(udev, (int*) stackdump,BUFF_L,100)>0);
CCCZ;
CCCC;
CREM_I;
 
NTDC = 1;
NADC = 2;
if(chan != 0)
{
NTDCCH = chan/2;
NADCCH = chan/2;
}
else
{
NTDCCH = 1;
NADCCH = 1;
}
printf("after: NTDCCH = %d, NADCCH = %d\n", NTDCCH, NADCCH);
 
// create command stack for the TDC and ADC
k=1;
for(i=0;(i<NTDCCH)&&(i<NADCCH);i++) { stackwrite[k++]=NAF(NTDC,i,0); stackwrite[k++]=NAF(NADC,i,0); }
// for(i=0;i<NADCCH;i++) stackwrite[k++]=NAF(NADC,i,0);
stackwrite[k++]=NAF(NTDC,0,9);
stackwrite[k++]=NAF(NADC,0,9);
stackwrite[k++]=NAFS(0,0,16); // insert next word to data
stackwrite[k++]=0xfafb; // event termination word
stackwrite[0]=k-1;
// upload stack #2
xxusb_stack_write(udev,0x2,(long int *)stackwrite);
xxusb_stack_read(udev,0x2,(long int *) stackdata);
DBG(for(i=0;i<k;i++) printf("0x%04x\n",stackdata[i]);)
 
int ret[10];
CAMAC_LED_settings(udev, 1,1,0,0);
ret[0] = CAMAC_register_read(udev,0,&k);
printf("Firmware ID (return %d) -> 0x%08lX\n",ret[0],k); // GKM: Firmware ID (i.e. 0x72000001 = 0111 0010 0000 0000 0000 0000 0000 0001)
ret[1] = CAMAC_register_read(udev,1,&k);
printf("Global Mode (return %d) -> 0x%08lX\n",ret[1],k);
k=(k&0xF000)|0x0005; // set buffer length: n=0..6 -> 0x10000 >> n, n=7 -> single event
ret[0] = CAMAC_register_write(udev,1,k); // GKM: sets the buffer length (i.e. k=5 -> buf length=128 words)
ret[1] = CAMAC_register_write(udev,2,0x80); // wait 0x80 us after trigger // GKM: delay settings in microseconds
ret[2] = CAMAC_register_write(udev,3,0x0); // Scaler Readout Control Register // GKM: scaler readout settings - sets the frequency of readout (if 0, it is disabled)
ret[3] = CAMAC_register_write(udev,9,0x0); // Lam Mask Register // GKM: When 0, readout is triggered by the signal on NIM input
ret[4] = CAMAC_register_write(udev,14,0x0); // USB Bulk Transfer Setup Register
 
// CAMAC_DGG(udev,1,2,3,0,200,0,0);
// CAMAC_DGG(udev,0,0,0,0,100,0,0);
ret[5] = CAMAC_register_write(udev,5,(0x06<<16)+(0x04<<8)+0x00); // output // GKM: NIM outputs (i.e. 0x060400 = 00 0110 0000 0100 0000 0000 -> NIM O2=DGG_B, NIM O3=DGG_A)
ret[6] = CAMAC_register_write(udev,6,(0x01<<24)+(0x01<<16)+(0x0<<8)+0x0); // SCLR & DGG // GKM: device source selector (i.e. 0x01010000 = 00 0000 0001 0000 0001 0000 0000 0000 0000 -> DGG_A=NIM I1, DGG_B=NIM I1, SCLR=disabled)
ret[7] = CAMAC_register_write(udev,7,(100<<16)+0); // output // GKM: Delay and Gate Generator A registers (i.e. 0x00640000 = 0000 0000 0110 0100 0000 0000 0000 0000 -> DDG_A [gate=100, delay=0])
ret[8] = CAMAC_register_write(udev,8,(10000<<16)+0); // output // GKM: Delay and Gate Generator B registers (i.e. 0x27100000 = 0010 0111 0001 0000 0000 0000 0000 0000 -> DDG_B [gate=10000, delay=0])
ret[9] = CAMAC_register_write(udev,13,0); // output // GKM: Extended (course) delay (i.e. 0x00000000 = 0 -> DDG_A ext=0, DDG_B ext=0)
 
// for(i = 0; i < 10; i++) printf("Setting %d? -> return = %d\n",i,ret[i]);
 
// ret[0] = CAMAC_register_read(udev,1,&k);
// printf("k (return %d) -> 0x%08lX\n",ret[0],k);
*/ printf("daq::init()\n");
return 0;
}
 
int daq::start(){
// xxusb_register_write(udev,1,0x1); // Start DAQ mode
printf("daq::start()\n");
return 0;
}
 
int daq::stop(){
// xxusb_register_write(udev,1,0x0); // Stop DAQ mode
// while (xxusb_usbfifo_read(udev,(int *)stackdump,BUFF_L,30)>0);
printf("daq::stop()\n");
return 0;
}
 
int daq::event(unsigned int *data, int maxn){
// int ib,count;
int count;
/* int events,evsize;
short ret;
 
ib=0;
ret=xxusb_usbfifo_read(udev,(int *) stackdata,BUFF_L,500);
events=stackdata[ib++];
DBG(printf("ret=%d,events=0x%08x\n",ret,events);)
if ((ret<0)||(ret!=(((NTDCCH+NADCCH)*4+4)*events+4))) return 0;
 
count=0;
while (ib<(ret/2-1)){
evsize = stackdata[ib++]&0xffff;
DBG(printf("Event:%d EvSize:%d\n", events, evsize);)
for (int i=0;i<(NTDCCH+NADCCH);i++,ib++) data[count++] =stackdata[ib++]&0xffff;
if (stackdata[ib++]!=0xfafb){
printf("Error!\n");,
return 0;
}
events--;
if (fStop) return 0;
}
if (stackdata[ib++]!=0xffff){
printf("Error!\n");
return 0;
}
*/
count = 1;
return count;
}
int daq::disconnect(){
// zapri daq
// WUSBXX_close();
printf("daq::disconnect()\n");
return 0;
}
 
daq::daq(){
fStop=0;
connect();
// if(devDetect > 0)
// init();
}
 
daq::~daq(){
disconnect();
}
 
#ifdef MAIN
void CatchSig (int signumber)
{
ctrlc = 1;
}
 
 
int main (int argc, char **argv){
int neve=1000000;
char *fname="test.dat";
if (argc==1) {
printf("Uporaba: %s stevilo_dogodkov ime_datoteke\n",argv[0]);
printf("Meritev prekini s Ctrl-C, ce je nabranih dogodkov ze dovolj\n");
exit(0);
}
if (argc>1) neve = atoi(argv[1]);
if (argc>2) fname = argv[2];
// intercept routine
if (signal (SIGINT, CatchSig) == SIG_E,RR) perror ("sigignore");
#define BSIZE 10000
int i,ieve,nc,nb;
// int hdr[4]={1,(NTDCCH+4)*sizeof(int)}; // hdr[0]=1, hdr[1]=(NTDCCH+4)*4
int hdr[4]={1,(NTDCCH+NADCCH+4)*sizeof(int)};
unsigned short adc;
unsigned int data[BSIZE];
daq *d= new daq();,
time_t time_check;,
 
// odpremo datoteko za pisanje
FILE *fp=fopen(fname,"w");
 
d->start();
ieve=0;
while((ieve<neve)&&(!ctrlc)){
nc=d->event(data,BSIZE);
nb=0;
while((nc>0)&&(ieve++<neve)&&(!ctrlc)){
// zapis v datoteko
hdr[2]=time(NULL);
hdr[3]=ieve;
fwrite(hdr,sizeof(int),4 ,fp);
fwrite(&data[nb],sizeof(int),(NTDCCH+NADCCH),fp);
// DBG(
for(i=0;i<(NTDCCH+NADCCH);i++){
adc=data[nb+i]&0xFFFF;
if(i % 2 == 0)
printf(/*"nev=%4d %d. TDC data=%d\n"*/"%d\t"/*,ieve,i*//*/2*/,adc);
// printf("nev=%4d %d. TDC data=%d\n",ieve,i/2,adc);
else if(i % 2 == 1)
printf(/*"nev=%4d %d. TDC data=%d\n"*/"%d\t"/*,ieve,i*//*/2*/,adc);
// printf("nev=%4d %d. ADC data=%d\n",ieve,i/2,adc);
}
printf("\n");
// )
nb+=(NTDCCH+NADCCH);
nc-=(NTDCCH+NADCCH);
if (!(ieve%1000)) printf("event no. -> %d\n",ieve);
};
};
d->stop();
fclose(fp);
printf("Podatki so v datoteki %s\n", fname);
delete d;
 
return 0;
}
#endif
/lab/sipmscan/trunk/input/daqusb.C.online
0,0 → 1,257
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <time.h>
#include "../include/wusbxx_dll.h" /* the header of the shared library */
#include "../include/daq.h"
 
//#define DEBUG /* vkljuci dodatni izpis */
#ifdef DEBUG
#define DBG(X) X
#define DBGFUNI(X) printf(">>> %s -> %d\n",#X,(X))
#else
#define DBG(X)
#define DBGFUNI(X) X
#endif
 
/* definiram lokacije enot*/
//#define NTDC 1 /* TDC */
//#define NTDCCH 8
//#define NADC 2 /* ADC */
//#define NADCCH 8
int ctrlc=0;
char *ccserial=(char*)"CC0126";
//int devDetect; // variable to tell if we detect any devices
 
int daq::connect(){
// odpri daq
xxusb_device_type devices[100];
//struct usb_device *dev;
devDetect = xxusb_devices_find(devices);
// printf("Detected devices: %d\n", devDetect);
//dev = devices[0].usbdev;
//udev = xxusb_device_open(dev);
 
if(devDetect > 0)
{
WUSBXX_load(NULL);
WUSBXX_open(ccserial);
printf("daq::connect()\n");
}
else
printf("daq::connect() - No devices were detected!\n");
return 0;
}
 
int daq::init(int chan = 0){
 
int i;
long k;
 
DBGFUNI(xxusb_register_write(udev,1,0x0)); // Stop DAQ mode
while (xxusb_usbfifo_read(udev, (int*) stackdump,BUFF_L,100)>0);
CCCZ;
CCCC;
CREM_I;
 
NTDC = 1;
NADC = 2;
if(chan != 0)
{
NTDCCH = chan/2;
NADCCH = chan/2;
}
else
{
NTDCCH = 1;
NADCCH = 1;
}
printf("after: NTDCCH = %d, NADCCH = %d\n", NTDCCH, NADCCH);
 
// create command stack for the TDC and ADC
k=1;
for(i=0;(i<NTDCCH)&&(i<NADCCH);i++) { stackwrite[k++]=NAF(NTDC,i,0); stackwrite[k++]=NAF(NADC,i,0); }
// for(i=0;i<NADCCH;i++) stackwrite[k++]=NAF(NADC,i,0);
stackwrite[k++]=NAF(NTDC,0,9);
stackwrite[k++]=NAF(NADC,0,9);
stackwrite[k++]=NAFS(0,0,16); // insert next word to data
stackwrite[k++]=0xfafb; // event termination word
stackwrite[0]=k-1;
// upload stack #2
xxusb_stack_write(udev,0x2,(long int *)stackwrite);
xxusb_stack_read(udev,0x2,(long int *) stackdata);
DBG(for(i=0;i<k;i++) printf("0x%04x\n",stackdata[i]);)
 
int ret[10];
CAMAC_LED_settings(udev, 1,1,0,0);
ret[0] = CAMAC_register_read(udev,0,&k);
printf("Firmware ID (return %d) -> 0x%08lX\n",ret[0],k); // GKM: Firmware ID (i.e. 0x72000001 = 0111 0010 0000 0000 0000 0000 0000 0001)
ret[1] = CAMAC_register_read(udev,1,&k);
printf("Global Mode (return %d) -> 0x%08lX\n",ret[1],k);
k=(k&0xF000)|0x0005; // set buffer length: n=0..6 -> 0x10000 >> n, n=7 -> single event
ret[0] = CAMAC_register_write(udev,1,k); // GKM: sets the buffer length (i.e. k=5 -> buf length=128 words)
ret[1] = CAMAC_register_write(udev,2,0x80); // wait 0x80 us after trigger // GKM: delay settings in microseconds
ret[2] = CAMAC_register_write(udev,3,0x0); // Scaler Readout Control Register // GKM: scaler readout settings - sets the frequency of readout (if 0, it is disabled)
ret[3] = CAMAC_register_write(udev,9,0x0); // Lam Mask Register // GKM: When 0, readout is triggered by the signal on NIM input
ret[4] = CAMAC_register_write(udev,14,0x0); // USB Bulk Transfer Setup Register
 
// CAMAC_DGG(udev,1,2,3,0,200,0,0);
// CAMAC_DGG(udev,0,0,0,0,100,0,0);
ret[5] = CAMAC_register_write(udev,5,(0x06<<16)+(0x04<<8)+0x00); // output // GKM: NIM outputs (i.e. 0x060400 = 00 0110 0000 0100 0000 0000 -> NIM O2=DGG_B, NIM O3=DGG_A)
ret[6] = CAMAC_register_write(udev,6,(0x01<<24)+(0x01<<16)+(0x0<<8)+0x0); // SCLR & DGG // GKM: device source selector (i.e. 0x01010000 = 00 0000 0001 0000 0001 0000 0000 0000 0000 -> DGG_A=NIM I1, DGG_B=NIM I1, SCLR=disabled)
ret[7] = CAMAC_register_write(udev,7,(100<<16)+0); // output // GKM: Delay and Gate Generator A registers (i.e. 0x00640000 = 0000 0000 0110 0100 0000 0000 0000 0000 -> DDG_A [gate=100, delay=0])
ret[8] = CAMAC_register_write(udev,8,(10000<<16)+0); // output // GKM: Delay and Gate Generator B registers (i.e. 0x27100000 = 0010 0111 0001 0000 0000 0000 0000 0000 -> DDG_B [gate=10000, delay=0])
ret[9] = CAMAC_register_write(udev,13,0); // output // GKM: Extended (course) delay (i.e. 0x00000000 = 0 -> DDG_A ext=0, DDG_B ext=0)
 
// for(i = 0; i < 10; i++) printf("Setting %d? -> return = %d\n",i,ret[i]);
 
// ret[0] = CAMAC_register_read(udev,1,&k);
// printf("k (return %d) -> 0x%08lX\n",ret[0],k);
printf("daq::init()\n");
return 0;
}
 
int daq::start(){
xxusb_register_write(udev,1,0x1); // Start DAQ mode
printf("daq::start()\n");
return 0;
}
 
int daq::stop(){
xxusb_register_write(udev,1,0x0); // Stop DAQ mode
while (xxusb_usbfifo_read(udev,(int *)stackdump,BUFF_L,30)>0);
printf("daq::stop()\n");
return 0;
}
 
int daq::event(unsigned int *data, int maxn){
int ib,count;
int events,evsize;
short ret;
 
ib=0;
ret=xxusb_usbfifo_read(udev,(int *) stackdata,BUFF_L,500);
events=stackdata[ib++];
DBG(printf("ret=%d,events=0x%08x\n",ret,events);)
if ((ret<0)||(ret!=(((NTDCCH+NADCCH)*4+4)*events+4))) return 0;
 
count=0;
while (ib<(ret/2-1)){
evsize = stackdata[ib++]&0xffff;
DBG(printf("Event:%d EvSize:%d\n", events, evsize);)
for (int i=0;i<(NTDCCH+NADCCH);i++,ib++) data[count++] =stackdata[ib++]&0xffff;
if (stackdata[ib++]!=0xfafb){
printf("Error!\n");
return 0;
}
events--;
if (fStop) return 0;
}
if (stackdata[ib++]!=0xffff){
printf("Error!\n");
return 0;
}
 
// count = 1;
return count;
}
int daq::disconnect(){
// zapri daq
WUSBXX_close();
printf("daq::disconnect()\n");
return 0;
}
 
daq::daq(){
fStop=0;
connect();
// if(devDetect > 0)
// init();
}
 
daq::~daq(){
disconnect();
}
 
#ifdef MAIN
void CatchSig (int signumber)
{
ctrlc = 1;
}
 
 
int main (int argc, char **argv){
int neve=1000000;
char *fname="test.dat";
if (argc==1) {
printf("Uporaba: %s stevilo_dogodkov ime_datoteke\n",argv[0]);
printf("Meritev prekini s Ctrl-C, ce je nabranih dogodkov ze dovolj\n");
exit(0);
}
if (argc>1) neve = atoi(argv[1]);
if (argc>2) fname = argv[2];
// intercept routine
if (signal (SIGINT, CatchSig) == SIG_ERR) perror ("sigignore");
#define BSIZE 10000
int i,ieve,nc,nb;
// int hdr[4]={1,(NTDCCH+4)*sizeof(int)}; // hdr[0]=1, hdr[1]=(NTDCCH+4)*4
int hdr[4]={1,(NTDCCH+NADCCH+4)*sizeof(int)};
unsigned short adc;
unsigned int data[BSIZE];
daq *d= new daq();
time_t time_check;
 
// odpremo datoteko za pisanje
FILE *fp=fopen(fname,"w");
 
d->start();
ieve=0;
while((ieve<neve)&&(!ctrlc)){
nc=d->event(data,BSIZE);
nb=0;
while((nc>0)&&(ieve++<neve)&&(!ctrlc)){
// zapis v datoteko
hdr[2]=time(NULL);
hdr[3]=ieve;
fwrite(hdr,sizeof(int),4 ,fp);
fwrite(&data[nb],sizeof(int),(NTDCCH+NADCCH),fp);
// DBG(
for(i=0;i<(NTDCCH+NADCCH);i++){
adc=data[nb+i]&0xFFFF;
if(i % 2 == 0)
printf(/*"nev=%4d %d. TDC data=%d\n"*/"%d\t"/*,ieve,i*//*/2*/,adc);
// printf("nev=%4d %d. TDC data=%d\n",ieve,i/2,adc);
else if(i % 2 == 1)
printf(/*"nev=%4d %d. TDC data=%d\n"*/"%d\t"/*,ieve,i*//*/2*/,adc);
// printf("nev=%4d %d. ADC data=%d\n",ieve,i/2,adc);
}
printf("\n");
// )
nb+=(NTDCCH+NADCCH);
nc-=(NTDCCH+NADCCH);
if (!(ieve%1000)) printf("event no. -> %d\n",ieve);
};
};
d->stop();
fclose(fp);
printf("Podatki so v datoteki %s\n", fname);
delete d;
 
return 0;
}
#endif
/lab/sipmscan/trunk/input/libxxusb.h.offline
0,0 → 1,111
#include "usb.h"
 
 
#define XXUSB_WIENER_VENDOR_ID 0x16DC /* Wiener, Plein & Baus */
#define XXUSB_VMUSB_PRODUCT_ID 0x000B /* VM-USB */
#define XXUSB_CCUSB_PRODUCT_ID 0x0001 /* CC-USB */
#define XXUSB_ENDPOINT_OUT 2 /* Endpoint 2 Out*/
#define XXUSB_ENDPOINT_IN 0x86 /* Endpoint 6 In */
#define XXUSB_FIRMWARE_REGISTER 0
#define XXUSB_GLOBAL_REGISTER 1
#define XXUSB_ACTION_REGISTER 10
#define XXUSB_DELAYS_REGISTER 2
#define XXUSB_WATCHDOG_REGISTER 3
#define XXUSB_SELLEDA_REGISTER 6
#define XXUSB_SELNIM_REGISTER 7
#define XXUSB_SELLEDB_REGISTER 4
#define XXUSB_SERIAL_REGISTER 15
#define XXUSB_LAMMASK_REGISTER 8
#define XXUSB_LAM_REGISTER 12
#define XXUSB_READOUT_STACK 2
#define XXUSB_SCALER_STACK 3
#define XXUSB_NAF_DIRECT 12
 
struct XXUSB_STACK
{
long Data;
short Hit;
short APatt;
short Num;
short HitMask;
};
 
struct XXUSB_CC_COMMAND_TYPE
{
short Crate;
short F;
short A;
short N;
long Data;
short NoS2;
short LongD;
short HitPatt;
short QStop;
short LAMMode;
short UseHit;
short Repeat;
short AddrScan;
short FastCam;
short NumMod;
short AddrPatt;
long HitMask[4];
long Num;
};
 
struct xxusb_device_typ
{
struct usb_device *usbdev;
char SerialString[7];
};
 
typedef struct xxusb_device_typ xxusb_device_type;
typedef unsigned char UCHAR;
typedef struct usb_bus usb_busx;
 
 
int xxusb_longstack_execute(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_bulk_read(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_bulk_write(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_usbfifo_read(usb_dev_handle *hDev, int *DataBuffer, int lDataLen, int timeout);
 
short xxusb_register_read(usb_dev_handle *hDev, short RegAddr, long *RegData);
short xxusb_stack_read(usb_dev_handle *hDev, short StackAddr, long *StackData);
short xxusb_stack_write(usb_dev_handle *hDev, short StackAddr, long *StackData);
short xxusb_stack_execute(usb_dev_handle *hDev, long *StackData);
short xxusb_register_write(usb_dev_handle *hDev, short RegAddr, long RegData);
short xxusb_reset_toggle(usb_dev_handle *hDev);
 
short xxusb_devices_find(xxusb_device_type *xxusbDev);
short xxusb_device_close(usb_dev_handle *hDev);
usb_dev_handle* xxusb_device_open(struct usb_device *dev);
short xxusb_flash_program(usb_dev_handle *hDev, char *config, short nsect);
short xxusb_flashblock_program(usb_dev_handle *hDev, UCHAR *config);
usb_dev_handle* xxusb_serial_open(char *SerialString);
 
short VME_register_write(usb_dev_handle *hdev, long VME_Address, long Data);
short VME_register_read(usb_dev_handle *hdev, long VME_Address, long *Data);
short VME_LED_settings(usb_dev_handle *hdev, int LED, int code, int invert, int latch);
short VME_DGG(usb_dev_handle *hdev, unsigned short channel, unsigned short trigger,unsigned short output, long delay, unsigned short gate, unsigned short invert, unsigned short latch);
 
short VME_Output_settings(usb_dev_handle *hdev, int Channel, int code, int invert, int latch);
 
short VME_read_16(usb_dev_handle *hdev,short Address_Modifier, long VME_Address, long *Data);
short VME_read_32(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long *Data);
short VME_BLT_read_32(usb_dev_handle *hdev, short Address_Modifier, int count, long VME_Address, long Data[]);
short VME_write_16(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long Data);
short VME_write_32(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long Data);
 
short CAMAC_DGG(usb_dev_handle *hdev, short channel, short trigger, short output, int delay, int gate, short invert, short latch);
short CAMAC_register_read(usb_dev_handle *hdev, int A, long *Data);
short CAMAC_register_write(usb_dev_handle *hdev, int A, long Data);
short CAMAC_LED_settings(usb_dev_handle *hdev, int LED, int code, int invert, int latch);
short CAMAC_Output_settings(usb_dev_handle *hdev, int Channel, int code, int invert, int latch);
short CAMAC_read_LAM_mask(usb_dev_handle *hdev, long *Data);
short CAMAC_write_LAM_mask(usb_dev_handle *hdev, long Data);
 
short CAMAC_write(usb_dev_handle *hdev, int N, int A, int F, long Data, int *Q, int *X);
short CAMAC_read(usb_dev_handle *hdev, int N, int A, int F, long *Data, int *Q, int *X);
short CAMAC_Z(usb_dev_handle *hdev);
short CAMAC_C(usb_dev_handle *hdev);
short CAMAC_I(usb_dev_handle *hdev, int inhibit);
 
/lab/sipmscan/trunk/input/libxxusb.h.online
0,0 → 1,111
#include <usb.h>
 
 
#define XXUSB_WIENER_VENDOR_ID 0x16DC /* Wiener, Plein & Baus */
#define XXUSB_VMUSB_PRODUCT_ID 0x000B /* VM-USB */
#define XXUSB_CCUSB_PRODUCT_ID 0x0001 /* CC-USB */
#define XXUSB_ENDPOINT_OUT 2 /* Endpoint 2 Out*/
#define XXUSB_ENDPOINT_IN 0x86 /* Endpoint 6 In */
#define XXUSB_FIRMWARE_REGISTER 0
#define XXUSB_GLOBAL_REGISTER 1
#define XXUSB_ACTION_REGISTER 10
#define XXUSB_DELAYS_REGISTER 2
#define XXUSB_WATCHDOG_REGISTER 3
#define XXUSB_SELLEDA_REGISTER 6
#define XXUSB_SELNIM_REGISTER 7
#define XXUSB_SELLEDB_REGISTER 4
#define XXUSB_SERIAL_REGISTER 15
#define XXUSB_LAMMASK_REGISTER 8
#define XXUSB_LAM_REGISTER 12
#define XXUSB_READOUT_STACK 2
#define XXUSB_SCALER_STACK 3
#define XXUSB_NAF_DIRECT 12
 
struct XXUSB_STACK
{
long Data;
short Hit;
short APatt;
short Num;
short HitMask;
};
 
struct XXUSB_CC_COMMAND_TYPE
{
short Crate;
short F;
short A;
short N;
long Data;
short NoS2;
short LongD;
short HitPatt;
short QStop;
short LAMMode;
short UseHit;
short Repeat;
short AddrScan;
short FastCam;
short NumMod;
short AddrPatt;
long HitMask[4];
long Num;
};
 
struct xxusb_device_typ
{
struct usb_device *usbdev;
char SerialString[7];
};
 
typedef struct xxusb_device_typ xxusb_device_type;
typedef unsigned char UCHAR;
typedef struct usb_bus usb_busx;
 
 
int xxusb_longstack_execute(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_bulk_read(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_bulk_write(usb_dev_handle *hDev, void *DataBuffer, int lDataLen, int timeout);
int xxusb_usbfifo_read(usb_dev_handle *hDev, int *DataBuffer, int lDataLen, int timeout);
 
short xxusb_register_read(usb_dev_handle *hDev, short RegAddr, long *RegData);
short xxusb_stack_read(usb_dev_handle *hDev, short StackAddr, long *StackData);
short xxusb_stack_write(usb_dev_handle *hDev, short StackAddr, long *StackData);
short xxusb_stack_execute(usb_dev_handle *hDev, long *StackData);
short xxusb_register_write(usb_dev_handle *hDev, short RegAddr, long RegData);
short xxusb_reset_toggle(usb_dev_handle *hDev);
 
short xxusb_devices_find(xxusb_device_type *xxusbDev);
short xxusb_device_close(usb_dev_handle *hDev);
usb_dev_handle* xxusb_device_open(struct usb_device *dev);
short xxusb_flash_program(usb_dev_handle *hDev, char *config, short nsect);
short xxusb_flashblock_program(usb_dev_handle *hDev, UCHAR *config);
usb_dev_handle* xxusb_serial_open(char *SerialString);
 
short VME_register_write(usb_dev_handle *hdev, long VME_Address, long Data);
short VME_register_read(usb_dev_handle *hdev, long VME_Address, long *Data);
short VME_LED_settings(usb_dev_handle *hdev, int LED, int code, int invert, int latch);
short VME_DGG(usb_dev_handle *hdev, unsigned short channel, unsigned short trigger,unsigned short output, long delay, unsigned short gate, unsigned short invert, unsigned short latch);
 
short VME_Output_settings(usb_dev_handle *hdev, int Channel, int code, int invert, int latch);
 
short VME_read_16(usb_dev_handle *hdev,short Address_Modifier, long VME_Address, long *Data);
short VME_read_32(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long *Data);
short VME_BLT_read_32(usb_dev_handle *hdev, short Address_Modifier, int count, long VME_Address, long Data[]);
short VME_write_16(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long Data);
short VME_write_32(usb_dev_handle *hdev, short Address_Modifier, long VME_Address, long Data);
 
short CAMAC_DGG(usb_dev_handle *hdev, short channel, short trigger, short output, int delay, int gate, short invert, short latch);
short CAMAC_register_read(usb_dev_handle *hdev, int A, long *Data);
short CAMAC_register_write(usb_dev_handle *hdev, int A, long Data);
short CAMAC_LED_settings(usb_dev_handle *hdev, int LED, int code, int invert, int latch);
short CAMAC_Output_settings(usb_dev_handle *hdev, int Channel, int code, int invert, int latch);
short CAMAC_read_LAM_mask(usb_dev_handle *hdev, long *Data);
short CAMAC_write_LAM_mask(usb_dev_handle *hdev, long Data);
 
short CAMAC_write(usb_dev_handle *hdev, int N, int A, int F, long Data, int *Q, int *X);
short CAMAC_read(usb_dev_handle *hdev, int N, int A, int F, long *Data, int *Q, int *X);
short CAMAC_Z(usb_dev_handle *hdev);
short CAMAC_C(usb_dev_handle *hdev);
short CAMAC_I(usb_dev_handle *hdev, int inhibit);
 
/lab/sipmscan/trunk/input/start.sh.in
0,0 → 1,21
if [ $rootdirectory != -1 ]; then
printenv ROOTSYS > /dev/null
if [ $? != 0 ]; then
echo "Preparing ROOT..."
source $rootdirectory/bin/thisroot.sh
fi
fi
 
if [ $snmpdirectory != -1 ]; then
printenv PATH | grep "snmp" > /dev/null
if [ $? != 0 ]; then
echo "Preparing NET-SNMP..."
export PATH=$snmpdirectory/bin:$PATH
fi
fi
 
if [ ! -d results ]; then
mkdir results
fi
 
./bin/sipmscan
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/lab/sipmscan/trunk/input/usb.h.offline
0,0 → 1,344
/*
* Prototypes, structure definitions and macros.
*
* Copyright (c) 2000-2003 Johannes Erdfelt <johannes@erdfelt.com>
*
* This library is covered by the LGPL, read LICENSE for details.
*
* This file (and only this file) may alternatively be licensed under the
* BSD license as well, read LICENSE for details.
*/
#ifndef __USB_H__
#define __USB_H__
 
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
 
#include <sys/param.h>
#include <dirent.h>
 
/*
* USB spec information
*
* This is all stuff grabbed from various USB specs and is pretty much
* not subject to change
*/
 
/*
* Device and/or Interface Class codes
*/
#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */
#define USB_CLASS_AUDIO 1
#define USB_CLASS_COMM 2
#define USB_CLASS_HID 3
#define USB_CLASS_PRINTER 7
#define USB_CLASS_PTP 6
#define USB_CLASS_MASS_STORAGE 8
#define USB_CLASS_HUB 9
#define USB_CLASS_DATA 10
#define USB_CLASS_VENDOR_SPEC 0xff
 
/*
* Descriptor types
*/
#define USB_DT_DEVICE 0x01
#define USB_DT_CONFIG 0x02
#define USB_DT_STRING 0x03
#define USB_DT_INTERFACE 0x04
#define USB_DT_ENDPOINT 0x05
 
#define USB_DT_HID 0x21
#define USB_DT_REPORT 0x22
#define USB_DT_PHYSICAL 0x23
#define USB_DT_HUB 0x29
 
/*
* Descriptor sizes per descriptor type
*/
#define USB_DT_DEVICE_SIZE 18
#define USB_DT_CONFIG_SIZE 9
#define USB_DT_INTERFACE_SIZE 9
#define USB_DT_ENDPOINT_SIZE 7
#define USB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */
#define USB_DT_HUB_NONVAR_SIZE 7
 
/* All standard descriptors have these 2 fields in common */
struct usb_descriptor_header {
uint8_t bLength;
uint8_t bDescriptorType;
} __attribute__ ((packed));
 
/* String descriptor */
struct usb_string_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wData[1];
} __attribute__ ((packed));
 
/* HID descriptor */
struct usb_hid_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdHID;
uint8_t bCountryCode;
uint8_t bNumDescriptors;
/* uint8_t bReportDescriptorType; */
/* uint16_t wDescriptorLength; */
/* ... */
} __attribute__ ((packed));
 
/* Endpoint descriptor */
#define USB_MAXENDPOINTS 32
struct usb_endpoint_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
uint8_t bRefresh;
uint8_t bSynchAddress;
 
unsigned char *extra; /* Extra descriptors */
int extralen;
};
 
#define USB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */
#define USB_ENDPOINT_DIR_MASK 0x80
 
#define USB_ENDPOINT_TYPE_MASK 0x03 /* in bmAttributes */
#define USB_ENDPOINT_TYPE_CONTROL 0
#define USB_ENDPOINT_TYPE_ISOCHRONOUS 1
#define USB_ENDPOINT_TYPE_BULK 2
#define USB_ENDPOINT_TYPE_INTERRUPT 3
 
/* Interface descriptor */
#define USB_MAXINTERFACES 32
struct usb_interface_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
 
struct usb_endpoint_descriptor *endpoint;
 
unsigned char *extra; /* Extra descriptors */
int extralen;
};
 
#define USB_MAXALTSETTING 128 /* Hard limit */
struct usb_interface {
struct usb_interface_descriptor *altsetting;
 
int num_altsetting;
};
 
/* Configuration descriptor information.. */
#define USB_MAXCONFIG 8
struct usb_config_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t MaxPower;
 
struct usb_interface *interface;
 
unsigned char *extra; /* Extra descriptors */
int extralen;
};
 
/* Device descriptor */
struct usb_device_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} __attribute__ ((packed));
 
struct usb_ctrl_setup {
uint8_t bRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} __attribute__ ((packed));
 
/*
* Standard requests
*/
#define USB_REQ_GET_STATUS 0x00
#define USB_REQ_CLEAR_FEATURE 0x01
/* 0x02 is reserved */
#define USB_REQ_SET_FEATURE 0x03
/* 0x04 is reserved */
#define USB_REQ_SET_ADDRESS 0x05
#define USB_REQ_GET_DESCRIPTOR 0x06
#define USB_REQ_SET_DESCRIPTOR 0x07
#define USB_REQ_GET_CONFIGURATION 0x08
#define USB_REQ_SET_CONFIGURATION 0x09
#define USB_REQ_GET_INTERFACE 0x0A
#define USB_REQ_SET_INTERFACE 0x0B
#define USB_REQ_SYNCH_FRAME 0x0C
 
#define USB_TYPE_STANDARD (0x00 << 5)
#define USB_TYPE_CLASS (0x01 << 5)
#define USB_TYPE_VENDOR (0x02 << 5)
#define USB_TYPE_RESERVED (0x03 << 5)
 
#define USB_RECIP_DEVICE 0x00
#define USB_RECIP_INTERFACE 0x01
#define USB_RECIP_ENDPOINT 0x02
#define USB_RECIP_OTHER 0x03
 
/*
* Various libusb API related stuff
*/
 
#define USB_ENDPOINT_IN 0x80
#define USB_ENDPOINT_OUT 0x00
 
/* Error codes */
#define USB_ERROR_BEGIN 500000
 
/*
* This is supposed to look weird. This file is generated from autoconf
* and I didn't want to make this too complicated.
*/
#if 0
#define USB_LE16_TO_CPU(x) do { x = ((x & 0xff) << 8) | ((x & 0xff00) >> 8); } while(0)
#else
#define USB_LE16_TO_CPU(x)
#endif
 
/* Data types */
struct usb_device;
struct usb_bus;
 
/*
* To maintain compatibility with applications already built with libusb,
* we must only add entries to the end of this structure. NEVER delete or
* move members and only change types if you really know what you're doing.
*/
#ifdef PATH_MAX
#define LIBUSB_PATH_MAX PATH_MAX
#else
#define LIBUSB_PATH_MAX 4096
#endif
struct usb_device {
struct usb_device *next, *prev;
 
char filename[LIBUSB_PATH_MAX + 1];
 
struct usb_bus *bus;
 
struct usb_device_descriptor descriptor;
struct usb_config_descriptor *config;
 
void *dev; /* Darwin support */
 
uint8_t devnum;
 
unsigned char num_children;
struct usb_device **children;
};
 
struct usb_bus {
struct usb_bus *next, *prev;
 
char dirname[LIBUSB_PATH_MAX + 1];
 
struct usb_device *devices;
uint32_t location;
 
struct usb_device *root_dev;
};
 
struct usb_dev_handle;
typedef struct usb_dev_handle usb_dev_handle;
 
/* Variables */
extern struct usb_bus *usb_busses;
 
#ifdef __cplusplus
extern "C" {
#endif
 
/* Function prototypes */
 
/* usb.c */
usb_dev_handle *usb_open(struct usb_device *dev);
int usb_close(usb_dev_handle *dev);
int usb_get_string(usb_dev_handle *dev, int index, int langid, char *buf,
size_t buflen);
int usb_get_string_simple(usb_dev_handle *dev, int index, char *buf,
size_t buflen);
 
/* descriptors.c */
int usb_get_descriptor_by_endpoint(usb_dev_handle *udev, int ep,
unsigned char type, unsigned char index, void *buf, int size);
int usb_get_descriptor(usb_dev_handle *udev, unsigned char type,
unsigned char index, void *buf, int size);
 
/* <arch>.c */
int usb_bulk_write(usb_dev_handle *dev, int ep, const char *bytes, int size,
int timeout);
int usb_bulk_read(usb_dev_handle *dev, int ep, char *bytes, int size,
int timeout);
int usb_interrupt_write(usb_dev_handle *dev, int ep, const char *bytes, int size,
int timeout);
int usb_interrupt_read(usb_dev_handle *dev, int ep, char *bytes, int size,
int timeout);
int usb_control_msg(usb_dev_handle *dev, int requesttype, int request,
int value, int index, char *bytes, int size, int timeout);
int usb_set_configuration(usb_dev_handle *dev, int configuration);
int usb_claim_interface(usb_dev_handle *dev, int interface);
int usb_release_interface(usb_dev_handle *dev, int interface);
int usb_set_altinterface(usb_dev_handle *dev, int alternate);
int usb_resetep(usb_dev_handle *dev, unsigned int ep);
int usb_clear_halt(usb_dev_handle *dev, unsigned int ep);
int usb_reset(usb_dev_handle *dev);
 
#if 1
#define LIBUSB_HAS_GET_DRIVER_NP 1
int usb_get_driver_np(usb_dev_handle *dev, int interface, char *name,
unsigned int namelen);
#define LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP 1
int usb_detach_kernel_driver_np(usb_dev_handle *dev, int interface);
#endif
 
char *usb_strerror(void);
 
void usb_init(void);
void usb_set_debug(int level);
int usb_find_busses(void);
int usb_find_devices(void);
struct usb_device *usb_device(usb_dev_handle *dev);
struct usb_bus *usb_get_busses(void);
 
#ifdef __cplusplus
}
#endif
 
#endif /* __USB_H__ */
 
/lab/sipmscan/trunk/input/workstation.h.in
0,0 → 1,33
#ifndef _workstation_h_
#define _workstation_h_
 
// Debug signal (0 = no debug, 1 = printout debug, 2 = structure + printout debug)
#define DBGSIG 0
 
// Define the working computer (O=offline, S=offline with scope, I=IJS/online) and the base directory
#define WORKSTAT 'N'
 
// Define if working computer is connected to IJS ethernet network (for fieldpoint)
#define IJSNET 1
 
#ifdef WORKSTAT
#define rootdir "path-to-installation"
#endif
 
// Title colors and font
#define FORECOLOR 0xfcfcfc
#define BACKCOLOR 0x2e5a86
#define FONT "-*-helvetica-bold-r-normal-*-13-*-*-*-*-*-iso8859-"
#define HELPFONT "-*-courier-bold-r-normal-*-13-*-*-*-*-*-iso8859-"
 
// Global variables
#define histext ".root"
#define histextall "*.root"
#define tdctimeconversion 45.0909
#define lenconversion 0.3595
#define rotconversion (6.3281/3600.)
#define histname "hdata"
#define singlewait 3
#define doublewait 2
 
#endif
/lab/sipmscan/trunk/layout/default.layout
0,0 → 1,21
# Default layout file:
# - comment lines start with #
# - each frame layout is separated by a comment
# - any blank lines are skipped
# - the splitted subwindows are regarded as follows:
# > when major split is horizontal, start on left side (top to bottom) and move towards right
# > when major split is vertical, start from top (left to right) and move to the bottom
 
# Whole window width and height
1240 800 main
 
# Measurement subwindows width and height
248 480 settings
248 261 display
984 745 mainmeasure
 
# Analysis subwindows width and height
826 480 histfile
826 261 analysis
406 400 histogram
406 341 histctrl
/lab/sipmscan/trunk/layout/selected_layout.txt
0,0 → 1,0
default.layout
/lab/sipmscan/trunk/src/MIKRO/MIKRO.c
0,0 → 1,296
#include "rs232.h"
#include "MIKRO.h"
 
//#define DEBUG
 
#define COMWAIT 0.5
#define COMDELAY 0.1
 
static char MIKRO_Send[100], MIKRO_Receive[100];
static char MIKRO_Device, MIKRO_Axes, MIKRO_Response;
static int MIKRO_Port;
static int nin, nout, rstat;
static int MIKRO_type[100];
 
int MIKRO_Cmd (int node, char *cmd)
{
printf("Command: %1d %s\n",node,cmd);
Delay(COMDELAY);
FlushInQ (MIKRO_Port);
nout = sprintf (MIKRO_Send, "%1d %s\r", node, cmd);
ComWrt (MIKRO_Port, MIKRO_Send, nout);
if ((nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa))==0) {
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
if (nin==2) return (0);
}
return (-1);
}
 
int MIKRO_Set (int node, char cmd[], int val)
{
printf("Command: %1d %s %d\n",node,cmd, val);
Delay(COMDELAY);
FlushInQ (MIKRO_Port);
nout = sprintf (MIKRO_Send, "%1d %s %d\r", node, cmd, val);
ComWrt (MIKRO_Port, MIKRO_Send, nout);
if ((nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa))==0) {
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
if (nin==2) return (0);
}
return (-1);
}
 
int MIKRO_Get (int node, char cmd[], int *val)
{
short int stmp;
 
Delay(COMDELAY);
FlushInQ (MIKRO_Port);
nout = sprintf (MIKRO_Send, "%1d %s\r", node, cmd);
ComWrt (MIKRO_Port, MIKRO_Send, nout);
if ((nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa))==0) {
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
if (nin>0){
// MIKRO_Receive[--nin]=0;
switch (nin) {
case 9:
sscanf (MIKRO_Receive, "%*x %hx",&stmp);
*val=stmp;
return (0);
case 13:
sscanf (MIKRO_Receive, "%*x %x",val);
return (0);
default:
printf("Node %d Com error => bytes rcved=0x%02x buf=%s\n",node,nin,MIKRO_Receive);
break;
}
}
}
return (-1);
}
 
int MIKRO_GetStat (int node)
{
int tmp;
 
Delay(COMDELAY);
FlushInQ (MIKRO_Port);
nout = sprintf (MIKRO_Send, "%1d st\r", node);
ComWrt (MIKRO_Port, MIKRO_Send, nout);
if ((nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa))==0) {
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
// if (nin>0) nin--;
MIKRO_Receive[nin]=0;
if (nin==9) {
tmp=0;
sscanf (MIKRO_Receive, "%*x %hx",(short int *)&tmp);
return (tmp);
}
}
return (-1);
}
 
int _VI_FUNC MIKRO_Open (char * dev)
{
 
MIKRO_Port=OpenComConfig (dev, "", 38400, 0, 8, 1, 512, 512);
// SetXMode (MIKRO_Port, 0);
// SetCTSMode (MIKRO_Port, LWRS_HWHANDSHAKE_OFF);
// SetComTime (MIKRO_Port, COMWAIT);
return 0;
}
 
int _VI_FUNC MIKRO_Init (int node, int type)
{
MIKRO_type[node]=type;
Delay(0.1);
MIKRO_Cmd(node,"ok 1");
MIKRO_Cmd(node,"ab");
switch (type){
case 1: // 3M Linear
MIKRO_Cmd(node,"k 1");
MIKRO_Cmd(node,"ad 200");
MIKRO_Cmd(node,"aa 2");
MIKRO_Cmd(node,"fa 1");
MIKRO_Cmd(node,"fd 3000"); // Set Max Dynamic Following Error (1000)
MIKRO_Cmd(node,"sr 1000");
MIKRO_Cmd(node,"sp 750");
MIKRO_Cmd(node,"ac 100");
MIKRO_Cmd(node,"dc 200");
MIKRO_Cmd(node,"por 28000");
MIKRO_Cmd(node,"i 600");
MIKRO_Cmd(node,"ano 2350");
MIKRO_Cmd(node,"ls 1");
MIKRO_Cmd(node,"hp 1");
MIKRO_Cmd(node,"hf 1");
break;
case 2: // 3M Rotary
MIKRO_Cmd(node,"k 1");
MIKRO_Cmd(node,"ad 200");
MIKRO_Cmd(node,"aa 1");
MIKRO_Cmd(node,"fa 1");
MIKRO_Cmd(node,"fd 3000"); // Set Max Dynamic Following Error (1000)
MIKRO_Cmd(node,"sr 1000");
MIKRO_Cmd(node,"sp 550");
MIKRO_Cmd(node,"ac 100");
MIKRO_Cmd(node,"dc 200");
MIKRO_Cmd(node,"por 28000");
MIKRO_Cmd(node,"i 600");
MIKRO_Cmd(node,"ano 2350");
MIKRO_Cmd(node,"ls 99");
MIKRO_Cmd(node,"hp 1");
MIKRO_Cmd(node,"hf 1");
break;
case 3: // 4M Linear
MIKRO_Cmd(node,"k 1");
MIKRO_Cmd(node,"ad 1000");
MIKRO_Cmd(node,"aa 2");
MIKRO_Cmd(node,"fa 1");
MIKRO_Cmd(node,"fd 3000"); // Set Max Dynamic Following Error (1000)
MIKRO_Cmd(node,"sr 1000");
MIKRO_Cmd(node,"sp 1000");
MIKRO_Cmd(node,"ac 100");
MIKRO_Cmd(node,"dc 200");
MIKRO_Cmd(node,"por 28000");
MIKRO_Cmd(node,"i 600");
MIKRO_Cmd(node,"ano 2600");
MIKRO_Cmd(node,"ls 1");
MIKRO_Cmd(node,"hp 1");
MIKRO_Cmd(node,"hf 1");
break;
case 4: // 4M Rotary
MIKRO_Cmd(node,"k 1");
MIKRO_Cmd(node,"ad 100");
MIKRO_Cmd(node,"aa 1");
MIKRO_Cmd(node,"fa 1");
MIKRO_Cmd(node,"fd 3000"); // Set Max Dynamic Following Error (1000)
MIKRO_Cmd(node,"sp 800");
MIKRO_Cmd(node,"sr 1000");
MIKRO_Cmd(node,"ac 100");
MIKRO_Cmd(node,"dc 200");
MIKRO_Cmd(node,"por 28000");
MIKRO_Cmd(node,"i 600");
MIKRO_Cmd(node,"ano 2600");
MIKRO_Cmd(node,"ls 99");
break;
default:
break;
}
MIKRO_Cmd(node,"rd 0");
MIKRO_Cmd(node,"n 2");
MIKRO_Cmd(node,"en");
if (type != 0){
MIKRO_Cmd(node,"eeboot 1");
MIKRO_Cmd(node,"eepsav 1");
Delay(0.1);
}
return 0;
}
 
int _VI_FUNC MIKRO_Reset (int node)
{
 
MIKRO_Cmd(node,"di"); // disables the node
 
Delay(COMDELAY);
nout = sprintf (MIKRO_Send, "%1d rn\r", node); // resets the node
ComWrt (MIKRO_Port, MIKRO_Send, nout);
 
SetComTime (MIKRO_Port, 20);
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
SetComTime (MIKRO_Port, COMWAIT);
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
// if (nin!=0) nin--;
// MIKRO_Receive[nin]=0;
printf("%s\n",MIKRO_Receive);
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
nin = ComRdTerm (MIKRO_Port, MIKRO_Receive, 30, 0xa);
// if (nin!=0) nin--;
// MIKRO_Receive[nin]=0;
printf("%s\n",MIKRO_Receive);
MIKRO_Init(node,0);
return 0;
}
 
int _VI_FUNC MIKRO_ReferenceMove (int node)
{
int fac=10;
int n2,as;
 
MIKRO_Cmd(node,"ab");
MIKRO_Cmd(node,"en");
MIKRO_Set(node,"ll",-1000000);
MIKRO_Set(node,"ll",1000000);
 
if (!(MIKRO_GetStat(node)&0x8000)){
MIKRO_Set(node,"v", -100*fac);
do {
MIKRO_GetPosition(node,&n2);
MIKRO_Get(node,"as",&as);
printf("Approaching N-limit node=%d pos=%d speed=%d\n",node,n2,as);
} while (MIKRO_GetStat(node)&0x1 );
if (!(MIKRO_GetStat(node)&0x8000)){
printf("N-limit not reached! Trying with half speed.\n");
MIKRO_Set(node,"v", -50*fac);
do {
MIKRO_GetPosition(node,&n2);
MIKRO_Get(node,"as",&as);
printf("Approaching N-limit node=%d pos=%d speed=%d\n",node,n2,as);
} while (MIKRO_GetStat(node)&0x1 );
if (!(MIKRO_GetStat(node)&0x8000)){
printf("N-limit not reached! Aborting ...\n");
MIKRO_Cmd(node,"ab");
return -1;
}
}
}
MIKRO_MoveFor(node,1000);
MIKRO_Set(node,"v", -10*fac);
do {
MIKRO_GetPosition(node,&n2);
MIKRO_Get(node,"as",&as);
printf("Fine tuning 0: node=%d pos=%d speed=%d\n",node,n2, as);
} while (MIKRO_GetStat(node)&0x1);
if (!(MIKRO_GetStat(node)&0x8000)){
printf("N-limit not reached! Aborting ...\n");
MIKRO_Cmd(node,"ab");
return -1;
}
MIKRO_MoveFor(node,1000);
MIKRO_Set(node,"ho",0);
MIKRO_Set(node,"ll",-100);
MIKRO_Set(node,"ll",500100);
return 0;
}
 
int _VI_FUNC MIKRO_MoveFor (int node, int dist)
{
MIKRO_Set(node,"lr", dist);
MIKRO_Cmd(node,"mv");
while (MIKRO_GetStat(node)&1) Delay(0.1);
return 0;
}
 
int _VI_FUNC MIKRO_MoveTo (int node, int dest)
{
// printf("-> MIKRO_MoveTo \n");
MIKRO_Set(node,"la", dest);
MIKRO_Cmd(node,"mv");
while (MIKRO_GetStat(node)&1) Delay(0.1);
return 0;
}
 
int _VI_FUNC MIKRO_GetPosition (int node, int pos[])
{
MIKRO_Get(node,"pos",pos);
return 0;
}
 
void _VI_FUNC MIKRO_Close (void)
{
CloseCom (MIKRO_Port);
}
 
/lab/sipmscan/trunk/src/MIKRO/MIKRO.h
0,0 → 1,21
 
#define _VI_FUNC
int _VI_FUNC MIKRO_Open (char *dev);
 
int _VI_FUNC MIKRO_Reset (int node);
 
int _VI_FUNC MIKRO_Init (int node, int type);
 
int _VI_FUNC MIKRO_ReferenceMove (int node);
 
int _VI_FUNC MIKRO_MoveFor (int node, int dist);
 
int _VI_FUNC MIKRO_MoveTo (int node, int dest);
 
int _VI_FUNC MIKRO_GetPosition (int node, int pos[]);
 
int _VI_FUNC MIKRO_SetZero (char axes);
 
int _VI_FUNC MIKRO_SetPlain (char axes);
 
void _VI_FUNC MIKRO_Close (void);
/lab/sipmscan/trunk/src/MIKRO/Makefile
0,0 → 1,4
mikro_ctrl: mikro_ctrl.c rs232.c rs232.h MIKRO.c
gcc mikro_ctrl.c rs232.c MIKRO.c -o mikro_ctrl -lm
mikro_ctrl_d: mikro_ctrl.c rs232.c rs232.h MIKRO.c
gcc mikro_ctrl.c rs232.c MIKRO.c -o mikro_ctrl_d -lm -DDEBUG
/lab/sipmscan/trunk/src/MIKRO/mikro_ctrl
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/lab/sipmscan/trunk/src/MIKRO/mikro_ctrl.c
0,0 → 1,148
#include <stdlib.h>
#include <stdio.h>
#include "MIKRO.h"
 
 
#include <getopt.h>
 
#define MIKRO_COM "/dev/ttyUSB0"
 
int help(){
fprintf(stderr,"Usage: mikro [-i node][-n node] [-u up] [-d down] [-r node] [-h node] [-a] [-g] [-m pos]\n");
fprintf(stderr," Options:\n");
fprintf(stderr,"[-n node] -i type .. initialize node + save to EEPROM\n");
fprintf(stderr," (1=3MLin,2=3MRot,3=4MLin,4=4MRot,0=skip\n");
fprintf(stderr," -n node -h .. homing procedure for node\n");
fprintf(stderr," -n node -r .. reset node\n");
fprintf(stderr," -n node -u .. move node for +1000\n");
fprintf(stderr," -n node -d .. move node for -1000\n");
fprintf(stderr,"[-n node] -a .. current status of the nodes\n");
fprintf(stderr," -n node -v value -s cmd .. set value of the cmd on the node\n");
fprintf(stderr," -n node -g cmd .. get value of the cmd on the node\n");
fprintf(stderr," -n node -m position .. move node to position\n");
fprintf(stderr," -l delaysec .. loop test with the delay delaysec\n");
return 0;
}
 
int main (int argc, char ** argv){
int i,j,k;
int node=0,opt,value=0,itype=0;
int nr_nodes=3;
int ierr;
int pos,xpos,ypos,zpos;
char custcmd[20];
char statbits[16][10]={"Moving","In-Pos","Mode","AMN Mode","%Done","DNet","DNErr","FD-Error",
"Disable","R-Lim","Local","Estop","Event1","P-Lim","Event2","N-Lim"};
 
MIKRO_Open (MIKRO_COM);
 
// ":" just indicates that this option needs an argument
while ((opt = getopt(argc, argv, "i:av:s:l:udn:c:pm:g:hre")) != -1) {
switch (opt) {
case 'i':
itype = atoi(optarg);
if(node != 0)
MIKRO_Init (node,itype);
else
for(i=1; i<nr_nodes+1; i++) MIKRO_Init (i,itype);
break;
case 'a':
if(node != 0) {
pos=0;
ierr=MIKRO_GetStat(node);
MIKRO_GetPosition (node, &pos);
printf("node %d position %d status =%04x\n",node,pos,ierr);
for(i=0; i<16; i++){
printf("%d: %s\n", (ierr&1),statbits[i]);
ierr>>=1;
}
}else{
pos=0;
for (j=1;j<nr_nodes+1;j++){
ierr=MIKRO_GetStat(j);
MIKRO_GetPosition (j, &pos);
printf("node %d position %d status =%04x\n",j,pos,ierr);
for(i=0; i<16; i++){
printf("%d: %s\n", (ierr&1),statbits[i]);
ierr>>=1;
}
}
}
break;
case 'l':
printf("MIKRO_MoveTo Loop\n");
for (i=0;i<5;i++){
xpos=i*1000+10000;
MIKRO_MoveTo (1, xpos);
for (j=0;j<5;j++){
ypos=j*1000+10000;
MIKRO_MoveTo (2, ypos);
for (k=0;k<50;k++){
zpos=k*1000+10000;
MIKRO_MoveTo (3, zpos);
printf("x=%d y=%d z=%d\n",xpos,ypos,zpos);
Delay(atof(optarg));
}
}
}
break;
case 'n':
node = atoi(optarg);
break;
case 'm':
MIKRO_MoveTo (node, atoi(optarg));
printf("MIKRO_MoveTo node=%d pos=%d \n",node,atoi(optarg));
MIKRO_GetPosition (node, &i);
printf("node %d position %d \n",node,i);
break;
case 'v':
value=atoi(optarg);
break;
case 's':
MIKRO_Set (node,optarg,value);
printf("MIKRO_Set node %d cmd=%s val=%d\n",node,optarg, value);
break;
case 'g':
MIKRO_Get (node,optarg,&i);
printf("MIKRO_Get node %d cmd=%s val=%d\n",node,optarg, i);
break;
case 'h':
printf("MIKRO_ReferenceMove node=%d\n",node);
MIKRO_ReferenceMove (node);
break;
case 'r':
printf("MIKRO_Reset node=%d\n",node);
MIKRO_Reset (node);
break;
case 'u':
MIKRO_Set(node,"lr", 1000);
MIKRO_Cmd(node,"mv");
break;
case 'd':
MIKRO_Set(node,"lr", -1000);
MIKRO_Cmd(node,"mv");
break;
case 'e':
MIKRO_Cmd(node,"ab");
MIKRO_Cmd(node,"n 2");
MIKRO_Cmd(node,"en");
break;
case 'c': // cust. com.
sprintf(custcmd,"%s",optarg);
MIKRO_Cmd(node,custcmd);
break;
case 'p': // get pos.
if(node != 0){
MIKRO_GetPosition (node, &pos);
printf("%d\n",pos);
}
break;
default: // '?'
help();
break;
}
}
if (argc==1) help();
MIKRO_Close ();
return 0;
}
/lab/sipmscan/trunk/src/MIKRO/mikro_ctrl_d
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/lab/sipmscan/trunk/src/MIKRO/quick_scan.sh
0,0 → 1,15
#! /bin/bash
 
#fname=$1
#num_events=$2
 
#./addheader $fname 1 $num_events 0 0 0 0 0 0
#./addheader $fname 3 0 0 0 0 0 0
#./daq $fname $num_events
#./addheader $fname 2
 
position=`./mikro_ctrl -a | grep -o '[[:digit:]]*' | awk -F : '{if(NR==2 || NR==5){print $1}}'`
#pos_x=${position}[0]
#pos_y=${position}[1]
#echo "position x = " $pos_x " position y = " $pos_y
echo $position >> test.txt
/lab/sipmscan/trunk/src/MIKRO/rs232.c
0,0 → 1,125
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
 
#include "rs232.h"
//#define DEBUG
 
const int debug=0;
 
struct termios tattr;
 
int Delay(double sec){
return usleep((int) (sec*1e6) );
}
 
int SetComTime(int fd, double timeout_seconds){
 
int ntenth;
 
ntenth = (int)(timeout_seconds*10);
tattr.c_cc[VTIME] = ntenth;
tcsetattr(fd, TCSANOW, &tattr);
#ifdef DEBUG
printf("SetComTime: %d\n", ntenth);
#endif
return 0;
}
 
int FlushInQ(int fd){
return 0;
}
 
int FlushOutQ(int fd){
return 0;
}
 
int ComWrt (int fd, char* cmd, int Count ){
int nwr;
 
nwr=write(fd, cmd, Count);
#ifdef DEBUG
printf ( "ComWrt: %d, %d, %s\n", Count, nwr, cmd);
#endif
return nwr;
}
 
int ComRdTerm (int fd, char *response, int nb, int termchar)
{
 
int nread, nloop;
 
nread=0;
nloop=0;
 
#ifdef DEBUG
printf ( "ComRdTerm start\n") ;
#endif
// rewind(fpr);
while (1) {
if (nloop++ == nb) return -1;
// nread += read ( fd, response+nread, nb-nread );
nread += read ( fd, response+nread, 1 );
#ifdef DEBUG
response[nread]=0;
printf ("ComRdTerm nread: %d %d %s\n", nloop, nread, response) ;
#endif
if (nread>1) if(response[nread-1] == termchar) break;
}
 
nread = nread - 2;
response[nread]=0;
#ifdef DEBUG
printf("CmdRdTerm: %s\n",response);
#endif
return nread;
}
 
int OpenComConfig( char *dev, char * device_name, long Baud_Rate, int Parity, int Data_Bits,
int Stop_Bits, int Input_Queue_Size, int Output_Queue_Size ){
 
int fd;
 
memset (&tattr, 0, sizeof tattr);
 
fd=open(dev, O_RDWR | O_NOCTTY | O_SYNC);
// see 'man tcsetattr'
tcgetattr (fd, &tattr);
cfmakeraw(&tattr);
cfsetspeed(&tattr, B38400);
// cfsetispeed(&tattr, B38400);
// cfsetospeed(&tattr, B38400);
// input modes
tattr.c_iflag&=~IGNBRK;
tattr.c_iflag&=~(IGNCR | ICRNL | INLCR);
tattr.c_iflag&=~(IXON | IXOFF | IXANY);
// output modess
tattr.c_oflag=0;
// local modes
tattr.c_lflag=0;
tattr.c_lflag &= ~(ICANON|ECHO) ; // canonical mode and echo input char
// control modes
tattr.c_cflag |= (CLOCAL | CREAD); // ignore modem controls,
// enable reading
tattr.c_cflag &= ~(PARENB | PARODD); // shut off parity
tattr.c_cflag &= ~CSTOPB; // set two stop bits
tattr.c_cflag &= ~CRTSCTS; // enable RTS/CTS flow control
 
tattr.c_cc[VMIN] = 0;
tattr.c_cc[VTIME] = 2;
tcsetattr(fd, TCSAFLUSH, &tattr);
 
#ifdef DEBUG
printf("OpenComConfig\n");
#endif
return fd; ;
}
 
 
int CloseCom (int fd){
 
close(fd);
return;
}
/lab/sipmscan/trunk/src/MIKRO/rs232.h
0,0 → 1,20
#ifndef _RS232_H_
#define _RS232_H_
#include <stdlib.h>
#include <stdio.h>
 
#define LWRS_HWHANDSHAKE_OFF 0
#define LWRS_HWHANDSHAKE_CTS_RTS_DTR 1
#define LWRS_HWHANDSHAKE_CTS_RTS 2
 
int Delay(double seconds);
int FlushInQ(int fd);
int FlushOutQ(int fd);
int ComWrt (int fd, char* cmd, int Count ) ;
int ComRdTerm (int fd, char* result, int count, int termchar );
int OpenComConfig(char *dev, char * device_name, long Baud_Rate, int Parity, int Data_Bits,
int Stop_Bits, int Input_Queue_Size, int Output_Queue_Size );
int CloseCom (int fd);
int SetComTime(int fd, double timeout_seconds);
#endif
 
/lab/sipmscan/trunk/src/analysis.cpp
0,0 → 1,1699
#include "../include/sipmscan.h"
#include "../include/workstation.h"
 
#include <stdio.h>
#include <stdlib.h>
 
// Peak detection function
int npeaks = 20;
double FindPeaks(double *x, double *par)
{
double result = 0;
for(int i = 0; i < npeaks; i++)
{
double norm = par[3*i];
double mean = par[3*i+1];
double sigma = par[3*i+2];
result += norm*TMath::Gaus(x[0], mean, sigma);
}
return result;
}
 
// File browser for selecting the dark run histogram
void TGAppMainFrame::SelectDarkHist()
{
TGFileInfo file_info;
const char *filetypes[] = {"Histograms",histextall,0,0};
char *cTemp;
file_info.fFileTypes = filetypes;
cTemp = new char[1024];
sprintf(cTemp, "%s/results", rootdir);
file_info.fIniDir = StrDup(cTemp);
file_info.fMultipleSelection = kFALSE;
new TGFileDialog(gClient->GetDefaultRoot(), fMain, kFDOpen, &file_info);
delete[] cTemp;
 
if(file_info.fFilename != NULL)
{
darkRun->widgetTE->SetText(file_info.fFilename);
fileList->AddEntry(file_info.fFilename, fileList->GetNumberOfEntries());
fileList->Layout();
}
else
darkRun->widgetTE->SetText("");
}
 
// Reset analysis defaults for the current analysis type (0 = Integrate spectrum, 1 = Relative PDE, 2 = Breakdown voltage, 3 = Surface scan, 4 = Timing analysis)
void TGAppMainFrame::AnalysisDefaults()
{
printf("AnalysisDefaults(): Current analysis tab = %d\n", analTab->GetCurrent());
if(analTab->GetCurrent() == 0) // Integrate spectrum
{
intSpect->widgetChBox[0]->SetState(kButtonUp);
intSpect->widgetChBox[1]->SetState(kButtonUp);
intSpect->widgetChBox[2]->SetState(kButtonDown);
resol2d->widgetNE[0]->SetNumber(40);
resol2d->widgetNE[1]->SetNumber(40);
}
else if(analTab->GetCurrent() == 1) // Relative PDE
{
relPde->widgetChBox[1]->SetState(kButtonDown);
midPeak->widgetChBox[0]->SetState(kButtonUp);
zeroAngle->widgetNE[0]->SetNumber(0.00);
}
else if(analTab->GetCurrent() == 2) // Breakdown voltage
{
minPeak->widgetNE[0]->SetNumber(2);
minPeak->widgetNE[0]->SetNumber(1);
}
else if(analTab->GetCurrent() == 3) // Surface scan
{
surfScanOpt->widgetChBox[0]->SetState(kButtonDown);
surfScanOpt->widgetChBox[1]->SetState(kButtonUp);
resolSurf->widgetNE[0]->SetNumber(40);
resolSurf->widgetNE[1]->SetNumber(40);
}
}
 
// Analysis handle function
void TGAppMainFrame::AnalysisHandle(int type)
{
TList *files;
bool createTab = true;
int tabid = -1;
int analtab = analTab->GetCurrent();
 
int analtype;
if( (analtab == 0) && (!intSpect->widgetChBox[0]->IsDown() && !intSpect->widgetChBox[1]->IsDown()) )
analtype = 0;
else if( (analtab == 0) && (intSpect->widgetChBox[0]->IsDown() || intSpect->widgetChBox[1]->IsDown()) )
analtype = 1;
else if( analtab == 1 )
analtype = 2;
else if( analtab == 2 )
analtype = 3;
else if( analtab == 3 )
analtype = 4;
 
// Only integrate spectrum or make relative PDE
if(type == 0)
{
files = new TList();
fileList->GetSelectedEntries(files);
 
if( analtype == 0 )
IntegSpectrum(files, 0, 0);
 
if( intSpect->widgetChBox[0]->IsDown() )
IntegSpectrum(files, 1, 0);
 
if( intSpect->widgetChBox[1]->IsDown() )
IntegSpectrum(files, 2, 0);
 
if( analtype == 2 )
PhotonMu(files, 0);
 
if( analtype == 3 )
BreakdownVolt(files, 0);
 
if( analtype == 4 )
SurfaceScan(files, 0);
}
// Integrate spectrum or make relative PDE and open edit window
else if(type == 1)
{
files = new TList();
fileList->GetSelectedEntries(files);
 
// Prepare a new analysis edit tab, if we want to edit plots
for(int i = 0; i < fTab->GetNumberOfTabs(); i++)
{
if(strcmp("Analysis edit", fTab->GetTabTab(i)->GetString() ) == 0)
{
createTab = false;
tabid = i;
}
if(DBGSIG) printf("AnalysisHandle(): Name of tab = %s\n", fTab->GetTabTab(i)->GetString() );
}
if(files->GetSize() > 0)
{
TempAnalysisTab(fTab, createTab, &tabid, analtype);
 
// Integrate spectra
if( analtype == 0 )
IntegSpectrum(files, 0, 1);
 
if( intSpect->widgetChBox[0]->IsDown() )
IntegSpectrum(files, 1, 1);
 
if( intSpect->widgetChBox[1]->IsDown() )
IntegSpectrum(files, 2, 1);
 
if( analtype == 2 )
PhotonMu(files, 1);
 
if( analtype == 3 )
BreakdownVolt(files, 1);
 
if( analtype == 4 )
SurfaceScan(files, 1);
 
fTab->SetTab(tabid);
}
}
 
delete files;
}
 
// Analysis functions ----------------------------------
void TGAppMainFrame::IntegSpectrum(TList *files, int direction, int edit)
{
unsigned int nrfiles = files->GetSize();
char ctemp[1024];
char exportname[1024];
int j, k = 0, m = 0;
 
TTree *header_data, *meas_data;
double *integralCount, *integralAcc;
integralCount = new double[nrfiles];
integralAcc = new double[nrfiles];
double *surfxy, *surfz;
surfxy = new double[nrfiles];
surfz = new double[nrfiles];
double minInteg, maxInteg;
bool norm = intSpect->widgetChBox[2]->IsDown();
double curzval;
bool edge2d = false;
TCanvas *gCanvas;
 
float progVal = 0;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
 
// Zero the integral count and accumulated vaules
for(int i = 0; i < (int)nrfiles; i++) {integralCount[i] = 0; integralAcc[i] = 0; }
 
// Start if we select at least one file
if(nrfiles > 0)
{
for(int i = 0; i < (int)nrfiles; i++)
{
if(files->At(i))
{
// Read the X,Y and Z positions from header and ADC and TDC values from the measurements
sprintf(ctemp, "%s", files->At(i)->GetTitle());
inroot = new TFile(ctemp, "READ");
inroot->GetObject("header_data", header_data);
inroot->GetObject("meas_data", meas_data);
header_data->SetBranchAddress("xpos", &evtheader.xpos);
header_data->GetEntry(0);
header_data->SetBranchAddress("ypos", &evtheader.ypos);
header_data->GetEntry(0);
header_data->SetBranchAddress("zpos", &evtheader.zpos);
header_data->GetEntry(0);
 
char rdc[256];
j = selectCh->widgetNE[0]->GetNumber();
double rangetdc[2];
rangetdc[0] = tdcRange->widgetNE[0]->GetNumber();
rangetdc[1] = tdcRange->widgetNE[1]->GetNumber();
k = 0;
m = 0;
// Reading the data
for(int e = 0; e < meas_data->GetEntries(); e++)
{
sprintf(rdc, "ADC%d", j);
meas_data->SetBranchAddress(rdc, &evtdata.adcdata[j]);
meas_data->GetEntry(e);
sprintf(rdc, "TDC%d", j);
meas_data->SetBranchAddress(rdc, &evtdata.tdcdata[j]);
meas_data->GetEntry(e);
// Use data point only if it is inside the TDC window
if( ((double)evtdata.tdcdata[j]/tdctimeconversion >= rangetdc[0]) && ((double)evtdata.tdcdata[j]/tdctimeconversion <= rangetdc[1]) )
{
k++;
m += evtdata.adcdata[j];
}
}
 
// X, Y and Z values from each file (table units or microns)
if(posUnits->widgetCB->GetSelected() == 0)
{
if(direction == 1)
surfxy[i] = (double)(evtheader.xpos);
else if(direction == 2)
surfxy[i] = (double)(evtheader.ypos);
surfz[i] = (double)(evtheader.zpos);
}
else if(posUnits->widgetCB->GetSelected() == 1)
{
if(direction == 1)
surfxy[i] = (double)(evtheader.xpos*lenconversion);
else if(direction == 2)
surfxy[i] = (double)(evtheader.ypos*lenconversion);
surfz[i] = (double)(evtheader.zpos*lenconversion);
}
 
// Check if we have different Z values: if no, just make the edge plots; if yes, save edge plots and make a 2d edge plot
if(i == 0) curzval = surfz[i];
else
{
if(surfz[i] != curzval)
edge2d = true;
}
 
// Print the calculated integral, if no X or Y direction edge plots are enabled; otherwise, just save for later plotting
if(direction == 0)
{
if(norm)
{
integralCount[i] += ((double)m)/((double)k);
printf("IntegSpectrum(): %s: The integral is: %lf\n", ctemp, integralCount[i]);
}
else
{
integralCount[i] += m;
printf("IntegSpectrum(): %s: The integral is: %d\n", ctemp, (int)integralCount[i]);
}
}
else
{
if(norm)
integralCount[i] += ((double)m)/((double)k);
else
integralCount[i] += m;
}
inroot->Close();
delete inroot;
}
 
// Update the progress bar
progVal = (float)(75.00/nrfiles)*i;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
printf("IntegSpectrum(): %d files were selected.\n", nrfiles);
 
// If only an integral is needed, do not plot and exit here
if( direction == 0 )
{
delete[] integralCount;
delete[] surfxy;
delete[] surfz;
return;
}
 
// Current z value and the accumulated counter
curzval = surfz[0];
j = 0;
int acc = 0;
int zb;
for(int i = 0; i <= (int)nrfiles; i++)
{
// Collect the accumulated integral in order to produce a PDF from a CDF
// While we are at the same Z value, save under one set
if( (surfz[i] == curzval) && (acc != nrfiles) )
{
integralAcc[j] = integralCount[i];
if(DBGSIG) printf("IntegSpectrum(): Integral check 1 (i=%d,j=%d,z=%.2lf): %lf\t%lf\n", i, j, surfz[i], integralCount[i], integralAcc[j]);
j++;
acc++;
}
// When we switch to a new set of Z values and at the end, we must save the previous ones to make 1D edge plots
else
{
// Find minimal and maximal integral values to subtract the offset and normate PDF to 1
NormateSet(i, j, &minInteg, &maxInteg, integralCount, integralAcc);
 
if(acc != nrfiles)
{
curzval = surfz[i];
// PDF and CDF plot
PlotEdgeDistribution(files, i, j, &minInteg, &maxInteg, surfxy, integralAcc, direction, edge2d, edit);
i--;
j = 0;
}
else
{
// PDF and CDF plot
PlotEdgeDistribution(files, i, j, &minInteg, &maxInteg, surfxy, integralAcc, direction, edge2d, edit);
i--;
break;
}
}
 
// Update the progress bar
progVal = (float)(15.00/nrfiles)*i+75.00;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
// Make the 2D edge plot
if(edge2d)
{
if(edit == 0)
gCanvas = new TCanvas("canv","canv",900,900);
else
gCanvas = tempAnalysisCanvas->GetCanvas();
 
double range[4];
TGraph2D *gScan2D;
gScan2D = new TGraph2D();
range[0] = TMath::MinElement(nrfiles, surfxy);
range[1] = TMath::MaxElement(nrfiles, surfxy);
range[2] = TMath::MinElement(nrfiles, surfz);
range[3] = TMath::MaxElement(nrfiles, surfz);
 
for(int i = 0; i < nrfiles; i++)
{
if(DBGSIG)
printf("IntegSpectrum(): %.2lf\t%.2lf\t%lf\n", surfxy[i], surfz[i], integralCount[i]);
gScan2D->SetPoint(i, surfxy[i], surfz[i], integralCount[i]);
 
// Update the progress bar
progVal = (float)(9.00/nrfiles)*i+90.00;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
gCanvas->cd();
gStyle->SetPalette(1);
gCanvas->SetLeftMargin(0.15);
gCanvas->SetRightMargin(0.126);
gCanvas->SetTopMargin(0.077);
gScan2D->Draw("COLZ");
gCanvas->Modified();
gCanvas->Update();
 
gScan2D->SetNpx((int)resol2d->widgetNE[0]->GetNumber());
gScan2D->SetNpy((int)resol2d->widgetNE[1]->GetNumber());
gCanvas->Modified();
gCanvas->Update();
if(direction == 1)
gScan2D->GetXaxis()->SetTitle("X [#mum]");
else if(direction == 2)
gScan2D->GetXaxis()->SetTitle("Y [#mum]");
 
gScan2D->GetXaxis()->SetTitleOffset(1.3);
gScan2D->GetXaxis()->CenterTitle(kTRUE);
gScan2D->GetXaxis()->SetLabelSize(0.027);
gScan2D->GetXaxis()->SetLabelOffset(0.02);
gScan2D->GetXaxis()->SetRangeUser(range[0], range[1]);
gScan2D->GetXaxis()->SetNoExponent(kTRUE);
gScan2D->GetYaxis()->SetTitleOffset(1.9);
gScan2D->GetYaxis()->CenterTitle(kTRUE);
gScan2D->GetYaxis()->SetLabelSize(0.027);
gScan2D->GetXaxis()->SetLabelOffset(0.02);
gScan2D->GetYaxis()->SetRangeUser(range[2], range[3]);
gScan2D->GetYaxis()->SetNoExponent(kTRUE);
 
/* TGaxis *yax = (TGaxis*)gScan2D->GetYaxis();
yax->SetMaxDigits(4);*/
 
if(!cleanPlots)
{
if(direction == 1)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan2D->SetTitle("Laser focal point;X [table units];Z [table units]");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan2D->SetTitle("Laser focal point;X [#mum];Z [#mum]");
}
else if(direction == 2)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan2D->SetTitle("Laser focal point;Y [table units];Z [table units]");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan2D->SetTitle("Laser focal point;Y [#mum];Z [#mum]");
}
}
else
{
if(direction == 1)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan2D->SetTitle(";X [table units];Z [table units]");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan2D->SetTitle(";X [#mum];Z [#mum]");
}
else if(direction == 2)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan2D->SetTitle(";Y [table units];Z [table units]");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan2D->SetTitle(";Y [#mum];Z [#mum]");
}
}
gCanvas->Modified();
gCanvas->Update();
 
remove_from_last((char*)files->At(0)->GetTitle(), '_', ctemp);
sprintf(exportname, "%s", ctemp);
remove_from_last(exportname, '_', ctemp);
if(direction == 1)
sprintf(exportname, "%s_xdir_focalpoint.pdf", ctemp);
else if(direction == 2)
sprintf(exportname, "%s_ydir_focalpoint.pdf", ctemp);
gCanvas->SaveAs(exportname);
 
// Update the progress bar
analysisProgress->widgetPB->SetPosition(100.0);
gVirtualX->Update(1);
 
if(edit == 0)
{
delete gScan2D;
delete gCanvas;
}
}
else
{
// Update the progress bar
analysisProgress->widgetPB->SetPosition(100.0);
gVirtualX->Update(1);
}
}
}
 
void TGAppMainFrame::PlotEdgeDistribution(TList *files, int filenr, int points, double *min, double *max, double *xy, double *integAcc, int axis, bool edge2d, int edit)
{
TGraph *gScan[2];
int pdfmax = -1;
int count = 0;
char ctemp[1024];
char exportname[1024];
TCanvas *gCanvas;
 
// Prepare the CDF plot
gScan[1] = new TGraph();
for(int i = 0; i < points; i++)
{
count = filenr - points + i;
gScan[1]->SetPoint(i, (double)xy[count], (double)integAcc[i]/(*max));
if(DBGSIG) printf("PlotEdgeDistribution(): CDF %d: %lf, %lf\n", i, (double)xy[count], (double)integAcc[i]/(*max));
 
if( ((integAcc[i+1]-integAcc[i])/(*max) > pdfmax) && (i < points-1) )
pdfmax = (integAcc[i+1]-integAcc[i])/(*max);
}
 
pdfmax = (TMath::Ceil(pdfmax*10))/10.;
 
// Prepare the PDF plot
gScan[0] = new TGraph();
for(int i = points-1; i >= 0; i--)
{
count = (filenr-1) - (points-1) + i;
// Set any negative values of the PDF to 0
if( (integAcc[i]-integAcc[i-1])/(*max) < 0 )
gScan[0]->SetPoint(i, (double)xy[count], 0);
else
gScan[0]->SetPoint(i, (double)xy[count], (integAcc[i]-integAcc[i-1])/(*max));
if(DBGSIG) printf("PlotEdgeDistribution(): PDF %d: %lf, %lf\n", i, (double)xy[count], (integAcc[i+1]-integAcc[i])/(*max));
}
 
remove_from_last((char*)files->At(filenr-1)->GetTitle(), '_', ctemp);
sprintf(exportname, "%s_edge.pdf", ctemp);
 
if(edit == 0)
gCanvas = new TCanvas("canv1d","canv1d",1200,900);
else
gCanvas = tempAnalysisCanvas->GetCanvas();
 
// Fit the PDF with a gaussian
gScan[0]->Fit("gaus","Q");
gScan[0]->GetFunction("gaus")->SetNpx(400);
 
gStyle->SetOptFit(1);
 
gScan[1]->Draw("AL");
gPad->Update();
gScan[0]->Draw("LP");
 
gCanvas->Modified();
gCanvas->Update();
 
TPaveStats *stats = (TPaveStats*)gScan[0]->FindObject("stats");
if(!cleanPlots)
{
stats->SetX1NDC(0.86); stats->SetX2NDC(1.0);
stats->SetY1NDC(0.87); stats->SetY2NDC(1.0);
}
else
{
stats->SetX1NDC(1.1); stats->SetX2NDC(1.3);
stats->SetY1NDC(1.1); stats->SetY2NDC(1.3);
}
 
gCanvas->SetGridx(1);
gCanvas->SetGridy(1);
if(axis == 1)
gScan[1]->GetXaxis()->SetTitle("X [#mum]");
else if(axis == 2)
gScan[1]->GetXaxis()->SetTitle("Y [#mum]");
gScan[1]->GetXaxis()->SetTitleOffset(1.3);
gScan[1]->GetXaxis()->CenterTitle(kTRUE);
gScan[1]->GetXaxis()->SetLabelSize(0.027);
gScan[1]->GetXaxis()->SetLabelOffset(0.02);
gScan[1]->GetXaxis()->SetNoExponent(kTRUE);
gScan[1]->GetYaxis()->SetTitle("Normalized ADC integral");
 
gScan[1]->GetYaxis()->CenterTitle(kTRUE);
gScan[1]->GetYaxis()->SetLabelSize(0.027);
gScan[1]->GetYaxis()->SetLabelOffset(0.02);
gScan[1]->GetYaxis()->SetRangeUser(0,1);
gScan[1]->GetYaxis()->SetTitleOffset(1.4);
gScan[1]->GetYaxis()->SetTitleSize(0.030);
 
if(!cleanPlots)
{
if(axis == 1)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan[1]->SetTitle("SiPM edge detection;X [table units];Normalized ADC integral");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan[1]->SetTitle("SiPM edge detection;X [#mum];Normalized ADC integral");
}
else if(axis == 2)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan[1]->SetTitle("SiPM edge detection;Y [table units];Normalized ADC integral");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan[1]->SetTitle("SiPM edge detection;Y [#mum];Normalized ADC integral");
}
}
else
{
if(axis == 1)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan[1]->SetTitle(";X [table units];Normalized ADC integral");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan[1]->SetTitle(";X [#mum];Normalized ADC integral");
}
else if(axis == 2)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan[1]->SetTitle(";Y [table units];Normalized ADC integral");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan[1]->SetTitle(";Y [#mum];Normalized ADC integral");
}
}
gScan[1]->SetLineColor(kBlue);
gScan[0]->SetLineWidth(2);
gScan[1]->SetLineWidth(2);
 
gCanvas->Modified();
gCanvas->Update();
 
gCanvas->SaveAs(exportname);
 
// If 2D edge plot, delete the 1D edge plots as we go
if(edge2d)
{
delete gScan[0];
delete gScan[1];
if(edit == 0)
delete gCanvas;
}
else
{
if(edit == 0)
{
delete gScan[0];
delete gScan[1];
delete gCanvas;
}
}
}
 
void TGAppMainFrame::PhotonMu(TList *files, int edit)
{
unsigned int nrfiles = files->GetSize();
char ctemp[1024];
char exportname[1024];
int j, k = 0, m = 0, n = 0, k2 = 0, m2 = 0;
 
TCanvas *gCanvas;
TTree *header_data, *meas_data;
double *integralCount, *integralPedestal;
integralCount = new double[nrfiles];
integralPedestal = new double[nrfiles];
double *angle, *pdeval, *muval;
angle = new double[nrfiles];
pdeval = new double[nrfiles];
muval = new double[nrfiles];
 
// Zero the integral count and accumulated vaules
for(int i = 0; i < (int)nrfiles; i++) {integralCount[i] = 0; integralPedestal[i] = 0; }
 
// Fitting variables
TSpectrum *spec;
TH1F *histtemp;
TH1 *histback;
TH1F *h2;
float *xpeaks;
TF1 *fit;
TF1 *fittingfunc;
double *fparam, *fparamerr;
double meansel[20];
double sigmasel[20];
double meanparam, paramsigma;
int sortindex[20];
int adcpedestal[2];
int zeromu = 0;
int darkhist = -1;
 
double pointest[12];
bool exclude = false;
 
// Zero the parameter values
for(int i = 0; i < 20; i++) {meansel[i] = 0; sigmasel[i] = 0; }
 
float progVal = 0;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
 
// Start if we select at least one file
if(nrfiles > 0)
{
for(int i = 0; i < (int)nrfiles; i++)
{
if(files->At(i))
{
if(strcmp(files->At(i)->GetTitle(),darkRun->widgetTE->GetText()) == 0)
{
printf("PhotonMu(): %s is the dark histogram file.\n", files->At(i)->GetTitle());
darkhist = i;
}
 
// Replot the spectrum on analysisCanvas and do not close the input file
DisplayHistogram( (char*)(files->At(i)->GetTitle()), 0, 1);
analysisCanvas->GetCanvas()->Modified();
analysisCanvas->GetCanvas()->Update();
// Get the spectrum
histtemp = (TH1F*)analysisCanvas->GetCanvas()->GetPrimitive(histname);
npeaks = 15;
double par[300];
spec = new TSpectrum(npeaks);
// Find spectrum background
histback = spec->Background(histtemp, (int)fitInter->widgetNE[0]->GetNumber(), "same");
// Clone histogram and subtract background from it if we select that option
h2 = (TH1F*)histtemp->Clone("h2");
if(fitChecks->widgetChBox[0]->IsDown())
h2->Add(histback, -1);
// Search for the peaks
int found = spec->Search(h2, fitSigma->widgetNE[0]->GetNumber(), "goff", fitTresh->widgetNE[0]->GetNumber() );
printf("PhotonMu(): Found %d candidates to fit.\n",found);
npeaks = found;
// Set initial peak parameters
xpeaks = spec->GetPositionX();
for(j = 0; j < found; j++)
{
float xp = xpeaks[j];
int bin = h2->GetXaxis()->FindBin(xp);
float yp = h2->GetBinContent(bin);
par[3*j] = yp;
par[3*j+1] = xp;
par[3*j+2] = (double)fitSigma->widgetNE[0]->GetNumber();
}
// Fit the histogram
fit = new TF1("fit", FindPeaks, adcRange->widgetNE[0]->GetNumber(), adcRange->widgetNE[1]->GetNumber(), 3*npeaks);
TVirtualFitter::Fitter(histtemp, 3*npeaks);
fit->SetParameters(par);
fit->SetNpx(300);
h2->Fit("fit","Q");
// Get the fitted parameters
fittingfunc = h2->GetFunction("fit");
fparam = fittingfunc->GetParameters();
fparamerr = fittingfunc->GetParErrors();
// Gather the parameters (mean peak value for now)
int j = 1;
int nrfit = 0;
while(1)
{
if( (fparam[j] < 1.E-30) || (nrfit > 8) )
break;
else
{
// Check if pedestal is above the lower limit and sigma is smaller than the mean
if( (fparam[j] > pedesLow->widgetNE[0]->GetNumber()) && ((double)fparamerr[j]/fparam[j] < accError->widgetNE[0]->GetNumber()) )
{
// With the additional ADC offset, we can shift the mean values slightly, so they are not close to the X.5, but to the X.0 values
meansel[nrfit] = fparam[j]+(adcOffset->widgetNE[0]->GetNumber());
sigmasel[nrfit] = fparam[j+1];
nrfit++;
}
}
j+=3;
}
TMath::Sort(nrfit, meansel, sortindex, kFALSE);
 
meanparam = meansel[sortindex[0]];
paramsigma = sigmasel[sortindex[0]];
 
for(j = 0; j < nrfit; j++)
if(DBGSIG)
printf("PhotonMu(): %d: peak mean = %lf\n", j, meansel[sortindex[j]]);
j = 0;
adcpedestal[0] = 0;
adcpedestal[1] = -1;
 
while(1)
{
int bin = histtemp->GetXaxis()->FindBin((int)(j+meanparam+paramsigma));
int yp = histtemp->GetBinContent(bin);
 
// Check where we get to first minimum after pedestal peak or where we get to the half maximum of the pedestal peak (in case there is only a pedestal peak)
if(adcpedestal[1] == -1)
{
adcpedestal[0] = j+meanparam+paramsigma;
adcpedestal[1] = yp;
}
else
{
if( (npeaks > 1) && (adcpedestal[1] >= yp) )
{
adcpedestal[0] = j+meanparam+paramsigma;
adcpedestal[1] = yp;
}
else if( (npeaks == 1) && (adcpedestal[0] < meanparam+5*paramsigma) ) // TODO -> Determining the pedestal when only one peak
{
adcpedestal[0] = j+meanparam+paramsigma;
adcpedestal[1] = yp;
}
else
break;
}
j++;
if(j > 50) break;
}
 
if(npeaks > 1)
{
int bin = histtemp->GetXaxis()->FindBin((int)(meanparam+meansel[sortindex[1]])/2);
adcpedestal[0] = (meanparam+meansel[sortindex[1]])/2;
printf("PhotonMu(): multipeak x = %d, ", adcpedestal[0]);
adcpedestal[1] = histtemp->GetBinContent(bin);
}
 
if(midPeak->widgetChBox[0]->IsDown())
{
if( (meanparam - (int)meanparam >= 0.) && (meanparam - (int)meanparam < 0.5) )
m = TMath::Floor(meanparam);
else if( (meanparam - (int)meanparam >= 0.5) && (meanparam - (int)meanparam < 1.) )
m = TMath::Ceil(meanparam);
int bin = histtemp->GetXaxis()->FindBin(m);
adcpedestal[0] = m;
printf("midpeak x = %d, ", adcpedestal[0]);
adcpedestal[1] = histtemp->GetBinContent(bin);
}
 
/* // Option to show the fit
fittingfunc->Draw("L SAME");
analysisCanvas->GetCanvas()->Modified();
analysisCanvas->GetCanvas()->Update();*/
printf("Pedestal ends = %d and nr. of counts = %d\n", adcpedestal[0], adcpedestal[1]);
 
// Delete the opened histogram and spectrum
delete spec;
delete inroot;
 
// Open the input file and read header, ADC and TDC values
sprintf(ctemp, "%s", files->At(i)->GetTitle());
inroot = new TFile(ctemp, "READ");
inroot->GetObject("header_data", header_data);
inroot->GetObject("meas_data", meas_data);
// Reading the header
if( header_data->FindBranch("angle") )
{
header_data->SetBranchAddress("angle", &evtheader.angle);
header_data->GetEntry(0);
}
else
{
printf("PhotonMu(): Error! Selected file has no angle header value. Please edit header to add the angle header value.\n");
break;
}
char rdc[256];
j = selectCh->widgetNE[0]->GetNumber();
double rangetdc[2];
rangetdc[0] = tdcRange->widgetNE[0]->GetNumber();
rangetdc[1] = tdcRange->widgetNE[1]->GetNumber();
k = 0;
k2 = 0;
m = 0;
m2 = 0;
 
// Reading the data
for(int e = 0; e < meas_data->GetEntries(); e++)
{
sprintf(rdc, "ADC%d", j);
meas_data->SetBranchAddress(rdc, &evtdata.adcdata[j]);
meas_data->GetEntry(e);
sprintf(rdc, "TDC%d", j);
meas_data->SetBranchAddress(rdc, &evtdata.tdcdata[j]);
meas_data->GetEntry(e);
// If our data point is inside the TDC window
if( ((double)evtdata.tdcdata[j]/tdctimeconversion >= rangetdc[0]) && ((double)evtdata.tdcdata[j]/tdctimeconversion <= rangetdc[1]) )
{
// Gather only the integral of the pedestal
if((double)evtdata.adcdata[j] < (double)adcpedestal[0]+0.5 )
{
k2++;
m2 += evtdata.adcdata[j];
}
 
// Gather the complete integral
k++;
m += evtdata.adcdata[j];
}
}
 
// Determine the angle, mu and relative PDE
angle[i] = (double)(evtheader.angle);
integralCount[i] += (double)m;
printf("PhotonMu(): %lf: Complete integral (%d evts) = %lf\n", angle[i], k, integralCount[i]);
integralPedestal[i] += (double)m2;
printf("PhotonMu(): %lf: Pedestal integral (%d evts) = %lf\n", angle[i], k2, integralPedestal[i]);
if( (angle[i] == zeroAngle->widgetNE[0]->GetNumber()) && (darkhist != i) )
zeromu = i;
 
muval[i] = -TMath::Log((double)k2/(double)k);
printf("PhotonMu(): %lf: muval = %lf\n", angle[i], muval[i]);
 
inroot->Close();
delete inroot;
}
 
// Update the progress bar
progVal = (float)(90.00/nrfiles)*i;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
printf("PhotonMu(): %d files were selected.\n", nrfiles);
 
printf("PhotonMu(): angle\tmu\trelative PDE\n");
m = 0;
// Set the 0 degree muval, reuse meansel[1]
meansel[1] = muval[zeromu];
printf("Zero value (id=%d, angle=%lf) = %lf\n", zeromu, angle[zeromu], meansel[1]);
 
// TODO - point estimation still not working correctly!
for(int i = 0; i < (int)nrfiles; i++)
{
// Estimate next point and check error (5 point least square fit estimation)
if( ((i > 4) && (m == i)) || ((i > 5) && (m < i)) )
{
// Set exclude signal to false
exclude = false;
 
// Get next point values (if zero value -> need to add the dark hist value again)
pointest[10] = angle[i];
pointest[11] = muval[i];
 
// Check if next point has larger error than acceptable (if yes, set exclude signal to true), reuse meansel[0]
meansel[0] = PointEstimate(5, pointest); // PointEstimate only works with very small step size
if(meansel[0] > accError->widgetNE[0]->GetNumber())
{
printf("PhotonMu(): Point (%lf, %lf) excluded due to error: %lf\n", pointest[10], pointest[11], meansel[0]);
exclude = true;
}
 
// Value with 0 angle and dark histogram are always needed, so should not be excluded
if(i == darkhist)
exclude = false;
 
// If nothing excluded, pass the points in pointest variable like in a FIFO
if(!exclude)
{
for(int j = 0; j < 10; j++)
{
if(DBGSIG) printf("PhotonMu(): j = %d: Old X value = %lf\n", j, pointest[j]);
pointest[j] = pointest[j+2];
}
}
else
{
for(int j = 0; j < 10; j++)
if(DBGSIG) printf("PhotonMu(): No j = %d: Old X value = %lf\n", j, pointest[j]);
}
}
else
{
// First 5 points act as estimator points for next one
pointest[2*m] = angle[i];
pointest[2*m+1] = muval[i];
}
 
// Run only if we have a dark run histogram and middle pedestal peak estimation
if( (darkhist != -1) && midPeak->widgetChBox[0]->IsDown() )
{
if(DBGSIG) printf("PhotonMu(): m = %d, i = %d: muval = %lf, ", m, i, muval[i]);
 
// Subtract the dark value from all values
angle[m] = angle[i];
muval[m] = muval[i] - muval[darkhist];
 
if(DBGSIG) printf("angle = %lf, newmuval = %lf, darkmuval = %lf, ", angle[m], muval[m], muval[darkhist]);
 
// Calculate relative PDE
// pdeval[m] = muval[m]/(muval[zeromu]*TMath::Cos(angle[m]*TMath::ACos(-1.)/180.));
pdeval[m] = muval[m]/((meansel[1]-muval[darkhist])*TMath::Cos(angle[m]*TMath::ACos(-1.)/180.));
if(DBGSIG) printf("pdeval = %lf\n", pdeval[m]);
 
// Only increase counter if error is not too big
if( (darkhist != i) && (!exclude) )
m++;
}
else
{
// Relative PDE calculation
angle[m] = angle[i];
muval[m] = muval[i];
// pdeval[m] = muval[m]/(muval[zeromu]*TMath::Cos(angle[m]*TMath::ACos(-1.)/180.));
pdeval[m] = muval[m]/(meansel[1]*TMath::Cos(angle[m]*TMath::ACos(-1.)/180.));
 
// Only increase counter if error is not too big
if(!exclude)
m++;
}
printf("PhotonMu(): %lf\t%lf\t%lf\n", angle[i], muval[i], pdeval[i]);
}
 
if(DBGSIG) printf("\n");
if(darkhist != -1)
printf("PhotonMu(): Number of excluded points: %d\n", (nrfiles-1-m));
else
printf("PhotonMu(): Number of excluded points: %d\n", (nrfiles-m));
 
// Plot mu and PDE angle dependance plots
if(edit == 0)
gCanvas = new TCanvas("canv","canv",1200,900);
else if(edit == 1)
gCanvas = tempAnalysisCanvas->GetCanvas();
gCanvas->cd();
gCanvas->SetGrid();
 
TGraph *pde = new TGraph(m, angle, pdeval);
pde->SetMarkerStyle(21);
pde->SetMarkerSize(0.7);
pde->SetMarkerColor(2);
pde->SetLineWidth(1);
pde->SetLineColor(2);
pde->GetXaxis()->SetLabelSize(0.030);
pde->GetXaxis()->CenterTitle();
// pde->GetXaxis()->SetRange(angle[0],angle[nrfiles-1]);
// pde->GetXaxis()->SetRangeUser(angle[0],angle[nrfiles-1]);
pde->GetXaxis()->SetRange(-90,90);
pde->GetXaxis()->SetRangeUser(-90,90);
pde->GetXaxis()->SetLimits(-90,90);
pde->GetYaxis()->SetTitleOffset(1.2);
pde->GetYaxis()->SetLabelSize(0.030);
pde->GetYaxis()->CenterTitle();
pde->GetYaxis()->SetRangeUser(0., 1.2);
pde->SetName("pde");
pde->Draw("ALP");
 
pde->SetTitle(";Incidence angle (#circ);Relative PDE(#theta) / #mu(#theta)");
 
TGraph *mugr = new TGraph(m, angle, muval);
mugr->SetMarkerStyle(20);
mugr->SetMarkerSize(0.7);
mugr->SetMarkerColor(4);
mugr->SetLineWidth(1);
mugr->SetLineColor(4);
mugr->SetName("muval");
mugr->Draw("SAME;LP");
 
gCanvas->Modified();
gCanvas->Update();
 
if(edit == 0)
{
remove_from_last((char*)files->At(0)->GetTitle(), '_', ctemp);
sprintf(exportname, "%s_pde.pdf", ctemp);
gCanvas->SaveAs(exportname);
 
delete mugr;
delete pde;
delete gCanvas;
}
else if(edit == 1)
{
gCanvas->Modified();
gCanvas->Update();
}
 
// Update the progress bar
analysisProgress->widgetPB->SetPosition(100.);
gVirtualX->Update(1);
}
}
 
void TGAppMainFrame::BreakdownVolt(TList *files, int edit)
{
unsigned int nrfiles = files->GetSize();
char ctemp[1024];
char exportname[1024];
char paramname[1024];
int j, k = 0;
 
TCanvas *gCanvas;
TTree *header_data, *meas_data;
 
// Fitting variables
TSpectrum *spec;
TH1F *histtemp;
TH1 *histback;
TH1F *h2;
float *xpeaks;
TF1 *fit;
TF1 *fittingfunc;
TLatex *latex;
double *fparam, *fparamerr;
double meansel[20];
double meanselerr[20];
double sigmasel[20];
double meanparam, meanparamerr, paramsigma;
int sortindex[20];
bool exclude = false;
 
int p = 0;
double volt[nrfiles], volterr[nrfiles], sep[3][nrfiles], seperr[3][nrfiles];
int first = 1;
 
FILE *fp;
remove_from_last((char*)files->At(0)->GetTitle(), '_', ctemp);
sprintf(paramname, "%s_fitresult.txt", ctemp);
fp = fopen(paramname, "w");
fclose(fp);
 
int peaklimit = minPeak->widgetNE[0]->GetNumber()+1; // +1 to account for the pedestal peak
 
// Zero the parameter values
for(int i = 0; i < nrfiles; i++)
{
volt[i] = 0; volterr[i] = 0;
sep[0][i] = 0; sep[1][i] = 0; sep[2][i] = 0;
seperr[0][i] = 0; seperr[1][i] = 0; seperr[2][i] = 0;
if(i < 20) { meansel[i] = 0; meanselerr[i] = 0; sigmasel[i] = 0; }
}
 
float progVal = 0;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
 
// Start if we select at least one file
if(nrfiles > 0)
{
for(int i = 0; i < (int)nrfiles; i++)
{
if(files->At(i))
{
// Replot the spectrum on analysisCanvas and do not close the input file
DisplayHistogram( (char*)(files->At(i)->GetTitle()), 0, 1);
analysisCanvas->GetCanvas()->Modified();
analysisCanvas->GetCanvas()->Update();
// Get the spectrum
histtemp = (TH1F*)analysisCanvas->GetCanvas()->GetPrimitive(histname);
npeaks = 15;
double par[300];
spec = new TSpectrum(npeaks);
// Find spectrum background
histback = spec->Background(histtemp, (int)fitInter->widgetNE[0]->GetNumber(), "same");
// Clone histogram and subtract background from it if we select that option
h2 = (TH1F*)histtemp->Clone("h2");
if(fitChecks->widgetChBox[0]->IsDown())
h2->Add(histback, -1);
// Search for the peaks
int found = spec->Search(h2, fitSigma->widgetNE[0]->GetNumber(), "goff", fitTresh->widgetNE[0]->GetNumber() );
printf("BreakdownVolt(): Found %d candidates to fit.\n",found);
npeaks = found;
// Set initial peak parameters
xpeaks = spec->GetPositionX();
for(j = 0; j < found; j++)
{
float xp = xpeaks[j];
int bin = h2->GetXaxis()->FindBin(xp);
float yp = h2->GetBinContent(bin);
par[3*j] = yp;
par[3*j+1] = xp;
par[3*j+2] = (double)fitSigma->widgetNE[0]->GetNumber();
}
// Fit the histogram
fit = new TF1("fit", FindPeaks, adcRange->widgetNE[0]->GetNumber(), adcRange->widgetNE[1]->GetNumber(), 3*npeaks);
TVirtualFitter::Fitter(histtemp, 3*npeaks);
fit->SetParameters(par);
fit->SetNpx(300);
h2->Fit("fit","Q");
// Get the fitted parameters
fittingfunc = h2->GetFunction("fit");
if(nrfiles == 1) // TODO: Show the fit if only one file is selected
fittingfunc->Draw("SAME");
fparam = fittingfunc->GetParameters();
fparamerr = fittingfunc->GetParErrors();
// Gather the parameters (mean peak value for now)
int j = 1;
int nrfit = 0;
while(1)
{
if( (fparam[j] < 1.E-30) || (fparamerr[j] < 1.E-10) )// TODO: Maybe not correct for the error
break;
else
{
// Check if pedestal is above the lower limit and sigma is smaller than the mean
if( (fparam[j] > pedesLow->widgetNE[0]->GetNumber()) && ((double)fparamerr[j]/fparam[j] < accError->widgetNE[0]->GetNumber()) )
{
meansel[nrfit] = fparam[j];
meanselerr[nrfit] = fparamerr[j];
sigmasel[nrfit] = fparam[j+1];
nrfit++;
}
}
j+=3;
}
TMath::Sort(nrfit, meansel, sortindex, kFALSE);
 
meanparam = meansel[sortindex[0]];
meanparamerr = meanselerr[sortindex[0]];
paramsigma = sigmasel[sortindex[0]];
 
for(j = 0; j < nrfit; j++)
{
if(DBGSIG)
printf("BreakdownVolt(): %d: peak mean = %lf, peak err = %lf\n", j, meansel[sortindex[j]], meanselerr[sortindex[j]]);
}
 
// Delete the opened histogram and spectrum
delete spec;
delete inroot;
 
// Open the input file and read header, ADC and TDC values
sprintf(ctemp, "%s", files->At(i)->GetTitle());
inroot = new TFile(ctemp, "READ");
inroot->GetObject("header_data", header_data);
inroot->GetObject("meas_data", meas_data);
// Reading the header
if( header_data->FindBranch("biasvolt") )
{
header_data->SetBranchAddress("biasvolt", &evtheader.biasvolt);
header_data->GetEntry(0);
}
else
{
printf("BreakdownVolt(): Error! Selected file has no bias voltage header value. Please edit header to add the bias voltage header value.\n");
break;
}
 
// h2->SetStats(0);
 
analysisCanvas->GetCanvas()->Modified();
analysisCanvas->GetCanvas()->Update();
// Save each fitting plot
if(fitChecks->widgetChBox[1]->IsDown()) // TODO: Check if this works
{
remove_ext((char*)files->At(i)->GetTitle(), ctemp);
sprintf(exportname, "%s_fit.pdf", ctemp);
analysisCanvas->GetCanvas()->SaveAs(exportname);
}
 
// Calculate the separation between peaks
volt[p] = evtheader.biasvolt;
volterr[p] = 1.e-5;
 
if(nrfit == 3)
{
sep[0][p] = meansel[sortindex[2]] - meansel[sortindex[1]];
seperr[0][p] = TMath::Abs(meanselerr[sortindex[2]]) + TMath::Abs(meanselerr[sortindex[1]]);
 
exclude = (seperr[0][p]/sep[0][p] < accError->widgetNE[0]->GetNumber());
}
else if(nrfit == 4)
{
sep[0][p] = meansel[sortindex[2]] - meansel[sortindex[1]];
sep[1][p] = meansel[sortindex[3]] - meansel[sortindex[2]];
seperr[0][p] = TMath::Abs(meanselerr[sortindex[2]]) + TMath::Abs(meanselerr[sortindex[1]]);
seperr[1][p] = TMath::Abs(meanselerr[sortindex[3]]) + TMath::Abs(meanselerr[sortindex[2]]);
 
exclude = ((seperr[0][p]/sep[0][p] < accError->widgetNE[0]->GetNumber()) && (seperr[1][p]/sep[1][p] < accError->widgetNE[0]->GetNumber()));
}
else if(nrfit > 4)
{
sep[0][p] = meansel[sortindex[2]] - meansel[sortindex[1]];
sep[1][p] = meansel[sortindex[3]] - meansel[sortindex[2]];
sep[2][p] = meansel[sortindex[4]] - meansel[sortindex[3]];
seperr[0][p] = TMath::Abs(meanselerr[sortindex[2]]) + TMath::Abs(meanselerr[sortindex[1]]);
seperr[1][p] = TMath::Abs(meanselerr[sortindex[3]]) + TMath::Abs(meanselerr[sortindex[2]]);
seperr[2][p] = TMath::Abs(meanselerr[sortindex[4]]) + TMath::Abs(meanselerr[sortindex[3]]);
 
exclude = ((seperr[0][p]/sep[0][p] < accError->widgetNE[0]->GetNumber()) && (seperr[1][p]/sep[1][p] < accError->widgetNE[0]->GetNumber()) && (seperr[2][p]/sep[2][p] < accError->widgetNE[0]->GetNumber()));
}
else
{
printf("BreakdownVolt(): The current separation measurements does not fall within acceptable errors.\n");
exclude = false;
}
 
// Write out parameters to a file
fp = fopen(paramname, "a");
if(exclude)
{
if(first == 1)
{
fprintf(fp, "%le\t%d\t", evtheader.biasvolt, nrfit);
for(j = 0; j < nrfit; j++)
fprintf(fp, "%le\t%le\t", meansel[sortindex[j]], meanselerr[sortindex[j]]);
fprintf(fp,"\n");
first = 0;
}
p++;
}
else
{
if(nrfit == 3)
printf("Point (at %.2lfV) rejected due to too large errors: %lf\n", volt[p], seperr[0][p]/sep[0][p]);
else if(nrfit == 4)
printf("Point (at %.2lfV) rejected due to too large errors: %lf, %lf\n", volt[p], seperr[0][p]/sep[0][p], seperr[1][p]/sep[1][p]);
else if(nrfit > 4)
printf("Point (at %.2lfV) rejected due to too large errors: %lf, %lf, %lf\n", volt[p], seperr[0][p]/sep[0][p], seperr[1][p]/sep[1][p], seperr[2][p]/sep[2][p]);
}
fclose(fp);
}
 
if(nrfiles == 1) break;
first = 1;
 
// Update the progress bar
progVal = (float)(90.00/nrfiles)*i;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
printf("BreakdownVolt(): %d files were selected.\n", nrfiles);
printf("BreakdownVolt(): Number of points to plot is %d\n", p);
// Plot and fit breakdown voltage plot
if(edit == 0)
gCanvas = new TCanvas("canv","canv",1200,900);
else if(edit == 1)
gCanvas = tempAnalysisCanvas->GetCanvas();
gCanvas->cd();
gCanvas->SetGrid();
 
TGraphErrors* bdplot;
k = peakSepCalc->widgetNE[0]->GetNumber();
if(k < 4)
bdplot = new TGraphErrors(p, volt, sep[k-1], volterr, seperr[k-1]);
else
{
printf("BreakdownVold(): Unsupported peak separation selected (%d).\n", k);
return;
}
 
bdplot->SetMarkerStyle(20);
bdplot->SetMarkerSize(0.4);
bdplot->SetMarkerColor(kBlue);
bdplot->SetLineWidth(1);
bdplot->SetLineColor(kBlue);
bdplot->GetXaxis()->SetLabelSize(0.030);
bdplot->GetXaxis()->CenterTitle();
// bdplot->GetXaxis()->SetRange(-90,90);
// bdplot->GetXaxis()->SetRangeUser(-90,90);
// bdplot->GetXaxis()->SetLimits(-90,90);
bdplot->GetYaxis()->SetTitleOffset(1.2);
bdplot->GetYaxis()->SetLabelSize(0.030);
bdplot->GetYaxis()->CenterTitle();
// bdplot->GetYaxis()->SetRangeUser(0., 1.2);
bdplot->SetName("bdplot");
bdplot->Draw("AP");
bdplot->SetTitle(";Bias voltage (V);Peak separation");
 
// Fit the breakdown voltage plot with a line
bdplot->Fit("pol1","Q");
 
TF1 *fit1 = bdplot->GetFunction("pol1");
meansel[0] = fit1->GetParameter(0);
meanselerr[0] = fit1->GetParError(0);
meansel[1] = fit1->GetParameter(1);
meanselerr[1] = fit1->GetParError(1);
 
meansel[2] = -meansel[0]/meansel[1];
if(!cleanPlots)
{
sprintf(ctemp, "#splitline{#Delta_{p}(U) = (%.2lf #pm %.2lf)#timesU + (%.2lf #pm %.3lf)}{U_{0} = %.2lf #pm %.3lf}", meansel[0], meanselerr[0], meansel[1], meanselerr[1], meansel[2], meansel[2]*(TMath::Abs(meanselerr[0]/meansel[0]) + TMath::Abs(meanselerr[1]/meansel[1])) );
latex = new TLatex();
latex->SetTextSize(0.039);
latex->DrawLatex(volt[0], 0.97*sep[0][sortindex[p-1]], ctemp);
}
else
printf("#Delta_{p}(U) = (%.2lf #pm %.2lf)#timesU + (%.2lf #pm %.3lf)}{U_{0} = %.2lf #pm %.3lf", meansel[0], meanselerr[0], meansel[1], meanselerr[1], meansel[2], meansel[2]*(TMath::Abs(meanselerr[0]/meansel[0]) + TMath::Abs(meanselerr[1]/meansel[1])) );
 
if(edit == 0)
{
remove_from_last((char*)files->At(0)->GetTitle(), '_', ctemp);
sprintf(exportname, "%s_breakdown.pdf", ctemp);
gCanvas->SaveAs(exportname);
 
delete bdplot;
delete gCanvas;
}
else if(edit == 1)
{
gCanvas->Modified();
gCanvas->Update();
}
 
// Update the progress bar
analysisProgress->widgetPB->SetPosition(100.);
gVirtualX->Update(1);
}
}
 
void TGAppMainFrame::SurfaceScan(TList *files, int edit)
{
unsigned int nrfiles = files->GetSize();
char ctemp[1024];
char exportname[1024];
int j, k = 0, m = 0, n = 0;
 
TTree *header_data, *meas_data;
double *integralCount;
integralCount = new double[nrfiles];
double *surfx, *surfy;
surfx = new double[nrfiles];
surfy = new double[nrfiles];
double xsurfmin = 0, ysurfmin = 0;
int nrentries;
// double minInteg, maxInteg;
bool norm = surfScanOpt->widgetChBox[0]->IsDown();
// double curzval;
// bool edge2d = false;
TCanvas *gCanvas;
 
float progVal = 0;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
 
// Zero the integral count and accumulated vaules
for(int i = 0; i < (int)nrfiles; i++) integralCount[i] = 0;
 
// Start if we select at more than one file
if( (nrfiles > 1) && (multiSelect->widgetChBox[0]->IsOn()) )
{
printf("SurfaceScan(): Creating a surface plot. Please wait...\n");
for(int i = 0; i < (int)nrfiles; i++)
{
if(files->At(i))
{
n++;
// Read the X and Y positions from header and ADC and TDC values from the measurements
sprintf(ctemp, "%s", files->At(i)->GetTitle());
inroot = new TFile(ctemp, "READ");
inroot->GetObject("header_data", header_data);
inroot->GetObject("meas_data", meas_data);
header_data->SetBranchAddress("xpos", &evtheader.xpos);
header_data->GetEntry(0);
header_data->SetBranchAddress("ypos", &evtheader.ypos);
header_data->GetEntry(0);
 
char rdc[256];
j = selectCh->widgetNE[0]->GetNumber();
double rangetdc[2];
rangetdc[0] = tdcRange->widgetNE[0]->GetNumber();
rangetdc[1] = tdcRange->widgetNE[1]->GetNumber();
k = 0;
m = 0;
// Reading the data
for(int e = 0; e < meas_data->GetEntries(); e++)
{
sprintf(rdc, "ADC%d", j);
meas_data->SetBranchAddress(rdc, &evtdata.adcdata[j]);
meas_data->GetEntry(e);
sprintf(rdc, "TDC%d", j);
meas_data->SetBranchAddress(rdc, &evtdata.tdcdata[j]);
meas_data->GetEntry(e);
// Use data point only if it is inside the TDC window
if( ((double)evtdata.tdcdata[j]/tdctimeconversion >= rangetdc[0]) && ((double)evtdata.tdcdata[j]/tdctimeconversion <= rangetdc[1]) )
{
k++;
m += evtdata.adcdata[j];
}
}
 
// X, Y and Z values from each file (table units or microns)
if(posUnits->widgetCB->GetSelected() == 0)
{
if(n == 1)
{
xsurfmin = (double)(evtheader.xpos);
ysurfmin = (double)(evtheader.ypos);
}
 
surfx[i] = (double)(evtheader.xpos);
surfy[i] = (double)(evtheader.ypos);
}
else if(posUnits->widgetCB->GetSelected() == 1)
{
if(n == 1)
{
xsurfmin = (double)(evtheader.xpos*lenconversion);
ysurfmin = (double)(evtheader.ypos*lenconversion);
}
 
surfx[i] = (double)(evtheader.xpos*lenconversion);
surfy[i] = (double)(evtheader.ypos*lenconversion);
}
 
// Save result for later plotting
if(norm)
integralCount[i] += ((double)m)/((double)k);
else
integralCount[i] += m;
inroot->Close();
delete inroot;
}
 
// Update the progress bar
progVal = (float)(75.00/nrfiles)*i;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
nrentries = n;
printf("SurfaceScan(): %d files were selected.\n", nrfiles);
 
// // If only an integral is needed, do not plot and exit here
// if( direction == 0 )
// {
// delete[] integralCount;
// delete[] surfxy;
// delete[] surfz;
// return;
// }
//
// // Current z value and the accumulated counter
// curzval = surfz[0];
// j = 0;
// int acc = 0;
// int zb;
// for(int i = 0; i <= (int)nrfiles; i++)
// {
// // Collect the accumulated integral in order to produce a PDF from a CDF
// // While we are at the same Z value, save under one set
// if( (surfz[i] == curzval) && (acc != nrfiles) )
// {
// integralAcc[j] = integralCount[i];
// if(DBGSIG) printf("IntegSpectrum(): Integral check 1 (i=%d,j=%d,z=%.2lf): %lf\t%lf\n", i, j, surfz[i], integralCount[i], integralAcc[j]);
// j++;
// acc++;
// }
// // When we switch to a new set of Z values and at the end, we must save the previous ones to make 1D edge plots
// else
// {
// // Find minimal and maximal integral values to subtract the offset and normate PDF to 1
// NormateSet(i, j, &minInteg, &maxInteg, integralCount, integralAcc);
//
// if(acc != nrfiles)
// {
// curzval = surfz[i];
// // PDF and CDF plot
// PlotEdgeDistribution(files, i, j, &minInteg, &maxInteg, surfxy, integralAcc, direction, edge2d, edit);
// i--;
// j = 0;
// }
// else
// {
// // PDF and CDF plot
// PlotEdgeDistribution(files, i, j, &minInteg, &maxInteg, surfxy, integralAcc, direction, edge2d, edit);
// i--;
// break;
// }
// }
//
// // Update the progress bar
// progVal = (float)(15.00/nrfiles)*i+75.00;
// analysisProgress->widgetPB->SetPosition(progVal);
// gVirtualX->Update(1);
// }
 
// Make the 2D surface plot
if(edit == 0)
gCanvas = new TCanvas("canv","canv",1100,900);
else
gCanvas = tempAnalysisCanvas->GetCanvas();
 
double range[4];
TGraph2D *gScan2D;
gScan2D = new TGraph2D();
range[0] = TMath::MinElement(nrfiles, surfx);
range[1] = TMath::MaxElement(nrfiles, surfx);
range[2] = TMath::MinElement(nrfiles, surfy);
range[3] = TMath::MaxElement(nrfiles, surfy);
 
for(int i = 0; i < nrfiles; i++)
{
if(DBGSIG)
{
if(surfScanOpt->widgetChBox[1]->IsDown())
printf("SurfaceScan(): %.2lf\t%.2lf\t%lf\n", surfx[i]-range[0], surfy[i]-range[2], integralCount[i]);
else
printf("SurfaceScan(): %.2lf\t%.2lf\t%lf\n", surfx[i], surfy[i], integralCount[i]);
}
 
if(surfScanOpt->widgetChBox[1]->IsDown())
gScan2D->SetPoint(i, surfx[i]-range[0], surfy[i]-range[2], integralCount[i]);
else
gScan2D->SetPoint(i, surfx[i], surfy[i], integralCount[i]);
 
// Update the progress bar
progVal = (float)(9.00/nrfiles)*i+90.00;
analysisProgress->widgetPB->SetPosition(progVal);
gVirtualX->Update(1);
}
 
if(surfScanOpt->widgetChBox[1]->IsDown())
{
range[1] -= range[0];
range[3] -= range[2];
range[0] -= range[0];
range[2] -= range[2];
}
 
gCanvas->cd();
gStyle->SetPalette(1);
gCanvas->SetLeftMargin(0.15);
gCanvas->SetRightMargin(0.126);
gCanvas->SetTopMargin(0.077);
gScan2D->Draw("COLZ");
gCanvas->Modified();
gCanvas->Update();
if(!cleanPlots)
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan2D->SetTitle("Surface scan;X [table units];Y [table units]");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan2D->SetTitle("Surface scan;X [#mum];Y [#mum]");
}
else
{
if(posUnits->widgetCB->GetSelected() == 0)
gScan2D->SetTitle(";X [table units];Y [table units]");
else if(posUnits->widgetCB->GetSelected() == 1)
gScan2D->SetTitle(";X [#mum];Y [#mum]");
}
/* TGaxis *xax = (TGaxis*)gScan2D->GetXaxis();
xax->SetMaxDigits(4);
TGaxis *yax = (TGaxis*)gScan2D->GetYaxis();
yax->SetMaxDigits(4);*/
 
gScan2D->SetNpx((int)resolSurf->widgetNE[0]->GetNumber());
gScan2D->SetNpy((int)resolSurf->widgetNE[1]->GetNumber());
gCanvas->Modified();
gCanvas->Update();
gScan2D->GetXaxis()->SetTitleOffset(1.3);
gScan2D->GetXaxis()->CenterTitle(kTRUE);
gScan2D->GetXaxis()->SetLabelSize(0.027);
gScan2D->GetXaxis()->SetLabelOffset(0.02);
gScan2D->GetXaxis()->SetRangeUser(range[0], range[1]);
gScan2D->GetXaxis()->SetNoExponent(kTRUE);
gScan2D->GetYaxis()->SetTitleOffset(1.9);
gScan2D->GetYaxis()->CenterTitle(kTRUE);
gScan2D->GetYaxis()->SetLabelSize(0.027);
gScan2D->GetXaxis()->SetLabelOffset(0.02);
gScan2D->GetYaxis()->SetRangeUser(range[2], range[3]);
gScan2D->GetYaxis()->SetNoExponent(kTRUE);
gCanvas->Modified();
gCanvas->Update();
 
remove_from_last((char*)files->At(0)->GetTitle(), '_', ctemp);
sprintf(exportname, "%s_surfscan.pdf", ctemp);
gCanvas->SaveAs(exportname);
 
// Update the progress bar
analysisProgress->widgetPB->SetPosition(100.0);
gVirtualX->Update(1);
 
if(edit == 0)
{
delete gScan2D;
delete gCanvas;
}
else if(edit == 1)
{
gCanvas->Modified();
gCanvas->Update();
}
}
}
/lab/sipmscan/trunk/src/connections.cpp
0,0 → 1,2249
#include "../include/sipmscan.h"
#include "../include/workstation.h"
 
#include <stdio.h>
#include <stdlib.h>
 
int retTemp;
 
// Additional functions -------------------------------------
 
// Display the currently selected histogram in the file list
void TGAppMainFrame::DisplayHistogram(char *histfile, int histtype, int opt)
{
char histtime[256];
char ctemp[512];
 
if(DBGSIG)
printf("DisplayHistogram(): Selected file: %s\n", histfile);
 
TCanvas *gCanvas = analysisCanvas->GetCanvas();
 
inroot = TFile::Open(histfile, "READ");
 
TTree *header_data, *meas_data;
inroot->GetObject("header_data", header_data);
inroot->GetObject("meas_data", meas_data);
 
// Reading the header
header_data->SetBranchAddress("nrch", &evtheader.nrch);
header_data->GetEntry(0);
header_data->SetBranchAddress("timestamp", &evtheader.timestamp);
header_data->GetEntry(0);
header_data->SetBranchAddress("biasvolt", &evtheader.biasvolt);
header_data->GetEntry(0);
header_data->SetBranchAddress("xpos", &evtheader.xpos);
header_data->GetEntry(0);
header_data->SetBranchAddress("ypos", &evtheader.ypos);
header_data->GetEntry(0);
header_data->SetBranchAddress("zpos", &evtheader.zpos);
header_data->GetEntry(0);
header_data->SetBranchAddress("temperature", &evtheader.temperature);
header_data->GetEntry(0);
if( header_data->FindBranch("angle") )
{
header_data->SetBranchAddress("angle", &evtheader.angle);
header_data->GetEntry(0);
}
header_data->SetBranchAddress("laserinfo", &evtheader.laserinfo);
header_data->GetEntry(0);
 
// Change timestamp to local time
GetTime(evtheader.timestamp, histtime);
 
// Displaying header information debug
if(DBGSIG)
{
printf("DisplayHistogram(): Opened file header information:\n");
printf("- Number of channels (ADC and TDC are considered as separate channels): %d\n", evtheader.nrch);
printf("- Timestamp: %d (%s)\n", evtheader.timestamp, histtime);
printf("- Bias voltage: %lf\n", evtheader.biasvolt);
printf("- Table position (X,Y,Z): %d, %d, %d\n", evtheader.xpos, evtheader.ypos, evtheader.zpos);
if(evtheader.temperature)
printf("- Temperature: %lf\n", evtheader.temperature);
if( header_data->FindBranch("angle") )
printf("- Incidence angle: %lf\n", evtheader.angle);
else
printf("- Incidence angle: No angle information!\n");
printf("- Laser and filter settings: %s\n", evtheader.laserinfo);
}
 
// Displaying header information on the GUI
dispTime->widgetTE->SetText(histtime);
dispBias->widgetNE[0]->SetNumber(evtheader.biasvolt);
sprintf(ctemp, "%d, %d, %d", evtheader.xpos, evtheader.ypos, evtheader.zpos);
dispPos->widgetTE->SetText(ctemp);
if(evtheader.temperature)
dispTemp->widgetNE[0]->SetNumber(evtheader.temperature);
else
dispTemp->widgetNE[0]->SetNumber(0.0);
if( header_data->FindBranch("angle") )
dispAngle->widgetNE[0]->SetNumber(evtheader.angle);
else
dispAngle->widgetNE[0]->SetNumber(0.0);
dispLaser->widgetTE->SetText(evtheader.laserinfo);
 
selectCh->widgetNE[0]->SetLimitValues(0, (evtheader.nrch/2)-1);
 
// Redraw the histograms
int j;
char rdc[256];
char rdcsel[256];
 
j = selectCh->widgetNE[0]->GetNumber();
 
printf("Found %d data points.\n", (int)meas_data->GetEntries());
 
gCanvas->cd();
double range[4];
range[0] = adcRange->widgetNE[0]->GetNumber();
range[1] = adcRange->widgetNE[1]->GetNumber();
range[2] = tdcRange->widgetNE[0]->GetNumber();
range[3] = tdcRange->widgetNE[1]->GetNumber();
 
// ADC histogram
if(histtype == 0)
{
if( range[0] == range[1] )
sprintf(rdc, "ADC%d>>%s", j, histname);
else
sprintf(rdc, "ADC%d>>%s(%d,%lf,%lf)", j, histname, (int)(range[1]-range[0]), range[0]-0.5, range[1]-0.5);
 
sprintf(rdcsel, "(TDC%d>%lf)&&(TDC%d<%lf)", j, range[2]*tdctimeconversion, j, range[3]*tdctimeconversion);
meas_data->Draw(rdc, rdcsel);
 
sprintf(rdc, "ADC%d, Vbias=%.3lf, TDC=(%.2lf,%.2lf);ADC;", j, evtheader.biasvolt, range[2], range[3]);
TH1F *histtemp = (TH1F*)gCanvas->GetPrimitive(histname);
if(!cleanPlots)
histtemp->SetTitle(rdc);
else
histtemp->SetTitle(";ADC;");
histtemp->GetXaxis()->SetLabelSize(0.025);
histtemp->GetXaxis()->CenterTitle(kTRUE);
histtemp->GetYaxis()->SetLabelSize(0.025);
if(cleanPlots)
{
TGaxis *yax = (TGaxis*)histtemp->GetYaxis();
yax->SetMaxDigits(4);
}
 
gCanvas->Modified();
gCanvas->Update();
 
if( yRange->widgetNE[0]->GetNumber() != yRange->widgetNE[1]->GetNumber() )
{
if( (histOpt->widgetChBox[0]->IsDown()) && (yRange->widgetNE[0]->GetNumber() <= 0) )
{
histtemp->GetYaxis()->SetRangeUser(0.5, yRange->widgetNE[1]->GetNumber());
yRange->widgetNE[0]->SetNumber(0.5);
logChange = 1;
}
else
{
gCanvas->SetLogy(kFALSE);
if(logChange == 1)
{
yRange->widgetNE[0]->SetNumber(0.0);
logChange = 0;
}
histtemp->GetYaxis()->SetRangeUser(yRange->widgetNE[0]->GetNumber(), yRange->widgetNE[1]->GetNumber());
}
}
 
TPaveStats *stats = (TPaveStats*)histtemp->FindObject("stats");
if(!cleanPlots)
{
stats->SetX1NDC(0.84); stats->SetX2NDC(0.97);
stats->SetY1NDC(0.87); stats->SetY2NDC(0.97);
}
else
{
stats->SetX1NDC(1.1); stats->SetX2NDC(1.3);
stats->SetY1NDC(1.1); stats->SetY2NDC(1.3);
}
}
// TDC histogram
else if(histtype == 1)
{
if( range[0] == range[1] )
sprintf(rdc, "(TDC%d/%lf)>>%s", j, tdctimeconversion, histname);
else
sprintf(rdc, "(TDC%d/%lf)>>%s(%d,%lf,%lf)", j, tdctimeconversion, histname, (int)((range[3]-range[2])*tdctimeconversion), range[2], range[3]);
 
sprintf(rdcsel, "(TDC%d>%lf)&&(TDC%d<%lf)", j, range[2]*tdctimeconversion, j, range[3]*tdctimeconversion);
meas_data->Draw(rdc, rdcsel);
 
sprintf(rdc, "TDC%d, Vbias=%.3lf, TDC=(%.2lf,%.2lf);Time (TDC channel) [ns];", j, evtheader.biasvolt, range[2], range[3]);
TH1F *histtemp = (TH1F*)gCanvas->GetPrimitive(histname);
if(!cleanPlots)
histtemp->SetTitle(rdc);
else
histtemp->SetTitle(";Time (TDC channel) [ns];");
histtemp->GetXaxis()->SetLabelSize(0.025);
histtemp->GetXaxis()->CenterTitle(kTRUE);
histtemp->GetYaxis()->SetLabelSize(0.025);
if(cleanPlots)
{
TGaxis *yax = (TGaxis*)histtemp->GetYaxis();
yax->SetMaxDigits(4);
}
 
gCanvas->Modified();
gCanvas->Update();
 
if( yRange->widgetNE[0]->GetNumber() != yRange->widgetNE[1]->GetNumber() )
{
if( (histOpt->widgetChBox[0]->IsDown()) && (yRange->widgetNE[0]->GetNumber() <= 0) )
{
histtemp->GetYaxis()->SetRangeUser(0.5, yRange->widgetNE[1]->GetNumber());
yRange->widgetNE[0]->SetNumber(0.5);
logChange = 1;
}
else
{
gCanvas->SetLogy(kFALSE);
if(logChange == 1)
{
yRange->widgetNE[0]->SetNumber(0.0);
logChange = 0;
}
histtemp->GetYaxis()->SetRangeUser(yRange->widgetNE[0]->GetNumber(), yRange->widgetNE[1]->GetNumber());
}
}
 
TPaveStats *stats = (TPaveStats*)histtemp->FindObject("stats");
if(!cleanPlots)
{
stats->SetX1NDC(0.84); stats->SetX2NDC(0.97);
stats->SetY1NDC(0.87); stats->SetY2NDC(0.97);
}
else
{
stats->SetX1NDC(1.1); stats->SetX2NDC(1.3);
stats->SetY1NDC(1.1); stats->SetY2NDC(1.3);
}
}
// ADC vs. TDC histogram
else if(histtype == 2)
{
if( ((range[0] == range[1]) && (range[2] == range[3])) || (range[2] == range[3]) || (range[0] == range[1]) )
sprintf(rdc, "(TDC%d/%lf):ADC%d>>%s", j, tdctimeconversion, j, histname);
else
sprintf(rdc, "(TDC%d/%lf):ADC%d>>%s(%d,%lf,%lf,%d,%lf,%lf)", j, tdctimeconversion, j, histname, (int)(range[1]-range[0])/2, range[0]-0.5, range[1]-0.5, (int)((range[3]-range[2])*tdctimeconversion)/2, range[2], range[3]);
meas_data->Draw(rdc,"","COLZ");
 
sprintf(rdc, "ADC/TDC%d, Vbias=%.3lf, TDC=(%.2lf,%.2lf);ADC;TDC", j, evtheader.biasvolt, range[2], range[3]);
TH2F *histtemp = (TH2F*)gCanvas->GetPrimitive(histname);
if(!cleanPlots)
histtemp->SetTitle(rdc);
else
histtemp->SetTitle(";ADC;Time (TDC channel) [ns]");
histtemp->GetXaxis()->SetLabelSize(0.025);
histtemp->GetXaxis()->CenterTitle(kTRUE);
histtemp->GetYaxis()->SetLabelSize(0.025);
histtemp->GetYaxis()->CenterTitle(kTRUE);
histtemp->GetYaxis()->SetTitleOffset(1.35);
if(cleanPlots)
{
TGaxis *yax = (TGaxis*)histtemp->GetYaxis();
yax->SetMaxDigits(4);
}
 
gCanvas->Modified();
gCanvas->Update();
 
TPaveStats *stats = (TPaveStats*)histtemp->FindObject("stats");
stats->SetX1NDC(1.1); stats->SetX2NDC(1.3);
stats->SetY1NDC(1.1); stats->SetY2NDC(1.3);
 
TPaletteAxis *gpalette = (TPaletteAxis*)histtemp->GetListOfFunctions()->FindObject("palette");
gpalette->SetLabelSize(0.022);
}
 
if(histtype < 2)
{
if( histOpt->widgetChBox[0]->IsDown() )
gCanvas->SetLogy(kTRUE);
else if( !histOpt->widgetChBox[0]->IsDown() )
gCanvas->SetLogy(kFALSE);
}
else
gCanvas->SetLogy(kFALSE);
 
gCanvas->Modified();
gCanvas->Update();
 
delete header_data;
delete meas_data;
 
// Delete the opened file when we just display it in the analysis canvas (otherwise wait for histogram save)
if(opt != 1)
delete inroot;
 
// If you close the opened file (delete inroot), the data can not be accessed by other functions (any time we wish to use the data directly from histogram, we need to call the DisplayHistogram function -> using different opt to determine what we need to do)
}
 
// Start a measurement (acquisition from CAMAC)
void TGAppMainFrame::RunMeas(void *ptr, int runCase, int &scanon)
{
int vscan = 0, pscan = 0, zscan = 0, ascan = 0;
if(scansOn->widgetChBox[0]->IsDown()) vscan = 1;
if(scansOn->widgetChBox[1]->IsDown()) pscan = 1;
if(scansOn->widgetChBox[2]->IsDown()) zscan = 1;
if(scansOn->widgetChBox[3]->IsDown()) ascan = 1;
 
printf("Start of Run, run case %d\n", runCase);
 
float progVal;
 
char ctemp[256];
char ctemp2[256];
char fname[256];
int itemp = 0;
TH1F *liveHist;
 
float minVoltage, maxVoltage, stepVoltage, diffVoltage;
float minXpos, maxXpos, stepXpos, diffXpos;
float minYpos, maxYpos, stepYpos, diffYpos;
float minZpos, maxZpos, stepZpos, diffZpos;
float minAlpha, maxAlpha, stepAlpha, diffAlpha;
 
minVoltage = vOutStart->widgetNE[0]->GetNumber();
maxVoltage = vOutStop->widgetNE[0]->GetNumber();
diffVoltage = abs(maxVoltage - minVoltage);
stepVoltage = abs(vOutStep->widgetNE[0]->GetNumber());
minXpos = xPosMin->widgetNE[0]->GetNumber();
maxXpos = xPosMax->widgetNE[0]->GetNumber();
diffXpos = abs(maxXpos - minXpos);
stepXpos = abs(xPosStep->widgetNE[0]->GetNumber());
minYpos = yPosMin->widgetNE[0]->GetNumber();
maxYpos = yPosMax->widgetNE[0]->GetNumber();
diffYpos = abs(maxYpos - minYpos);
stepYpos = abs(yPosStep->widgetNE[0]->GetNumber());
minZpos = zPosMin->widgetNE[0]->GetNumber();
maxZpos = zPosMax->widgetNE[0]->GetNumber();
diffZpos = abs(maxZpos - minZpos);
stepZpos = abs(zPosStep->widgetNE[0]->GetNumber());
minAlpha = rotPosMin->widgetNE[0]->GetNumber();
maxAlpha = rotPosMax->widgetNE[0]->GetNumber();
diffAlpha = abs(maxAlpha - minAlpha);
stepAlpha = abs(rotPosStep->widgetNE[0]->GetNumber());
 
remove_ext((char*)fileName->widgetTE->GetText(), ctemp);
 
// TODO - angle scan + voltage scan
// Voltage or surface scan
if( vscan || pscan || ascan )
{
// No Z scan, No angle scan
if(!zscan && !ascan)
{
// When we have a voltage scan
if( vscan && (stepVoltage > 0.) )
SeqNumber(runCase, (int)diffVoltage/stepVoltage, ctemp2);
// With only a surface scan
else if(pscan)
{
if( stepXpos == 0 )
itemp = 1;
else
itemp = (int)diffXpos/stepXpos;
 
if( stepYpos == 0 )
itemp *= 1;
else
itemp *= (int)diffYpos/stepYpos;
SeqNumber(runCase, itemp, ctemp2);
}
sprintf(fname, "%s_%s%s", ctemp, ctemp2, histext);
}
// With Z scan, No angle scan
else if(zscan && !ascan)
{
SeqNumber((int)zPos->widgetNE[0]->GetNumber(), maxZpos, ctemp2);
 
// Voltage scan is on
if( vscan && (stepVoltage > 0.) )
{
sprintf(fname, "%s_z%s_", ctemp, ctemp2);
SeqNumber(runCase, (int)diffVoltage/stepVoltage+1, ctemp2);
strcat(fname, ctemp2);
strcat(fname, histext);
}
// Surface scan is on
else if(pscan)
{
sprintf(fname, "%s_z%s_", ctemp, ctemp2);
 
if( stepXpos == 0 )
itemp = 1;
else
itemp = (int)diffXpos/stepXpos+1;
 
if( stepYpos == 0 )
itemp *= 1;
else
itemp *= (int)diffYpos/stepYpos+1;
SeqNumber(runCase, itemp, ctemp2);
strcat(fname, ctemp2);
strcat(fname, histext);
}
// Just Z scan
else
sprintf(fname, "%s_z%s%s", ctemp, ctemp2, histext);
}
// No Z scan, With angle scan
else if(!zscan && ascan)
{
SeqNumber(runCase, (int)diffAlpha/stepAlpha, ctemp2);
 
// Voltage scan is on
if( vscan && (stepVoltage > 0.) )
{
sprintf(fname, "%s_phi%s_", ctemp, ctemp2);
SeqNumber(runCase, (int)diffVoltage/stepVoltage+1, ctemp2);
strcat(fname, ctemp2);
strcat(fname, histext);
}
// Just angle scan
else
sprintf(fname, "%s_phi%s%s", ctemp, ctemp2, histext);
}
}
// All the rest
else if(!vscan && !pscan)
sprintf(fname, "%s%s", ctemp, histext);
 
// Check if set voltage is below the hard limit
if( vOut->widgetNE[0]->GetNumber() > vHardlimit->widgetNE[0]->GetNumber() )
{
printf("Voltage hard limit triggered (%lf > %lf)!\n", vOut->widgetNE[0]->GetNumber(), vHardlimit->widgetNE[0]->GetNumber() );
vOut->widgetNE[0]->SetNumber( vHardlimit->widgetNE[0]->GetNumber() );
}
 
printf("Output file is (runCase = %d): %s\n", runCase, fname);
 
// Writing to output file
outroot = TFile::Open(fname, "RECREATE");
 
TTree *header_data = new TTree("header_data", "Header information for the measurement.");
TTree *meas_data = new TTree("meas_data", "Saved ADC and TDC measurement data.");
TTree *scope_data = new TTree("scope_data", "Saved scope measurement data.");
 
// Branches for the header
header_data->Branch("nrch", &evtheader.nrch, "nrch/I");
header_data->Branch("timestamp", &evtheader.timestamp, "timestamp/I");
header_data->Branch("biasvolt", &evtheader.biasvolt, "biasvolt/D");
header_data->Branch("xpos", &evtheader.xpos, "xpos/I");
header_data->Branch("ypos", &evtheader.ypos, "ypos/I");
header_data->Branch("zpos", &evtheader.zpos, "zpos/I");
header_data->Branch("temperature", &evtheader.temperature, "temperature/D");
header_data->Branch("angle", &evtheader.angle, "angle/D");
header_data->Branch("laserinfo", &evtheader.laserinfo, "laserinfo/C");
 
evtheader.nrch = (int)NCH->widgetNE[0]->GetNumber()*2;
evtheader.timestamp = (int)time(NULL);
evtheader.biasvolt = (double)vOut->widgetNE[0]->GetNumber();
if(posUnits->widgetCB->GetSelected() == 0)
{
evtheader.xpos = (int)xPos->widgetNE[0]->GetNumber();
evtheader.ypos = (int)yPos->widgetNE[0]->GetNumber();
evtheader.zpos = (int)zPos->widgetNE[0]->GetNumber();
}
else if(posUnits->widgetCB->GetSelected() == 1)
{
evtheader.xpos = (int)xPos->widgetNE[0]->GetNumber()/lenconversion;
evtheader.ypos = (int)yPos->widgetNE[0]->GetNumber()/lenconversion;
evtheader.zpos = (int)zPos->widgetNE[0]->GetNumber()/lenconversion;
}
evtheader.temperature = (double)chtemp->widgetNE[0]->GetNumber();
if(rotUnits->widgetCB->GetSelected() == 0)
evtheader.angle = (double)rotPos->widgetNE[0]->GetNumber()*rotconversion;
else if(rotUnits->widgetCB->GetSelected() == 1)
evtheader.angle = (double)rotPos->widgetNE[0]->GetNumber();
sprintf(evtheader.laserinfo, "%s", laserInfo->widgetTE->GetText());
 
char histtime[256];
GetTime(evtheader.timestamp, histtime);
 
printf("Save file header information:\n");
printf("- Number of channels: %d\n", evtheader.nrch);
printf("- Timestamp: %d (%s)\n", evtheader.timestamp, histtime);
printf("- Bias voltage: %lf\n", evtheader.biasvolt);
printf("- Table position (X,Y,Z): %d, %d, %d\n", evtheader.xpos, evtheader.ypos, evtheader.zpos);
printf("- Temperature: %lf\n", evtheader.temperature);
printf("- Incidence angle: %lf\n", evtheader.angle);
printf("- Laser and filter settings: %s\n", evtheader.laserinfo);
 
header_data->Fill();
 
// Branches for ADC and TDC data
for(int i = 0; i < evtheader.nrch/2; i++)
{
sprintf(ctemp, "ADC%d", i);
sprintf(fname, "ADC%d/I", i);
meas_data->Branch(ctemp, &evtdata.adcdata[i], fname);
 
sprintf(ctemp, "TDC%d", i);
sprintf(fname, "TDC%d/I", i);
meas_data->Branch(ctemp, &evtdata.tdcdata[i], fname);
}
 
//TODO
// Initialize the scope before measurement
/* if( sCamaclink->IsDown() )
InitializeScope();*/
 
// Branch for scope measurement data
/* if(gScopeDaq->scopeUseType == 2) // only if we select waveform measurement
{
if(gScopeDaq->scopeMeasSel == 0)
scope_data->Branch("amp", &evtmeas.measdata, "amp/D");
else if(gScopeDaq->scopeMeasSel == 1)
scope_data->Branch("area", &evtmeas.measdata, "area/D");
else if(gScopeDaq->scopeMeasSel == 2)
scope_data->Branch("delay", &evtmeas.measdata, "delay/D");
else if(gScopeDaq->scopeMeasSel == 3)
scope_data->Branch("fall", &evtmeas.measdata, "fall/D");
else if(gScopeDaq->scopeMeasSel == 4)
scope_data->Branch("freq", &evtmeas.measdata, "freq/D");
else if(gScopeDaq->scopeMeasSel == 5)
scope_data->Branch("max", &evtmeas.measdata, "max/D");
else if(gScopeDaq->scopeMeasSel == 6)
scope_data->Branch("mean", &evtmeas.measdata, "mean/D");
else if(gScopeDaq->scopeMeasSel == 7)
scope_data->Branch("min", &evtmeas.measdata, "min/D");
else if(gScopeDaq->scopeMeasSel == 8)
scope_data->Branch("pk2p", &evtmeas.measdata, "pk2p/D");
else if(gScopeDaq->scopeMeasSel == 9)
scope_data->Branch("pwidth", &evtmeas.measdata, "pwidth/D");
else if(gScopeDaq->scopeMeasSel == 10)
scope_data->Branch("rise", &evtmeas.measdata, "rise/D");
}*/
 
int neve = (int) evtNum->widgetNE[0]->GetNumber();
int allEvt, zProg;
zProg = 1;
 
#if WORKSTAT == 'I'
#else
// ONLY FOR TESTING!
TRandom *randNum = new TRandom();
randNum->SetSeed(0);
// ONLY FOR TESTING!
#endif
 
// Initialize the CAMAC
if (gDaq)
{
if(scanon == 0)
{
gDaq->init(evtheader.nrch);
scanon = 1;
}
gDaq->fStop=0;
 
// Set the stopwatch
clock_t clkt1;
 
// Prepare histogram for live histogram update
int liven;
TCanvas *gCanvas;
if(liveUpdate && (!vscan && !pscan && !zscan && !ascan))
{
gCanvas = measCanvas->GetCanvas();
gCanvas->SetGrid();
gCanvas->cd();
liveHist = new TH1F(histname,"",(int)TMath::Sqrt(neve),0,0);
liven = 1;
}
 
// Start gathering
gDaq->start();
 
for (int n=0;n<neve && !gDaq->fStop ;/*n++*/)
{
int nb = gDaq->event(gBuf,BSIZE);
 
#if WORKSTAT == 'I'
#else
// ONLY FOR TESTING!
for(int i=0; i < evtheader.nrch; i++)
{
if(i == 1)
gBuf[i] = randNum->Gaus(1500,300);
else if(i == 0)
gBuf[i] = randNum->Poisson(2500);
}
// ONLY FOR TESTING!
#endif
if (nb<=0) n--;
 
int nc=0;
 
while ( (nb>0) && (n<neve) )
{
for(int i = 0; i < evtheader.nrch; i++)
{
unsigned short adc = gBuf[i+nc]&0xFFFF;
if(i % 2 == 0) // TDC
evtdata.tdcdata[i/2] = (int)adc;
else if(i % 2 == 1) // ADC
evtdata.adcdata[i/2] = (int)adc;
 
// Start plotting the scope waveform
/* if( (gScopeDaq->scopeUseType == 1) && (sCamaclink->IsDown()) )
StartScopeAcq();*/ // TODO
}
meas_data->Fill();
n++;
sleep(1);
 
// Start making a scope measurement
/* if( (gScopeDaq->scopeUseType == 2) && (sCamaclink->IsDown()) )
{
StartScopeAcq();
evtmeas.measdata = gScopeDaq->measubuf;
}
scope_data->Fill();*/ // TODO
 
// Start filling the histogram (only in normal single scan)
if(liveUpdate && (!vscan && !pscan && !zscan && !ascan))
{
liveHist->Fill(evtdata.adcdata[0]);
if( n == (neve*liven)/10 )
{
gCanvas->cd();
liveHist->Draw("");
gCanvas->Modified();
gCanvas->Update();
liven++;
}
}
nc += evtheader.nrch;
nb -= evtheader.nrch;
}
 
MyTimer();
allEvt = n;
if (gSystem->ProcessEvents()) printf("Run Interrupted\n");
 
if( acqStarted && (n == (neve*zProg)/10) && (!vscan && !pscan && !zscan && !ascan) )
{
// Progress the progress bar
progVal = (float)zProg*10;
measProgress->widgetPB->SetPosition(progVal);
 
// Calculate the remaining time
TimeEstimate(clkt0, timet0, progVal, ctemp, 0);
printf("End time: %s\n", ctemp);
measProgress->widgetTE->SetText(ctemp);
 
gVirtualX->Update(1);
zProg++;
}
}
 
printf("Number of gathered events: %d\n", allEvt);
measProgress->widgetTB[0]->SetText("Start acquisition");
acqStarted = false;
 
gDaq->stop();
}
 
printf("End of Run neve=%d\n",neve);
 
header_data->Write();
meas_data->Write();
// scope_data->Write(); // TODO
delete header_data;
delete meas_data;
delete scope_data;
 
// Remove the histogram
if(liveUpdate && (!vscan && !pscan && !zscan && !ascan))
delete liveHist;
 
 
outroot->Close();
}
 
int TGAppMainFrame::MyTimer()
{
char cmd[100];
GetTime(-1, cmd);
if (timeStamp) timeStamp->widgetTE->SetText(cmd);
return 0;
}
 
// Additional functions -------------------------------------
 
// Settings pane connections --------------------------------
 
// Enable or disable scans
void TGAppMainFrame::EnableScan(int type)
{
// Voltage scan
if(type == 0)
{
if(scansOn->widgetChBox[type]->IsOn())
{
vOutStart->widgetNE[0]->SetState(kTRUE);
vOutStop->widgetNE[0]->SetState(kTRUE);
vOutStep->widgetNE[0]->SetState(kTRUE);
}
else
{
vOutStart->widgetNE[0]->SetState(kFALSE);
vOutStop->widgetNE[0]->SetState(kFALSE);
vOutStep->widgetNE[0]->SetState(kFALSE);
}
}
// Surface (X, Y axis) scan
else if(type == 1)
{
if(scansOn->widgetChBox[type]->IsOn())
{
xPosMin->widgetNE[0]->SetState(kTRUE);
xPosMax->widgetNE[0]->SetState(kTRUE);
xPosStep->widgetNE[0]->SetState(kTRUE);
yPosMin->widgetNE[0]->SetState(kTRUE);
yPosMax->widgetNE[0]->SetState(kTRUE);
yPosStep->widgetNE[0]->SetState(kTRUE);
}
else
{
xPosMin->widgetNE[0]->SetState(kFALSE);
xPosMax->widgetNE[0]->SetState(kFALSE);
xPosStep->widgetNE[0]->SetState(kFALSE);
yPosMin->widgetNE[0]->SetState(kFALSE);
yPosMax->widgetNE[0]->SetState(kFALSE);
yPosStep->widgetNE[0]->SetState(kFALSE);
}
}
// Z axis scan
else if(type == 2)
{
if(scansOn->widgetChBox[type]->IsOn())
{
zPosMin->widgetNE[0]->SetState(kTRUE);
zPosMax->widgetNE[0]->SetState(kTRUE);
zPosStep->widgetNE[0]->SetState(kTRUE);
}
else
{
zPosMin->widgetNE[0]->SetState(kFALSE);
zPosMax->widgetNE[0]->SetState(kFALSE);
zPosStep->widgetNE[0]->SetState(kFALSE);
}
}
// Incidence angle scan
else if(type == 3)
{
if(scansOn->widgetChBox[type]->IsOn())
{
rotPosMin->widgetNE[0]->SetState(kTRUE);
rotPosMax->widgetNE[0]->SetState(kTRUE);
rotPosStep->widgetNE[0]->SetState(kTRUE);
}
else
{
rotPosMin->widgetNE[0]->SetState(kFALSE);
rotPosMax->widgetNE[0]->SetState(kFALSE);
rotPosStep->widgetNE[0]->SetState(kFALSE);
}
}
}
 
// Apply the upper voltage limit from settings pane to main window
void TGAppMainFrame::VoltageLimit()
{
vOut->widgetNE[0]->SetLimitValues(0, vHardlimit->widgetNE[0]->GetNumber() );
}
 
// Select the table position units to be used (1 = 0.3595 micron)
void TGAppMainFrame::ChangeUnits(int type)
{
int pos[12], poslim[3], chng = 0;
double micro[12], microlim[3];
 
TGNumberEntry *posEntries[12];
posEntries[0] = (TGNumberEntry*)xPos->widgetNE[0];
posEntries[1] = (TGNumberEntry*)yPos->widgetNE[0];
posEntries[2] = (TGNumberEntry*)zPos->widgetNE[0];
posEntries[3] = (TGNumberEntry*)xPosMin->widgetNE[0];
posEntries[4] = (TGNumberEntry*)xPosMax->widgetNE[0];
posEntries[5] = (TGNumberEntry*)xPosStep->widgetNE[0];
posEntries[6] = (TGNumberEntry*)yPosMin->widgetNE[0];
posEntries[7] = (TGNumberEntry*)yPosMax->widgetNE[0];
posEntries[8] = (TGNumberEntry*)yPosStep->widgetNE[0];
posEntries[9] = (TGNumberEntry*)zPosMin->widgetNE[0];
posEntries[10] = (TGNumberEntry*)zPosMax->widgetNE[0];
posEntries[11] = (TGNumberEntry*)zPosStep->widgetNE[0];
 
// Table position values
if(type == 0)
{
// Check if we had microns before
if(posEntries[0]->GetNumStyle() == TGNumberFormat::kNESRealTwo)
chng = 1;
 
// Change to table position values
if(chng == 1)
{
for(int i = 0; i < 12; i++)
{
if(posEntries[i]->GetNumber() == 0.0)
pos[i] = 0;
else
pos[i] = (int)posEntries[i]->GetNumber()/lenconversion;
}
 
poslim[0] = -100;
poslim[1] = 215000;
poslim[2] = 375000;
 
for(int i = 0; i < 12; i++)
{
posEntries[i]->SetNumStyle(TGNumberFormat::kNESInteger);
if( (i > 8) || (i == 2) ) // limits for Z axis (longer table)
posEntries[i]->SetLimits(TGNumberFormat::kNELLimitMinMax, poslim[0], poslim[2]);
else
posEntries[i]->SetLimits(TGNumberFormat::kNELLimitMinMax, poslim[0], poslim[1]);
 
posEntries[i]->SetNumber(pos[i]);
}
}
}
// Microns
else if(type == 1)
{
// Check if we had table position values before
if(posEntries[0]->GetNumStyle() == TGNumberFormat::kNESInteger)
chng = 1;
 
// Change to microns
if(chng == 1)
{
for(int i = 0; i < 12; i++)
{
if(posEntries[i]->GetNumber() == 0.0)
micro[i] = 0.;
else
micro[i] = (double)posEntries[i]->GetNumber()*lenconversion;
}
microlim[0] = (double)-100*lenconversion;
microlim[1] = (double)215000*lenconversion;
microlim[2] = (double)375000*lenconversion;
for(int i = 0; i < 12; i++)
{
posEntries[i]->SetNumStyle(TGNumberFormat::kNESRealTwo);
if( (i > 8) || (i == 2) ) // limits for Z axis (longer table)
posEntries[i]->SetLimits(TGNumberFormat::kNELLimitMinMax, microlim[0], microlim[2]);
else
posEntries[i]->SetLimits(TGNumberFormat::kNELLimitMinMax, microlim[0], microlim[1]);
posEntries[i]->SetNumber(micro[i]);
}
}
}
}
 
// Select the rotation units to be used (1 = 6.3281/3600 degrees)
void TGAppMainFrame::ChangeUnitsRot(int type)
{
int rot[4], rotlim[2], chng = 0;
double deg[4], deglim[2];
 
TGNumberEntry *rotEntries[4];
rotEntries[0] = (TGNumberEntry*)rotPos->widgetNE[0];
rotEntries[1] = (TGNumberEntry*)rotPosMin->widgetNE[0];
rotEntries[2] = (TGNumberEntry*)rotPosMax->widgetNE[0];
rotEntries[3] = (TGNumberEntry*)rotPosStep->widgetNE[0];
 
// Rotation values
if(type == 0)
{
// Check if we had degrees before
if(rotEntries[0]->GetNumStyle() == TGNumberFormat::kNESRealTwo)
chng = 1;
 
// Change to rotation values
if(chng == 1)
{
for(int i = 0; i < 4; i++)
{
if(rotEntries[i]->GetNumber() == 0.0)
rot[i] = 0;
else
rot[i] = (int)rotEntries[i]->GetNumber()/rotconversion;
}
 
rotlim[0] = (int)-180/rotconversion;
rotlim[1] = (int)180/rotconversion;
 
for(int i = 0; i < 4; i++)
{
rotEntries[i]->SetNumStyle(TGNumberFormat::kNESInteger);
rotEntries[i]->SetLimits(TGNumberFormat::kNELLimitMinMax, rotlim[0], rotlim[1]);
 
rotEntries[i]->SetNumber(rot[i]);
}
}
}
// Degree
else if(type == 1)
{
// Check if we had table position values before
if(rotEntries[0]->GetNumStyle() == TGNumberFormat::kNESInteger)
chng = 1;
 
// Change to degrees
if(chng == 1)
{
for(int i = 0; i < 4; i++)
{
if(rotEntries[i]->GetNumber() == 0)
deg[i] = 0.;
else
deg[i] = (double)rotEntries[i]->GetNumber()*rotconversion;
}
deglim[0] = -180.;
deglim[1] = 180.;
for(int i = 0; i < 4; i++)
{
rotEntries[i]->SetNumStyle(TGNumberFormat::kNESRealTwo);
rotEntries[i]->SetLimits(TGNumberFormat::kNELLimitMinMax, deglim[0], deglim[1]);
rotEntries[i]->SetNumber(deg[i]);
}
}
}
}
 
// Enable display canvas to have a live update of histogram
void TGAppMainFrame::EnableLiveUpdate()
{
liveUpdate = liveDisp->widgetChBox[0]->IsDown();
}
 
// Settings pane connections --------------------------------
 
// Main measurement window connections ----------------------
 
// Get the currently selected channel
int TGAppMainFrame::GetChannel()
{
int selectedOutput;
if(vOutCh->widgetCB->GetSelected() < 8) selectedOutput = (vOutCh->widgetCB->GetSelected())+1;
else if( (vOutCh->widgetCB->GetSelected() >= 8) && (vOutCh->widgetCB->GetSelected() < 16) ) selectedOutput = (vOutCh->widgetCB->GetSelected())+93;
else selectedOutput = 1;
 
return selectedOutput;
}
 
// Set, get or reset the output voltage
void TGAppMainFrame::VoltOut(int opt)
{
char cmd[256];
 
// Set the selected voltage
if(opt == 0)
{
int outOn;
float outputVoltage;
outputVoltage = vOut->widgetNE[0]->GetNumber();
if(vOutOpt->widgetChBox[1]->IsOn()) outOn = 1;
else outOn = 0;
fflush(stdout);
sprintf(cmd, "%s/src/mpod/mpod_voltage.sh -o %d -v %f -s %d", rootdir, GetChannel(), outputVoltage, outOn);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
fflush(stdout);
}
// Get current voltage
else if(opt == 1)
{
fflush(stdout);
sprintf(cmd, "%s/src/mpod/mpod_voltage.sh -o %d -g > %s/settings/curvolt.txt", rootdir, GetChannel(), rootdir);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
fflush(stdout);
 
#if WORKSTAT == 'I'
FILE* fvolt;
double dtemp;
char ctemp[24];
sprintf(cmd, "%s/settings/curvolt.txt", rootdir);
fvolt = fopen(cmd, "r");
if(fvolt != NULL)
{
sprintf(cmd, "WIENER-CRATE-MIB::outputVoltage.u%d = Opaque: Float: %s V\n", GetChannel()-1, "%lf" );
retTemp = fscanf(fvolt, cmd, &dtemp);
vOut->widgetNE[0]->SetNumber(dtemp);
sprintf(cmd, "WIENER-CRATE-MIB::outputSwitch.u%d = INTEGER: %s\n", GetChannel()-1, "%s" );
retTemp = fscanf(fvolt, cmd, ctemp);
if( strcmp(ctemp, "On(1)") == 0 )
vOutOpt->widgetChBox[1]->SetState(kButtonDown);
else if( strcmp(ctemp, "Off(0)") == 0 )
vOutOpt->widgetChBox[1]->SetState(kButtonUp);
}
fclose(fvolt);
#endif
}
// Reset output voltage (if stuck in interlock)
else if(opt == 2)
{
vOut->widgetNE[0]->SetNumber(0.000);
vOutOpt->widgetChBox[1]->SetState(kButtonUp);
 
fflush(stdout);
sprintf(cmd, "%s/src/mpod/mpod_voltage.sh -r %d", rootdir, GetChannel());
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
fflush(stdout);
}
}
 
// Set output voltage polarity to negative
void TGAppMainFrame::NegativePolarity()
{
double newHardlimit;
int polar = 0; // 0 = positive, 1 = negative
 
if(vOutOpt->widgetChBox[0]->IsOn())
polar = 1;
else
polar = 0;
 
// Set hard limit to the negative version of what it was before
if( (vHardlimit->widgetNE[0]->GetNumber() > 0.) && (polar == 1) )
newHardlimit = -(vHardlimit->widgetNE[0]->GetNumber());
else if( (vHardlimit->widgetNE[0]->GetNumber() < 0.) && (polar == 0) )
newHardlimit = -(vHardlimit->widgetNE[0]->GetNumber());
else if(vHardlimit->widgetNE[0]->GetNumber() == 0.)
newHardlimit = 0.;
else
newHardlimit = vHardlimit->widgetNE[0]->GetNumber();
 
// Apropriately set the limit to the output voltage number entry
vHardlimit->widgetNE[0]->SetNumber(newHardlimit);
 
if(polar == 1)
vOut->widgetNE[0]->SetLimits(TGNumberFormat::kNELLimitMinMax, newHardlimit, 0.);
else if(polar == 0)
vOut->widgetNE[0]->SetLimits(TGNumberFormat::kNELLimitMinMax, 0., newHardlimit);
}
 
// Set, get, home or reset the table position
void TGAppMainFrame::PositionSet(int opt)
{
char cmd[1024];
 
// Set the selected table position
if(opt == 0)
{
int positX, positY, positZ;
if(posUnits->widgetCB->GetSelected() == 0)
{
positX = xPos->widgetNE[0]->GetNumber();
positY = yPos->widgetNE[0]->GetNumber();
positZ = zPos->widgetNE[0]->GetNumber();
}
else if(posUnits->widgetCB->GetSelected() == 1)
{
positX = (int)xPos->widgetNE[0]->GetNumber()/lenconversion;
positY = (int)yPos->widgetNE[0]->GetNumber()/lenconversion;
positZ = (int)zPos->widgetNE[0]->GetNumber()/lenconversion;
}
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 1 -v %d -s la && %s/src/MIKRO/mikro_ctrl -n 1 -c m", rootdir, positX, rootdir);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 2 -v %d -s la && %s/src/MIKRO/mikro_ctrl -n 2 -c m", rootdir, positY, rootdir);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 3 -v %d -s la && %s/src/MIKRO/mikro_ctrl -n 3 -c m", rootdir, positZ, rootdir);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
}
// Get current table position
else if(opt == 1)
{
fflush(stdout);
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 1 -p > %s/settings/curpos.txt", rootdir, rootdir); // X-axis
fflush(stdout);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 2 -p >> %s/settings/curpos.txt", rootdir, rootdir); // Y-axis
fflush(stdout);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 3 -p >> %s/settings/curpos.txt", rootdir, rootdir); // Z-axis
fflush(stdout);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
 
#if WORKSTAT == 'I'
FILE* fpos;
int itemp;
sprintf(cmd, "%s/settings/curpos.txt", rootdir);
fpos = fopen(cmd, "r");
if(fpos != NULL)
{
if(posUnits->widgetCB->GetSelected() == 0)
{
retTemp = fscanf(fpos, "%d\n", &itemp);
xPos->widgetNE[0]->SetNumber(itemp);
retTemp = fscanf(fpos, "%d\n", &itemp);
yPos->widgetNE[0]->SetNumber(itemp);
retTemp = fscanf(fpos, "%d\n", &itemp);
zPos->widgetNE[0]->SetNumber(itemp);
}
else if(posUnits->widgetCB->GetSelected() == 1)
{
retTemp = fscanf(fpos, "%d\n", &itemp);
xPos->widgetNE[0]->SetNumber((double)itemp*lenconversion);
retTemp = fscanf(fpos, "%d\n", &itemp);
yPos->widgetNE[0]->SetNumber((double)itemp*lenconversion);
retTemp = fscanf(fpos, "%d\n", &itemp);
zPos->widgetNE[0]->SetNumber((double)itemp*lenconversion);
}
}
 
fclose(fpos);
#endif
}
// Home the table position
else if(opt == 2)
{
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 1 -h", rootdir); // X-axis
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
 
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 2 -h", rootdir); // Y-axis
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
 
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 3 -h", rootdir); // Z-axis
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
PositionSet(1);
}
// Reset the table position
else if(opt == 3)
{
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 1 -r && sudo %s/src/MIKRO/mikro_ctrl -n 1 -i 3 && sudo %s/src/MIKRO/mikro_ctrl -n 1 -h", rootdir, rootdir, rootdir); // X-axis
#if WORKSTAT == 'I'
printf("Positioning table reset, initialization and homing in progress. Please wait...\n");
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
 
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 2 -r && sudo %s/src/MIKRO/mikro_ctrl -n 2 -i 3 && sudo %s/src/MIKRO/mikro_ctrl -n 2 -h", rootdir, rootdir, rootdir); // Y-axis
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
 
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 3 -r && sudo %s/src/MIKRO/mikro_ctrl -n 3 -i 3 && sudo %s/src/MIKRO/mikro_ctrl -n 3 -h", rootdir, rootdir, rootdir); // Z-axis
#if WORKSTAT == 'I'
retTemp = system(cmd);
printf("Positioning table reset, initialization and homing complete.\n");
#else
printf("Cmd: %s\n",cmd);
#endif
PositionSet(1);
}
}
 
// Set, get, home or reset the rotation platform
void TGAppMainFrame::RotationSet(int opt)
{
char cmd[1024];
 
// Set the selected rotation
if(opt == 0)
{
int positAlpha;
if(rotUnits->widgetCB->GetSelected() == 0)
positAlpha = rotPos->widgetNE[0]->GetNumber();
else if(rotUnits->widgetCB->GetSelected() == 1)
positAlpha = rotPos->widgetNE[0]->GetNumber()/rotconversion;
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -v %d -s la && %s/src/MIKRO/mikro_ctrl -n 4 -c m", rootdir, positAlpha, rootdir);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
}
// Get current rotation
else if(opt == 1)
{
fflush(stdout);
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -p > %s/settings/currot.txt", rootdir, rootdir);
fflush(stdout);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
 
#if WORKSTAT == 'I'
FILE* frot;
int itemp;
sprintf(cmd, "%s/settings/currot.txt", rootdir);
frot = fopen(cmd, "r");
 
if(frot != NULL)
{
retTemp = fscanf(frot, "%d\n", &itemp);
if(rotUnits->widgetCB->GetSelected() == 0)
rotPos->widgetNE[0]->SetNumber(itemp);
else if(rotUnits->widgetCB->GetSelected() == 1)
rotPos->widgetNE[0]->SetNumber((double)itemp*rotconversion);
}
 
fclose(frot);
#endif
}
// Home the rotation
else if(opt == 2)
{
// TODO: For now only set back to 0, not home!
// sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -h", rootdir);
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -v 0 -s la && %s/src/MIKRO/mikro_ctrl -n 4 -c m", rootdir, rootdir);
#if WORKSTAT == 'I'
retTemp = system(cmd);
#else
printf("Cmd: %s\n",cmd);
#endif
RotationSet(1);
}
// Reset the rotation
else if(opt == 3)
{
// TODO: For now only set back to 0, not home!
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -r && sudo %s/src/MIKRO/mikro_ctrl -n 4 -i 2 && sudo %s/src/MIKRO/mikro_ctrl -n 4 -h", rootdir, rootdir, rootdir);
#if WORKSTAT == 'I'
printf("Rotation platform reset, initalization and homing in progress. Please wait...\n");
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -v 0 -s la && %s/src/MIKRO/mikro_ctrl -n 4 -c m", rootdir, rootdir);
retTemp = system(cmd);
sleep(15); // wait for the motor to change position from wherever to 0
sprintf(cmd, "sudo %s/src/MIKRO/mikro_ctrl -n 4 -r && sudo %s/src/MIKRO/mikro_ctrl -n 4 -i 2", rootdir, rootdir);
retTemp = system(cmd);
printf("Rotation platform reset, initalization and homing complete.\n");
#else
printf("Cmd: %s\n",cmd);
#endif
RotationSet(1);
}
}
 
// File browser for selecting the save file
void TGAppMainFrame::SaveFile()
{
TGFileInfo file_info;
const char *filetypes[] = {"Histograms",histextall,0,0};
char *cTemp;
file_info.fFileTypes = filetypes;
cTemp = new char[1024];
sprintf(cTemp, "%s/results", rootdir);
file_info.fIniDir = StrDup(cTemp);
new TGFileDialog(gClient->GetDefaultRoot(), fMain, kFDSave, &file_info);
delete[] cTemp;
 </