Commit 21df86f7 authored by Béuren F. Bechlin's avatar Béuren F. Bechlin

Script de coleta finalizado.

parent 41cdecf6
......@@ -2,4 +2,5 @@
sources/python/
sources/*.log
sources/*.logbin
__pycache__
scripts/__pycache__
PYBIN := python3
VENVDIR := $(shell pwd)/.venv
VENVPY := ${VENVDIR}/bin/python
BUILDDIR := .build
.PHONY: help setup firmware serial run
......
This diff is collapsed.
This diff is collapsed.
File added
from terminalcolors import cprint, cstring
import argparse, subprocess, readchar, sys, os
# CONSTANTES
LOGPATH = 'logs/'
SOURCEPATH = 'sources/'
shexec = lambda command:\
subprocess.check_output(command, shell=True).decode('ascii')
def get_plataformio_serial_ports():
'''
'''
serial_raw = shexec("platformio serialports list").splitlines()
if serial_raw == []:
return ['/dev/tty/USB0']
# return []
else:
serial_ports = [serial_raw[i-1]
for i,x in enumerate(serial_raw) if '----' in x]
return serial_ports
def serial_ports_menu():
serials_available = get_plataformio_serial_ports()
if(serials_available == []):
print("{} nenhuma porta serial encontrada.\nAbortando.".format(cstring("ERRO:", attr='bold')))
sys.exit(0)
else:
index = 0
charac = 0
while(charac != '\r'):
print('\r', end = "", flush=True)
for i, ser in enumerate(serials_available):
print("{} {} ".format(cstring("-->", fore='green') if index == i else " " ,ser), end = "", flush=True)
charac = readchar.readkey()
if(charac == '\x1b[C'):
if(index != len(serials_available) - 1):
index += 1
if(charac == '\x1b[D'):
if(index != 0):
index -= 1
if(charac == '\x03'):
print("\nTecla de escape prescionada.\nAbortando")
sys.exit(1)
print("")
return serials_available[index]
def storage_info(inputDic):
cprint("Armazenamento:", attr='bold')
print("-Nome do arquivo: {} \t-Tempo de armazenamento: {} s".format(inputDic['fileName'],inputDic['execTime']))
print("-Porta Serial: {} \t -Baud Rate: {} ".format(inputDic['serialPort'],inputDic['baudRate']))
def visualization_info(inputDic):
cprint("Visualização:", attr='bold')
print("Tempo:\t\t\tFrequência:\t\t\tFiltro:")
print("-Inicial: {} s\t\t-Inicial: {} Hz\t\t\t-Ordem: {}".format(inputDic['initialTime'],inputDic['initialFreq'], inputDic['filterOrder']))
print("-Final: {} s\t\t-Final: {} Hz\t\t\t-Passadas: {}".format(inputDic['finalTime'],inputDic['finalFreq'], inputDic['filterNum']))
def visualization_menu_change_time(inputDic):
while True:
try:
inputDic['initialTime'] = int(input("Insira o tempo inicial de análise: "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
while True:
try:
inputDic['finalTime'] = int(input("Insira o tempo final de análise: "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
return inputDic
def visualization_menu_change_freq(inputDic):
while True:
try:
inputDic['initialFreq'] = float(input("Insira a frequência inicial de análise: "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
while True:
try:
inputDic['finalFreq'] = float(input("Insira a frequência final de análise: "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
return inputDic
def visualization_menu_change_filter(inputDic):
while True:
try:
inputDic['filterOrder'] = int(input("Insira a ordem do filtro, (MÁX 2): "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
while True:
try:
inputDic['filterNum'] = int(input("Insira o número de passadas do filtro: "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
return inputDic
def visualization_menu(inputDic):
options = ["Não", "Tempo", "Frequência", "Filtro"]
index = 1
while(index != 0):
index = 0
charac = 0
print("Deseja modificar algum item ?")
while(charac != '\r'):
print('\r', end = "", flush=True)
for i, ser in enumerate(options):
print("{} {} ".format(cstring("-->", fore='green') if index == i else " " ,ser), end = "", flush=True)
charac = readchar.readkey()
if(charac == '\x1b[C'):
if(index != len(options) - 1):
index += 1
if(charac == '\x1b[D'):
if(index != 0):
index -= 1
if(charac == '\x03'):
print("\nTecla de escape prescionada.\nAbortando")
sys.exit(1)
print("")
if(index == 1):
inputDic = visualization_menu_change_time(inputDic)
elif(index == 2):
inputDic = visualization_menu_change_freq(inputDic)
elif(index == 3):
inputDic = visualization_menu_change_filter(inputDic)
return inputDic
def runScripts(inputDic, store=True, visu=True):
if not os.access(inputDic['logPath'], os.R_OK):
os.mkdir(inputDic['logPath'])
if store and visu:
os.system("""
python3 {srcPath}armazenamento.py {serialPort} {baudRate} \
{logPath}{fileName} {execTime} &&
python3 {srcPath}visualiza.py {logPath}{fileName} {initialTime} \
{finalTime} {filterOrder} {filterNum} {initialFreq} {finalFreq}
""".format(**inputDic))
elif store:
os.system("""
python3 {srcPath}armazenamento.py {serialPort} {baudRate} \
{logPath}{fileName} {execTime}
""".format(**inputDic))
elif visu:
os.system("""
python3 {srcPath}visualiza.py {logPath}{fileName} {initialTime} \
{finalTime} {filterOrder} {filterNum} {initialFreq} {finalFreq}
""".format(**inputDic))
def checkPath(path):
a = os.getcwd().split('respirometro')[1]
return "../"*a.count('/')+path
def main():
cprint("--: Script de coleta e visualização Respirômetro CTA :--", attr='bold', fore='green')
inputDic = {'initialTime': 0, 'initialFreq': 0, 'finalFreq': 1,
'baudRate': 115200, 'filterOrder':2, 'filterNum':4,
'srcPath':checkPath(SOURCEPATH), 'logPath':checkPath(LOGPATH)}
cprint("\nArmazenamento:", fore='green')
inputDic['fileName'] = input("Insira o nome do arquivo em qual será salvo a coleta: ") + '.log'
print("Selecione a porta usb em que o microcontrolador está conectado.")
print("Use as teclas direcionais para navegar e enter para selecionar")
inputDic['serialPort'] = serial_ports_menu()
while True:
try:
inputDic['execTime'] = int(input("Insira o tempo de armazenamento de dados: "))
break
except ValueError:
print("Insira um número válido")
except KeyboardInterrupt:
print("Tecla de escape prescionada.\nAbortando")
sys.exit(1)
inputDic['finalTime'] = inputDic['execTime']
cprint("\nVisualização:", fore='green')
cprint("Default:", attr='bold')
visualization_info(inputDic)
inputDic = visualization_menu(inputDic)
cprint("\nConfirmação:", fore='green')
storage_info(inputDic)
visualization_info(inputDic)
runScripts(inputDic)
if __name__ == "__main__":
#Creating a parser
parser = argparse.ArgumentParser(description="""Script para realizar
armazenamento e visualização dos dados do respirômetro.""")
parser.add_argument('--foo', help='foo of the %(prog)s program')
main()
from terminalcolors import cstring, cprint
import types
class ProgBarTerm():
default_color = 'NORMAL'
complete_color = 'GREEN'
not_complete_color = 'NORMAL'
percentage_color = 'WHITE'
limetation_color = 'WHITE'
size = '15'
def __init__(self, **kwargs):
for key in kwargs.keys():
setattr(self, str(key), str(kwargs[key]))
# Creating a dict with atributes of this class
def __iter__(self):
# first start by grabbing the Class items
iters = dict((x,y) for x,y in ProgBarTerm.__dict__.items()
if not (x[:2] == '__' and type(y) == types.MethodType))
this_dict = dict((x,y) for x,y in self.__dict__.items()
if not (x[:2] == '__' and type(y) == types.MethodType))
# then update the class items with the instance items
iters.update(this_dict)
# now 'yield' (Generator) through the items
for x,y in iters.items():
if not(type(y) == types.MethodType):
yield x,y
def test(self):
print(dict(self.__dict__))
if __name__ == '__main__':
a = ProgBarTerm()
print(a.test())
print(dict(a))
class TerminalColors:
'''
Reference http://ascii-table.com/ansi-escape-sequences.php
'''
class ATTRIBUTES:
NORMAL = ''
BOLD = ';1'
UNDERSCORE = ';4'
BLINK = ';5'
REVERSE = ';6'
CONCEALED = ';7'
class FOREGROUND:
NORMAL = ''
BLACK = ';30'
RED = ';31'
GREEN = ';32'
YELLOW = ';33'
BLUE = ';34'
MAGENTA = ';35'
CYAN = ';36'
WHITE = ';37'
class BACKGROUND:
NORMAL = ''
BLACK = ';40'
RED = ';41'
GREEN = ';42'
YELLOW = ';43'
BLUE = ';44'
MAGENTA = ';45'
CYAN = ';46'
WHITE = ';47'
@classmethod
def cstring(cls, string, attr = 'NORMAL', fore = 'NORMAL', back = 'NORMAL'):
attr = getattr(cls.ATTRIBUTES, attr.upper(), '')
fore = getattr(cls.FOREGROUND, fore.upper(), '')
back = getattr(cls.BACKGROUND, back.upper(), '')
format_str = attr + fore + back
if(format_str != ''):
format_str = format_str[1:]
return '\033[{}m{}\033[0m'.format(format_str, string)
@classmethod
def cprint(cls, string, attr = 'NORMAL', fore = 'NORMAL', back = 'NORMAL',
sep = ' ', end = '\n', flush = False):
print(cls.cstring(string, attr, fore, back), end = end, sep = sep, flush = flush)
def cprint(*args, **kwargs):
TerminalColors.cprint(*args, **kwargs)
def cstring(*args, **kwargs):
return TerminalColors.cstring(*args, **kwargs)
if __name__ == '__main__':
cprint('TEST', fore='green', back = 'blue')
print(cstring('TESTE', fore='blue', back='green'))
......@@ -28,7 +28,7 @@ STRUCT_DATA = 'hhh'
STRUCT_HEADER = 'Hh'
# Exemplo: python3 armazenamento.py /dev/ttyACM0 115200 coleta_Nome_Exemplo_1min.log 30
from terminalcolors import cprint, cstring
import sys, serial, datetime, os, time, struct
def validateInput():
......@@ -66,18 +66,19 @@ def initSerial(port, baud):
ser.dtr = True # Liga DTR novamente
return ser
def progressBar(percent, lenght):
def progressBar(percent, lenght=15, description =""):
'''
Cursor necessita estar na linha onde está a barra de progresso.
DOC dos ANSII caracters:
http://ascii-table.com/ansi-escape-sequences.php
'''
highlight = " "*int((lenght-2)*percent*1.0/100)
notHighlight = " "*(lenght-2- len(highlight))
printString = "\t"+"\033[47m"+" "+"\033[42m"+"{}".format(highlight)+ \
notHighlight = " "*(lenght - len(highlight) - 2)
printString = "\t"+ cstring(" ", back = "White")+cstring("{}", back = "Green").format(highlight)+ \
"\033[0;0m"+"{}".format(notHighlight)+ "\033[47m"+" "\
"\033[0;32m"+"\t{}%".format(percent)+"\033[0;0m"
print(printString, end='\r')
print(printString, end='\r')
printS
def main():
args = validateInput()
......@@ -95,6 +96,7 @@ def main():
break
print("Leitura falhou. Reiniciando.")
except KeyboardInterrupt:
print("Tecla de escape prescionada. Abortando")
sys.exit()
except struct.error:
print("Leitura falhou. Reiniciando.")
......@@ -162,13 +164,22 @@ def unpackDataResp(fileName, timeI, timeF):
fisiologfile.readline()
fisiologfile.readline()
# Dados
for i, linha in enumerate(fisiologfile):
time = float(linha.replace('\n', '').split('\t')[3])
if time >= timeI and time <= timeF:
yCard.append(int(linha.split('\t')[0]))
yRespDir.append(int(linha.split('\t')[1]))
yRespEsq.append(int(linha.split('\t')[2]))
x.append(time)
if(timeF == 0):
for i, linha in enumerate(fisiologfile):
time = float(linha.replace('\n', '').split('\t')[3])
if time >= timeI:
yCard.append(int(linha.split('\t')[0]))
yRespDir.append(int(linha.split('\t')[1]))
yRespEsq.append(int(linha.split('\t')[2]))
x.append(time)
else:
for i, linha in enumerate(fisiologfile):
time = float(linha.replace('\n', '').split('\t')[3])
if time >= timeI and time <= timeF:
yCard.append(int(linha.split('\t')[0]))
yRespDir.append(int(linha.split('\t')[1]))
yRespEsq.append(int(linha.split('\t')[2]))
x.append(time)
fisiologfile.close()
if(len(yCard) % 2 != 0):
del(yCard[-1])
......
......@@ -34,14 +34,13 @@
divido por 2, ou seja, a as frequências definidas aqui devem estar no
intervalo [0;freq/2]
'''
# Exemplo: python3 visualiza.py coleta_Nome_Exemplo_1min.log 0 60 2 4 0 7
# Exemplo: python3 visualiza.py coleta_Nome_Exemplo_1min.log 0 60 2 4 0 1
from array import *
from scipy.fftpack import fft, fftfreq, fftshift
import numpy as np
from armazenamento import unpackDataResp
import sys, os
import sys, os, re, math
import matplotlib.pyplot as plt
import math
# ERROS:
# Testando se contém os argumentos
......@@ -63,8 +62,8 @@ n_filtro = int(parametro[3])
qtd_filtro = int(parametro[4])
freq_i = float(parametro[5])
freq_f = float(parametro[6])
png_name = 'Resp_'+log_file.split('_')[1]+'_'+str(t_inicial)+'_a_'+str(t_final)+'_'+str('%.2f' % freq_i)+'_a_'+str('%.2f' % freq_f)+'.png'
user_name = parametro[0].replace('_', ' ').split(' ')[1] + ' ' + parametro[0].replace('_', ' ').split(' ')[2]
png_name = 'Resp_'+str(log_file.split('/')[:-1])+'_'+str(t_inicial)+'_a_'+str(t_final)+'_'+str('%.2f' % freq_i)+'_a_'+str('%.2f' % freq_f)+'.png'
user_name = log_file
# ERRO:
# Ajustando para que os pontos iniciais não sejam maiores que os finais
......@@ -88,7 +87,6 @@ freq = float(data['Freq'])
N = len(data['Cardiogram'])
T = 1.0/freq
dx = float(freq)/N
print('Freq '+str(freq)+' N '+str(N))
# Inicialização de variáveis
x1 = array('f', data['Time'])
......@@ -374,6 +372,17 @@ plt.text(0.38,0.12,'Frequência Período Frequência Período
plt.text(0.42,0.06,'(Hz) (s) (Hz) (s)', fontsize=fontsize[4], fontstyle = 'italic')
plt.subplots_adjust(left = 0.1 ,right = 0.9 ,bottom=0.1, top = 0.9 ,wspace = 0.3, hspace = 0.3)
fig.savefig(png_name, dpi=400)
aux_str = parametro[0]
local_dir = ''
while True:
reg_exp = re.search('\/', aux_str)
if reg_exp != None:
local_dir += aux_str[:reg_exp.start()]
aux_str = aux_str[reg_exp.end():]
else:
break
local_dir += png_name
fig.savefig(local_dir, dpi=400)
#plt.show()
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