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 @@
sources/python/
sources/*.log
sources/*.logbin
logs/*
__pycache__
scripts/__pycache__
......@@ -12,8 +12,10 @@ help:
@ 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 ""
@ echo " store Execute the logger on the foreground. Hit Ctrl+C to stop it."
@ echo " analyse Execute the analyses data routine"
@ echo " run Execute the storage and analysis scripts. It's like run 'make store'"
@ echo " and 'make anlyse'."
@ echo " store Execute the storage data routine."
@ echo " analyze Execute the analysis data routine."
install-debian-deps:
sudo apt-get install -y python3 supervisor curl dialog
......@@ -42,5 +44,10 @@ pyserial:
python3 -i scripts/init_serial.py
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:
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)
def cstring(*args, **kwargs):
def colorstring(*args, **kwargs):
return TerminalColors.cstring(*args, **kwargs)
if __name__ == '__main__':
......
# -*- 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
......@@ -28,8 +34,8 @@ 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
from terminalcolors import colorprint, colorstring
import serial, datetime, time, struct
def validateInput():
'''
......@@ -74,11 +80,10 @@ def progressBar(percent, lenght=15, description =""):
'''
highlight = " "*int((lenght-2)*percent*1.0/100)
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;32m"+"\t{}%".format(percent)+"\033[0;0m"
print(printString, end='\r')
printS
def main():
args = validateInput()
......@@ -148,45 +153,47 @@ def main():
comm.close()
print("\nOperação finalizada com sucesso.")
def unpackDataResp(fileName, timeI, timeF):
fisiologfile = open(fileName)
yCard = []
yRespDir = []
yRespEsq = []
x = []
def unpackData(file_name):
log_file = open(file_name)
# Lendo HEADER
fisiologfile.readline()
frequency = fisiologfile.readline().replace('\n', '').split(' ')[4]
linha = fisiologfile.readline()
log_file.readline()
frequency = log_file.readline().replace('\n', '').split(' ')[4]
linha = log_file.readline()
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_h = linha.replace('\n','').split(' ')[7]
fisiologfile.readline()
fisiologfile.readline()
# Dados
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])
del(yRespDir[-1])
del(yRespEsq[-1])
del(x[-1])
return {'Freq':frequency, 'Date':date_time_d, 'Hour':date_time_h, 'Cardiogram':yCard, 'RespDir':yRespDir, 'RespEsq':yRespEsq, 'Time': x}
log_file.readline()
fields = log_file.readline().strip(' #(s)\n').split('\t')
data = {x:[] for x in fields}
for linha in log_file:
items = linha.replace('\n', '').split('\t')
for i, field in enumerate(fields):
data[field].append(float(items[i]))
log_file.close()
if(len(data[fields[0]]) % 2 != 0):
for item in data.values():
item.pop(-1)
header = {'Freq':frequency, 'Date':date_time_d, 'Hour':date_time_h}
data.update(header)
return data
def selectDataRange(data, key, t_in, t_fi):
if not key in data.keys():
return False
list_keys = [x for x in data.keys() if isinstance(data[x], list)]
out = {x:[] for x in data.keys() if x in list_keys}
out.update({x:y for (x,y) in zip(data.keys(), data.values()) if not x in list_keys})
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__':
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 @@
from array import *
from scipy.fftpack import fft, fftfreq, fftshift
import numpy as np
from armazenamento import unpackDataResp
from armazenamento import unpackData, selectDataRange
import sys, os, re, math
import matplotlib.pyplot as plt
......@@ -55,15 +55,14 @@ if not os.path.exists(sys.argv[1]):
# Atribuindo as váriaveis com os valores de entrada
parametro = sys.argv[1:]
log_file = parametro[0]
fisiologfile = open(log_file,'r')
t_inicial = int(parametro[1])
t_final = int(parametro[2])
n_filtro = int(parametro[3])
qtd_filtro = int(parametro[4])
freq_i = float(parametro[5])
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 = log_file
user_name = os.path.splitext(os.path.basename(log_file))[0]
png_name = 'Resp_{}_{}s_{}s_{}hz_{}hz.png'.format(user_name, t_inicial, t_final, freq_i, freq_f)
# ERRO:
# 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:
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)
data = unpackDataResp(log_file, t_inicial , t_final)
data = unpackData(log_file)
freq = float(data['Freq'])
N = len(data['Cardiogram'])
N = len(data['A0'])
T = 1.0/freq
dx = float(freq)/N
data = selectDataRange(data, 'Tempo', t_inicial, t_final)
# Inicialização de variáveis
x1 = array('f', data['Time'])
y1 = array('f', data['RespDir'])
y2 = array('f', data['RespEsq'])
x1 = array('f', data['Tempo'])
y1 = array('f', data['A0'])
y2 = array('f', data['A1'])
y1_filt = array('f', [])
y2_filt = array('f', [])
x_fft_plot = array('f', [])
......@@ -382,7 +382,7 @@ while True:
aux_str = aux_str[reg_exp.end():]
else:
break
local_dir += png_name
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