Commit 708eda69 authored by Matheus Müller's avatar Matheus Müller
Browse files

Load operacional, melhorias no label de status, ROI agora em tempo real

parent ac875fd3
......@@ -151,20 +151,13 @@ int main(int argc, char **argv)
{
// Get firmware revision
char fw_rev[10];
//TRACE( "\nN957 FW Rev. ");
if( ( N957_error_code= N957_GetFWRelease( user_setting.m_N957_handle, fw_rev, 10))!= N957Success)
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -3;
goto exit_point;
}
// TRACE( fw_rev);
}
// TRACE( "\n");
// TRACE( "\nHit 's' to start acquisition mode , any other to quit ...\n");
switch( getch()) {
case 's':
case 'S':
......@@ -174,111 +167,74 @@ int main(int argc, char **argv)
goto exit_point;
}
// Scaler Reading
// TRACE("\nADC Conversions Number : ");
if( ( N957_error_code=N957_GetScaler(user_setting.m_N957_handle, &data32)!= N957Success))
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -5;
goto exit_point;
}
// TRACE1("%d", data32);
// Timer Reading
// TRACE("\nTime (ms) : ");
if( ( N957_error_code=N957_GetTimer(user_setting.m_N957_handle, &data32)!= N957Success))
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -6;
goto exit_point;
}
// TRACE1("%d", data32);
// Live Time Reading
// TRACE("\nLive Time (ms) : ");
if( ( N957_error_code=N957_GetLiveTime(user_setting.m_N957_handle, &data32)!= N957Success))
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -7;
goto exit_point;
}
// TRACE1("%d",data32);
// Start acquisition with specific mode
// TRACE1( "\nN957 Start Acquisition mode %i : ", user_setting.m_mode);
if( ( N957_error_code= N957_StartAcquire( user_setting.m_N957_handle, user_setting.m_mode))!= N957Success)
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -8;
goto exit_point;
}
// TRACE( "Ok");
if( user_setting.m_debug) {
//
// If debugging features enable, convertion well be simulated by software
//
// Set software convertion
// TRACE( "\nN957 Debug Software convertion enable : ");
if( ( N957_error_code= N957_SetSwConvFlag( user_setting.m_N957_handle, N957_TRUE))!= N957Success)
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -9;
goto exit_point;
}
// TRACE( "Ok");
}
// Allocate buffer storage
data_buff= malloc( user_setting.m_bldim* sizeof( N957_UINT16));
if( data_buff== NULL)
{
// Insufficient memory
// TRACE1( "N957 Insufficient memory to allocate data buffer (%li bytes)", (long)( user_setting.m_bldim* sizeof( N957_UINT16)));
ret_val= -10;
goto exit_point;
}
// Allocate histogram buffer storage
histo_buff= malloc( N957_MAX_HISTO_SAMPLES* sizeof( *histo_buff));
if( histo_buff== NULL)
{
// Insufficient memory
// TRACE1( "N957 Insufficient memory to allocate histogram data buffer (%li bytes)", (long)N957_MAX_HISTO_SAMPLES* sizeof( *histo_buff));
ret_val= -11;
goto exit_point;
}
memset( histo_buff, 0, N957_MAX_HISTO_SAMPLES* sizeof( *histo_buff));
if( user_setting.m_log_to_file) {
// Create output file
if( ( out_file= fopen( user_setting.m_log_filename, "wt"))== NULL)
{
// TRACE1( "N957 output file creation failure '%s'", user_setting.m_log_filename);
ret_val= -12;
goto exit_point;
}
}
do_exit= FALSE;
while( !do_exit) {
N957_UINT16 data_read;
//// Check for user commands
data_read= user_setting.m_bldim;
if( user_setting.m_max_num_samples> 0){
// Check for maximun numsber of samples
if( tot_data_read>= user_setting.m_max_num_samples) {
ret_val= 0;
goto exit_point;
}
if( user_setting.m_max_num_samples- tot_data_read< user_setting.m_bldim) {
data_read= ( N957_UINT16)(int32_t)(user_setting.m_max_num_samples - tot_data_read);
}
......@@ -286,8 +242,6 @@ int main(int argc, char **argv)
//
// ReadData
if( ( N957_error_code= N957_ReadData( user_setting.m_N957_handle, data_buff, &data_read))!= N957Success) {
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -15;
goto exit_point;
}
......@@ -360,8 +314,11 @@ int main(int argc, char **argv)
break;
case 'y':
log = fopen("save.dat", "r");
for(w=0; w<8192; w++){
fscanf(log, "%i", &histograma[w]);
for(w=0; w<(8192-fator+1); w=w+fator)
{
fscanf(log, "%i", &temp);
for(i=w; i<=(w+fator-1); i++)
histograma[i] = temp/fator;
}
fclose(log);
break;
......@@ -378,7 +335,6 @@ int main(int argc, char **argv)
sprintf( aux_string, "%04d\n", data_buff[ i]);
if (!paused)
histograma[atoi(aux_string)+1] = histograma[atoi(aux_string)+1] +1;
//TRACE1("%d \n", atoi(aux_string));
}
}
}
......@@ -387,15 +343,11 @@ int main(int argc, char **argv)
{
//
// clear software convertion
// TRACE( "\nN957 Debug Software convertion disable : ");
if( ( N957_error_code= N957_SetSwConvFlag( user_setting.m_N957_handle, N957_FALSE))!= N957Success)
{
// TRACE( N957_DecodeError( N957_error_code));
//TRACE( "\n");
ret_val= -20;
goto exit_point;
}
// TRACE( "Ok");
}
exit_point:
......@@ -407,32 +359,20 @@ exit_point:
// Demo application specific
/////////////////////////////////////////
//TRACE( "\n\nHit any key to exit...");
getch();
// Stop acquisition
// TRACE( "\nN957 Stop Acquisition : ");
if( ( N957_error_code= N957_StopAcquire( user_setting.m_N957_handle))!= N957Success)
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -24;
goto exit_point;
}
// TRACE( "Ok");
// SW Clear
//TRACE( "\nSW Clear : ");
if( ( N957_error_code= N957_SwClear(user_setting.m_N957_handle)!= N957Success))
{
// TRACE( N957_DecodeError( N957_error_code));
// TRACE( "\n");
ret_val= -25;
goto exit_point;
}
//TRACE( "Ok");
// close modules
user_settings_close( &user_setting);
......
......@@ -8,6 +8,7 @@ import Tkinter as tk
import tkMessageBox
import matplotlib.pyplot as plt
from pylab import *
from threading import *
import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
......@@ -20,17 +21,15 @@ import tkFileDialog
child = pexpect.spawn('./N957Run')
time.sleep(3.3)
child.send('s')
paused = False
sys.setrecursionlimit(5000)
##############################################################################
##############################################################################
# Histrogram
t = 1500 #Refresh rate
bmin = 0
bmax = 8192
j = 0
Control = dict(t = 1500, bmin = 0, bmax = 8192, j = 0, filename = 'temp', count = 0, paused = False, ROIctrl = list())
Data=list()
ROIs=list()
for a in range(8192):
Data.insert(a, 0)
......@@ -41,7 +40,6 @@ for a in range(8192):
root = tk.Tk()
root.minsize(825,640)
root.title('Modulo Multicanal')
#root.geometry('670x470+200+200')
##############################################################################
##############################################################################
......@@ -58,8 +56,11 @@ def grid(a, n):
##############################################################################
# Regiao de interesse
def realtimerefresh(k):
Control['ROIctrl'][k] = 1
class InterestRegion:
def __init__(self, labfrm):
def __init__(self, labfrm, j):
self.Area = 0
self.xmin = 0
self.xmax = 0
......@@ -69,7 +70,7 @@ class InterestRegion:
self.label.pack(side='left')
self.xmaxe = tk.Entry(labfrm)
self.xmaxe.pack(side='left')
self.button = tk.Button(labfrm, text='Start', command = lambda i=i: self.ROIme())
self.button = tk.Button(labfrm, text='Start', command = lambda i=i: realtimerefresh(j))
self.button.pack(side='left')
self.label2 = tk.Label(labfrm, text='Total counts: %d' %self.Area)
self.label2.pack(side='bottom')
......@@ -82,27 +83,27 @@ class InterestRegion:
for n in range(self.xmin, (self.xmax)):
self.Area = self.Area + Data[n]
self.label2['text']='Total counts: %d' %self.Area
#root.after(2000, self.ROIme())
else:
tkMessageBox.showinfo("Error", "Invalid values")
def roiroi():
global bmin, bmax, j
j=0
Labelsf=list()
ROIs =list()
global ROIs
Control['j'] = 0
Labelsf = list()
ROIs = list()
roiwin = tk.Tk()
roiwin.title('ROI')
def addROI():
global j
Labelsf.insert(j, tk.LabelFrame(roiwin, text='ROI %d' %j))
Labelsf[j].pack(side='top')
ROIs.insert(j, InterestRegion(Labelsf[j]))
j = j + 1
Labelsf.insert(Control['j'], tk.LabelFrame(roiwin, text='ROI %d' %Control['j']))
Labelsf[Control['j']].pack(side='top')
ROIs.insert(Control['j'], InterestRegion(Labelsf[Control['j']], Control['j']))
Control['ROIctrl'].insert(Control['j'], 0)
Control['j'] = Control['j'] + 1
roibut = tk.Button(roiwin, text = 'Add', command = lambda i=i: addROI(), bd=2, width=7, height=1)
roibut.pack(side='top')
addROI()
roiwin.mainloop()
##############################################################################
......@@ -110,35 +111,33 @@ def roiroi():
Interface = dict(frames=list(), buttons=list(), labels=list(), spinboxes=list(), entries=list(), labelframes=list())
Livetime = dict(ADC_Conversion='0' , Time='0' , LiveTime='0' )
filename = 'temp'
count = 0
def set_fator(): # Define o fator para conversao do numero de canais
global Interface, child, bmax
if int(Interface['spinboxes'][0].get()) == 8192:
def set_fator(canais): # Define o fator para conversao do numero de canais
global Interface, child
if int(canais) == 8192:
child.send('a')
bmax = 8192
elif int(Interface['spinboxes'][0].get()) == 4096:
Control['bmax'] = 8192
elif int(canais) == 4096:
child.send('b')
bmax = 4096
elif int(Interface['spinboxes'][0].get()) == 2048:
Control['bmax'] = 4096
elif int(canais) == 2048:
child.send('c')
bmax = 2048
elif int(Interface['spinboxes'][0].get()) == 1024:
Control['bmax'] = 2048
elif int(canais) == 1024:
child.send('d')
bmax = 1024
elif int(Interface['spinboxes'][0].get()) == 512:
Control['bmax'] = 1024
elif int(canais) == 512:
child.send('e')
bmax = 512
elif int(Interface['spinboxes'][0].get()) == 256:
Control['bmax'] = 512
elif int(canais) == 256:
child.send('f')
bmax = 256
elif int(Interface['spinboxes'][0].get()) == 128:
Control['bmax'] = 256
elif int(canais) == 128:
child.send('g')
bmax = 128
elif int(Interface['spinboxes'][0].get()) == 64:
Control['bmax'] = 128
elif int(canais) == 64:
child.send('h')
bmax = 64
Control['bmax'] = 64
def settime():
Livetime['ADC_Conversion'] = child.readline().strip("\r\n")
......@@ -149,11 +148,10 @@ def settime():
Interface['labels'][2].configure(text='Live Time: %s' %Livetime['LiveTime'])
def graphic2(Data): #Plot
global Interface, bmin, bmax
temp.set_xdata(range(int(Interface['spinboxes'][0].get())))
temp.set_ydata(Data)
plt.xlim(bmin, bmax)
plt.ylim(0, max(Data[bmin:bmax])*1.2)
plt.xlim(Control['bmin'], Control['bmax'])
plt.ylim(0, max(Data[int(Control['bmin']):int(Control['bmax'])])*1.2)
grid(a, int(Interface['spinboxes'][0].get()))
f.canvas.draw()
......@@ -168,12 +166,15 @@ def dump(): # Sinal para programa coletor enviar os dados
child.send('i')
def realtimeplot(): # Funcao recursiva para plot em tempo real
global t, paused
if not paused:
global ROIs
if not Control['paused']:
dump()
try:
root.after(t, realtimeplot)
root.after(Control['t'], realtimeplot)
graphic()
for n in range(len(Control['ROIctrl'])):
if Control['ROIctrl'][n] == 1:
ROIs[n].ROIme()
except ValueError:
pass
......@@ -186,10 +187,10 @@ def reset(): # Zera o vetor de aquisicao
child.send('r')
def pause(): # Para/Continua a aquisicao de dados
global child, paused
paused = not paused
global child
Control['paused'] = not Control['paused']
child.send('p')
if paused:
if Control['paused']:
Interface['buttons'][1]['text'] = 'Resume'
Interface['labels'][3]['text'] = 'Paused'
else:
......@@ -200,34 +201,42 @@ def pause(): # Para/Continua a aquisicao de dados
def restart(): # Reinicia o programa de aquisicao
global child
child.send('j')
time.sleep(0.3)
time.sleep(0.5)
child = pexpect.spawn('./N957Run')
time.sleep(3.3)
child.send('s')
Interface['buttons'][0].invoke()
def save(): # Salva os dados no arquivo selecionado
global child, Data, count, filename
fname = open(filename+'.'+str(count), mode = 'w')
global child, Data
fname = open(Control['filename']+'.'+str(Control['count']), mode = 'w')
for n in range(int(Interface['spinboxes'][0].get())):
fname.write(str(n+1)+' '+str(Data[n])+'\n')
fname.close()
Interface['labels'][5]['text'] = '%s.%d' %(filename, count)
count = count + 1
Interface['labels'][5]['text'] = '%s.%d' %(Control['filename'], Control['count'])
Control['count'] = Control['count'] + 1
def saveas(): # Salva os dados no arquivo selecionado
global child, Data, count, filename
filename = tkFileDialog.asksaveasfilename()
count=0
fname = open(filename+'.'+str(count), mode = 'w')
global child, Data
Control['filename'] = tkFileDialog.asksaveasfilename()
Control['count']=0
fname = open(Control['filename']+'.'+str(Control['count']), mode = 'w')
for n in range(int(Interface['spinboxes'][0].get())):
fname.write(str(n+1)+' '+str(Data[n])+'\n')
fname.close()
Interface['labels'][5]['text'] = '%s.%d' %(filename, count)
count = count + 1
Interface['labels'][5]['text'] = '%s.%d' %(Control['filename'], Control['count'])
Control['count'] = Control['count'] + 1
#child.send('z')
def load(): # Manda os dados carregados para leitura
global child
newfile = tkFileDialog.askopenfilename()
filefile = np.loadtxt(newfile)
tempfile = open('save.dat','w+')
set_fator(len(filefile))
for h in filefile[:,1]:
tempfile.write(str(int(h))+'\n')
tempfile.close()
child.send('y')
def refreshrate(): # Define a frequencia de atualizacao do grafico
......@@ -237,11 +246,10 @@ def refreshrate(): # Define a frequencia de atualizacao do grafico
rrent.pack(side='left')
def setrr():
global t
if rrent.get().isdigit():
if int(rrent.get()) > 499: # Valores muito baixos causam stack overflow
t = int(rrent.get())
Interface['labels'][4].configure(text = ' Refresh Rate %dms' %t)
Control['t'] = int(rrent.get())
Interface['labels'][4].configure(text = ' Refresh Rate %dms' %Control['t'])
else:
tkMessageBox.showinfo("Error", "This refresh rate is likely to reach maximum recursion depht!")
else:
......@@ -264,12 +272,13 @@ def shutdown():
for i in range(4):
Interface['frames'].insert(i, tk.Frame(root))
Interface['frames'][i].pack(side='top')
Interface['frames'][2].pack(side='top',fill='both', expand=1)
if i == 2:
Interface['frames'][i].pack(side='top',fill='both', expand=1)
else:
Interface['frames'][i].pack(side='top',fill='x', expand=0)
Interface['labelframes'].insert(0,tk.LabelFrame(Interface['frames'][1], relief='raised', text='Bins', bd=2))
Interface['labelframes'].insert(1,tk.LabelFrame(Interface['frames'][1], relief='raised', text='Time', bd=2))
Interface['labelframes'].insert(0,tk.LabelFrame(Interface['frames'][1], relief='raised', text='Bins', bd=2, pady=3))
Interface['labelframes'].insert(1,tk.LabelFrame(Interface['frames'][1], relief='raised', text='Time', bd=2, pady=3))
for i in range(2):
Interface['labelframes'][i].pack(side='left')
......@@ -283,7 +292,7 @@ for i in range(3):
Interface['frames'][(i+4)].pack(side='left')
Interface['labels'][i].pack(side='left')
Interface['spinboxes'].insert(0, tk.Spinbox(Interface['labelframes'][0], command = set_fator, values=[64,128,256,512,1024,2048,4096,8192]))
Interface['spinboxes'].insert(0, tk.Spinbox(Interface['labelframes'][0], command = lambda i=i: set_fator(Interface['spinboxes'][0].get()), values=[64,128,256,512,1024,2048,4096,8192]))
Interface['spinboxes'][0].pack()
Interface['spinboxes'][0].delete(0,len(Interface['spinboxes'][0].get()))
Interface['spinboxes'][0].insert(0,512)
......@@ -304,9 +313,9 @@ menubar.add_cascade(label="Settings", menu=settings)
root.config(menu=menubar)
##############################################################################
Interface['buttons'].insert(0, tk.Button(Interface['frames'][0], text = 'Plot', command = lambda i=i: realtimeplot(), bd=2, width=11, height=1))
Interface['buttons'].insert(0, tk.Button(Interface['frames'][0], text = 'Start', command = lambda i=i: realtimeplot(), bd=2, width=11, height=1))
Interface['buttons'].insert(1, tk.Button(Interface['frames'][0], text = 'Pause', command = lambda i=i: pause(), bd=2, width=11, height=1))
Interface['buttons'].insert(2, tk.Button(Interface['frames'][0], text = 'Reset', command = lambda i=i: reset(), bd=2, width=11, height=1))
Interface['buttons'].insert(2, tk.Button(Interface['frames'][0], text = 'Clear', command = lambda i=i: reset(), bd=2, width=11, height=1))
Interface['buttons'].insert(3, tk.Button(Interface['frames'][0], text = 'Restart', command = lambda i=i: restart(), bd=2, width=11, height=1))
Interface['buttons'].insert(4, tk.Button(Interface['frames'][0], text = 'Save', command = lambda i=i: save(), bd=2, width=11, height=1))
Interface['buttons'].insert(5, tk.Button(Interface['frames'][0], text = 'Save As', command = lambda i=i: saveas(), bd=2, width=11, height=1))
......@@ -319,8 +328,8 @@ for i in range(3):
Interface['frames'][i+7].pack(side = 'left', fill='x', expand=1)
Interface['labels'].insert(3,tk.Label(Interface['frames'][7], text='Acquiring', anchor='w'))
Interface['labels'].insert(4,tk.Label(Interface['frames'][8], text=' Refresh Rate %dms' %t))
Interface['labels'].insert(5,tk.Label(Interface['frames'][9], text=' %s.%d' %(filename, count), anchor='e'))
Interface['labels'].insert(4,tk.Label(Interface['frames'][8], text='Refresh Rate %dms' %Control['t'], anchor='center'))
Interface['labels'].insert(5,tk.Label(Interface['frames'][9], text='%s.%d' %(Control['filename'], Control['count']), anchor='e'))
for n in arange(3,6):
Interface['labels'][n].pack(fill='x')
......@@ -343,7 +352,8 @@ ylabel('Counts')
##############################################################################
# Paralel processing
set_fator()
set_fator(Interface['spinboxes'][0].get())
Interface['buttons'][0].invoke()
root.mainloop()
##############################################################################
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment