Commit 6c6f2537 authored by Béuren F. Bechlin's avatar Béuren F. Bechlin

ATT: empacotamento e desenpacotamento de dados do respirômetro, read-me com instruções de uso

parent 21df86f7
...@@ -2,5 +2,6 @@ ...@@ -2,5 +2,6 @@
sources/python/ sources/python/
sources/*.log sources/*.log
sources/*.logbin sources/*.logbin
logs/*
__pycache__ __pycache__
scripts/__pycache__ scripts/__pycache__
...@@ -12,8 +12,10 @@ help: ...@@ -12,8 +12,10 @@ help:
@ echo " firmware Compile and upload the firmware to the Arduino board via serial" @ echo " firmware Compile and upload the firmware to the Arduino board via serial"
@ echo " serial Starts a serial session with Python for board communication" @ echo " serial Starts a serial session with Python for board communication"
@ echo "" @ echo ""
@ echo " store Execute the logger on the foreground. Hit Ctrl+C to stop it." @ echo " run Execute the storage and analysis scripts. It's like run 'make store'"
@ echo " analyse Execute the analyses data routine" @ echo " and 'make anlyse'."
@ echo " store Execute the storage data routine."
@ echo " analyze Execute the analysis data routine."
install-debian-deps: install-debian-deps:
sudo apt-get install -y python3 supervisor curl dialog sudo apt-get install -y python3 supervisor curl dialog
...@@ -42,5 +44,10 @@ pyserial: ...@@ -42,5 +44,10 @@ pyserial:
python3 -i scripts/init_serial.py python3 -i scripts/init_serial.py
run: run:
python3 logger/run.py python3 scripts/coleta_script.py
store:
python3 scripts/coleta_script.py --store
analyze:
python3 scripts/coleta_script.py --analyze
This diff is collapsed.
...@@ -48,9 +48,9 @@ class TerminalColors: ...@@ -48,9 +48,9 @@ class TerminalColors:
print(cls.cstring(string, attr, fore, back), end = end, sep = sep, flush = flush) print(cls.cstring(string, attr, fore, back), end = end, sep = sep, flush = flush)
def cprint(*args, **kwargs): def colorprint(*args, **kwargs):
TerminalColors.cprint(*args, **kwargs) TerminalColors.cprint(*args, **kwargs)
def cstring(*args, **kwargs): def colorstring(*args, **kwargs):
return TerminalColors.cstring(*args, **kwargs) return TerminalColors.cstring(*args, **kwargs)
if __name__ == '__main__': if __name__ == '__main__':
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os, sys
sys.path.append('{}respirometro{}scripts'.format(
os.path.dirname(os.path.realpath(__file__)).split('respirometro')[0],
os.path.sep))
''' '''
Respirômetro - Fisiolog CTA Respirômetro - Fisiolog CTA
...@@ -28,8 +34,8 @@ STRUCT_DATA = 'hhh' ...@@ -28,8 +34,8 @@ STRUCT_DATA = 'hhh'
STRUCT_HEADER = 'Hh' STRUCT_HEADER = 'Hh'
# Exemplo: python3 armazenamento.py /dev/ttyACM0 115200 coleta_Nome_Exemplo_1min.log 30 # Exemplo: python3 armazenamento.py /dev/ttyACM0 115200 coleta_Nome_Exemplo_1min.log 30
from terminalcolors import cprint, cstring from terminalcolors import colorprint, colorstring
import sys, serial, datetime, os, time, struct import serial, datetime, time, struct
def validateInput(): def validateInput():
''' '''
...@@ -74,11 +80,10 @@ def progressBar(percent, lenght=15, description =""): ...@@ -74,11 +80,10 @@ def progressBar(percent, lenght=15, description =""):
''' '''
highlight = " "*int((lenght-2)*percent*1.0/100) highlight = " "*int((lenght-2)*percent*1.0/100)
notHighlight = " "*(lenght - len(highlight) - 2) notHighlight = " "*(lenght - len(highlight) - 2)
printString = "\t"+ cstring(" ", back = "White")+cstring("{}", back = "Green").format(highlight)+ \ printString = "\t"+ colorstring(" ", back = "White")+colorstring("{}", back = "Green").format(highlight)+ \
"\033[0;0m"+"{}".format(notHighlight)+ "\033[47m"+" "\ "\033[0;0m"+"{}".format(notHighlight)+ "\033[47m"+" "\
"\033[0;32m"+"\t{}%".format(percent)+"\033[0;0m" "\033[0;32m"+"\t{}%".format(percent)+"\033[0;0m"
print(printString, end='\r') print(printString, end='\r')
printS
def main(): def main():
args = validateInput() args = validateInput()
...@@ -148,45 +153,47 @@ def main(): ...@@ -148,45 +153,47 @@ def main():
comm.close() comm.close()
print("\nOperação finalizada com sucesso.") print("\nOperação finalizada com sucesso.")
def unpackDataResp(fileName, timeI, timeF): def unpackData(file_name):
fisiologfile = open(fileName) log_file = open(file_name)
yCard = []
yRespDir = []
yRespEsq = []
x = []
# Lendo HEADER # Lendo HEADER
fisiologfile.readline() log_file.readline()
frequency = fisiologfile.readline().replace('\n', '').split(' ')[4] frequency = log_file.readline().replace('\n', '').split(' ')[4]
linha = fisiologfile.readline() linha = log_file.readline()
date_time_d = linha.split(' ')[6] date_time_d = linha.split(' ')[6]
date_time_d = date_time_d.split('-')[2]+ '/' + date_time_d.split('-')[1]+ '/' + date_time_d.split('-')[0] date_time_d = date_time_d.split('-')[2]+ '/' + date_time_d.split('-')[1]+ '/' + date_time_d.split('-')[0]
date_time_h = linha.replace('\n','').split(' ')[7] date_time_h = linha.replace('\n','').split(' ')[7]
fisiologfile.readline() log_file.readline()
fisiologfile.readline() fields = log_file.readline().strip(' #(s)\n').split('\t')
# Dados
if(timeF == 0): data = {x:[] for x in fields}
for i, linha in enumerate(fisiologfile): for linha in log_file:
time = float(linha.replace('\n', '').split('\t')[3]) items = linha.replace('\n', '').split('\t')
if time >= timeI: for i, field in enumerate(fields):
yCard.append(int(linha.split('\t')[0])) data[field].append(float(items[i]))
yRespDir.append(int(linha.split('\t')[1])) log_file.close()
yRespEsq.append(int(linha.split('\t')[2]))
x.append(time) if(len(data[fields[0]]) % 2 != 0):
else: for item in data.values():
for i, linha in enumerate(fisiologfile): item.pop(-1)
time = float(linha.replace('\n', '').split('\t')[3])
if time >= timeI and time <= timeF: header = {'Freq':frequency, 'Date':date_time_d, 'Hour':date_time_h}
yCard.append(int(linha.split('\t')[0])) data.update(header)
yRespDir.append(int(linha.split('\t')[1])) return data
yRespEsq.append(int(linha.split('\t')[2]))
x.append(time) def selectDataRange(data, key, t_in, t_fi):
fisiologfile.close() if not key in data.keys():
if(len(yCard) % 2 != 0): return False
del(yCard[-1])
del(yRespDir[-1]) list_keys = [x for x in data.keys() if isinstance(data[x], list)]
del(yRespEsq[-1]) out = {x:[] for x in data.keys() if x in list_keys}
del(x[-1]) out.update({x:y for (x,y) in zip(data.keys(), data.values()) if not x in list_keys})
return {'Freq':frequency, 'Date':date_time_d, 'Hour':date_time_h, 'Cardiogram':yCard, 'RespDir':yRespDir, 'RespEsq':yRespEsq, 'Time': x} for i, time in enumerate(data[key]):
if time >= t_in and time < t_fi:
for field in list_keys:
out[field].append(data[field][i])
return out
if __name__== '__main__': if __name__== '__main__':
main() # main()
a = unpackData('../logs/test.log')
b = selectDataRange(a, 'Tempo', 9.0, 9.5)
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 colorprint(*args, **kwargs):
TerminalColors.cprint(*args, **kwargs)
def colorstring(*args, **kwargs):
return TerminalColors.cstring(*args, **kwargs)
if __name__ == '__main__':
cprint('TEST', fore='green', back = 'blue')
print(cstring('TESTE', fore='blue', back='green'))
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
from array import * from array import *
from scipy.fftpack import fft, fftfreq, fftshift from scipy.fftpack import fft, fftfreq, fftshift
import numpy as np import numpy as np
from armazenamento import unpackDataResp from armazenamento import unpackData, selectDataRange
import sys, os, re, math import sys, os, re, math
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
...@@ -55,15 +55,14 @@ if not os.path.exists(sys.argv[1]): ...@@ -55,15 +55,14 @@ if not os.path.exists(sys.argv[1]):
# Atribuindo as váriaveis com os valores de entrada # Atribuindo as váriaveis com os valores de entrada
parametro = sys.argv[1:] parametro = sys.argv[1:]
log_file = parametro[0] log_file = parametro[0]
fisiologfile = open(log_file,'r')
t_inicial = int(parametro[1]) t_inicial = int(parametro[1])
t_final = int(parametro[2]) t_final = int(parametro[2])
n_filtro = int(parametro[3]) n_filtro = int(parametro[3])
qtd_filtro = int(parametro[4]) qtd_filtro = int(parametro[4])
freq_i = float(parametro[5]) freq_i = float(parametro[5])
freq_f = float(parametro[6]) freq_f = float(parametro[6])
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 = os.path.splitext(os.path.basename(log_file))[0]
user_name = log_file png_name = 'Resp_{}_{}s_{}s_{}hz_{}hz.png'.format(user_name, t_inicial, t_final, freq_i, freq_f)
# ERRO: # ERRO:
# Ajustando para que os pontos iniciais não sejam maiores que os finais # Ajustando para que os pontos iniciais não sejam maiores que os finais
...@@ -81,17 +80,18 @@ if t_inicial < 0 or t_final < 0: ...@@ -81,17 +80,18 @@ if t_inicial < 0 or t_final < 0:
sys.stderr.write('ERRO: Não possível operar com intervalos negativos.\nEm caso de dúvidas leia o READ_ME.md.\n') sys.stderr.write('ERRO: Não possível operar com intervalos negativos.\nEm caso de dúvidas leia o READ_ME.md.\n')
sys.exit(1) sys.exit(1)
data = unpackDataResp(log_file, t_inicial , t_final) data = unpackData(log_file)
freq = float(data['Freq']) freq = float(data['Freq'])
N = len(data['Cardiogram']) N = len(data['A0'])
T = 1.0/freq T = 1.0/freq
dx = float(freq)/N dx = float(freq)/N
data = selectDataRange(data, 'Tempo', t_inicial, t_final)
# Inicialização de variáveis # Inicialização de variáveis
x1 = array('f', data['Time']) x1 = array('f', data['Tempo'])
y1 = array('f', data['RespDir']) y1 = array('f', data['A0'])
y2 = array('f', data['RespEsq']) y2 = array('f', data['A1'])
y1_filt = array('f', []) y1_filt = array('f', [])
y2_filt = array('f', []) y2_filt = array('f', [])
x_fft_plot = array('f', []) x_fft_plot = array('f', [])
...@@ -382,7 +382,7 @@ while True: ...@@ -382,7 +382,7 @@ while True:
aux_str = aux_str[reg_exp.end():] aux_str = aux_str[reg_exp.end():]
else: else:
break break
local_dir += png_name local_dir += '/' + png_name
fig.savefig(local_dir, dpi=400) fig.savefig(local_dir, dpi=400)
#plt.show() #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