Commit 57132aa5 authored by Béuren F. Bechlin's avatar Béuren F. Bechlin

ADD: python requeriments, ATT:storeBinData

parent 5ce38a43
.build
sources/python/
sources/*.log
sources/*.logbin
......@@ -15,7 +15,8 @@ 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 " run Execute the logger on the foreground. Hit Ctrl+C to stop it."
@ echo " store Execute the logger on the foreground. Hit Ctrl+C to stop it."
@ echo " analyse Execute the analyses data routine"
install-debian-deps:
sudo apt-get install -y python3 supervisor curl dialog
......@@ -26,48 +27,23 @@ install-pip3:
rm get-pip.py
install-python-deps: install-pip3
sudo pip3 install -U virtualenv
sudo pip3 install -r scripts/requirements.pip
install-platformio:
sudo python -c "$$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)"
setup: install-debian-deps install-python-deps install-platformio venv
venv: clean-venv
@ echo "-------------------------------------------------------"
virtualenv -v --python='${PYBIN}' ${VENVDIR} --no-site-packages
${VENVDIR}/bin/pip install -r logger/requirements.pip
@ echo "-------------------------------------------------------"
@ echo "Required Python virtual environment sucessfully installed at "
@ du -sh ${VENVDIR}
clean-venv:
rm -rf ${VENVDIR}
check-venv:
@ command -v ${VENVPY} >/dev/null 2>&1 || \
{ printf "You need to prepare the required Python virtual environment";\
printf "\nfor running this software. Excecute, just once:";\
printf "\n\n $$ make setup\n\nor\n\n ";\
printf "$$ make setup PYBIN=<python_binary>\n\nfor specifying a ";\
printf "Python binary other than 'python3', like\n'python-3.x' ";\
printf "(where x is a number) for instance. \n\n"; exit 1; }
firmware:
python3 scripts/run_platformio.py
serial: check-venv
${VENVPY} scripts/init_serial.py --loop
pyserial: check-venv
${VENVPY} -i scripts/init_serial.py
syncrtc:
${VENVPY} scripts/init_serial.py --syncrtc
serial:
python3 scripts/init_serial.py --loop
boardhash:
${VENVPY} scripts/getboardhash.py
pyserial:
python3 -i scripts/init_serial.py
run: check-venv
${VENVPY} logger/run.py
run:
python3 logger/run.py
......@@ -36,7 +36,8 @@ sobre a licença GPL v3, como também os arquivos:
/* Criando estruturas de dados para definir como será enviado os
dados de comunicação*/
struct{
short int controlFlag = 0xAAAA;
byte controlFlag01 = 0xAA;
byte controlFlag02 = 0xAA;
short int frequency = FREQUENCY;;
}headerStruct;
......@@ -54,12 +55,7 @@ Interface interface(&measures, 1000.0/FREQUENCY);
void setup(){
/* Iniciando comunicação serial*/
Serial.begin(115200);
while(!Serial){
}
delay(50);
commHeader.send();
delay(50);
}
void loop(){
......
pyserial==3.0.1
pythondialog==3.2.0
......@@ -15,9 +15,11 @@ def get_plataformio_serial_ports():
'''
serial_raw = shexec("platformio serialports list").splitlines()
serial_ports = [serial_raw[i-1]
if serial_raw == []:
return [("ERRO", "ERRO: nenhuma porta serial encontrada")]
else:
serial_ports = [serial_raw[i-1]
for i,x in enumerate(serial_raw) if '----' in x]
return [(x,x) for x in serial_ports]
......@@ -69,15 +71,17 @@ def exec_dialog_select_board():
def platformio_setup(source_dir, build_dir='.build'):
board_name = exec_dialog_select_board()
serial_port = exec_dialog_select_serial_port()
os.system("""
rm -rf {build_dir} &&
mkdir -p {build_dir} &&
cd {build_dir} &&
yes | platformio init --board {board_name} &&
cp -r ../{source_dir}/* src/. &&
platformio run -t upload --upload-port {serial_port}
""".format(**locals()).strip())
if serial_port != "ERRO":
os.system("""
rm -rf {build_dir} &&
mkdir -p {build_dir} &&
cd {build_dir} &&
yes | platformio init --board {board_name} &&
cp -r ../{source_dir}/* src/. &&
platformio run -t upload --upload-port {serial_port}
""".format(**locals()).strip())
else:
os.system("clear")
platformio_setup(source_dir=SOURCE_DIR)
This diff is collapsed.
......@@ -25,9 +25,9 @@
'''
STRUCT_DATA = 'h'
STRUCT_HEADER = 'hh'
STRUCT_HEADER = 'Hh'
# Exemplo: python armazenamento.py /dev/ttyACM0 115200 coleta_Nome_Exemplo_1min.log 30
# Exemplo: python storeBinData.py /dev/ttyACM0 115200 coleta_Nome_Exemplo_1min.log 30
import sys, serial, datetime, os, time, struct
......@@ -58,13 +58,7 @@ def validateInput():
def initSerial(port, baud):
# Iniciando comunicação serial
ser = serial.Serial(port, baudrate = baud,
bytesize = serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=None,
xonxoff=0,
rtscts=0)
ser = serial.Serial(port, baud)
# Limpando buffer para retirar as medidas feitas antes de iniciar o software
ser.dtr = False # Desliga DTR
time.sleep(1)
......@@ -78,44 +72,58 @@ def progressBar(percent, lenght):
DOC dos ANSII caracters:
http://ascii-table.com/ansi-escape-sequences.php
'''
highlight = " "*int((lenght-2)*percent/100)
highlight = " "*int((lenght-2)*percent*1.0/100)
notHighlight = " "*(lenght-2- len(highlight))
print("\033[{}D\t|\033[1;42m{}\033[0;0m{}| {}%".format(lenght+20, highlight,
notHighlight, percent))
printString = "\t"+"\033[47m"+" "+"\033[42m"+"{}".format(highlight)+ \
"\033[0;0m"+"{}".format(notHighlight)+ "\033[47m"+" "\
"\033[0;32m"+"\t{}%".format(percent)+"\033[0;0m"
print(printString, end='\r')
def main(args):
serial = initSerial(args['SerialPort'], args['BaudRate'])
# Recebendo HEADER de controle
print("Lendo cabeçalho de controle...")
while True:
try:
dataLen = int(struct.unpack('B', serial.read(1))[0])
rawData = serial.read(dataLen)
comm = initSerial(args['SerialPort'], args['BaudRate'])
# Recebendo HEADER de controle
print("Lendo cabeçalho de controle...")
dataLen = int(struct.unpack('B', comm.read(1))[0])
rawData = comm.read(dataLen)
flagControl, freq = struct.unpack(STRUCT_HEADER, rawData)
if flagControl == -21846: # 0xAAAA
# Protocolo de comunicação usado envia os bytes 0xAA e 0xAA para
# indicar que o HEADER está sendo enviado
if flagControl == 0xAAAA:
break
print("Leitura falhou. Reiniciando.")
except:
print("Leitura falhou. Reiniciando.")
except KeyboardInterrupt:
sys.exit()
except struct.error:
print("Problemas com comunicação. Por favor reenvie o firmware para\
a placa")
sys.exit()
print("Frequência de operação é de {} Hz.".format(freq))
scriptTime = int(freq*args['ExecTime'])
dataFile = open(args['FileName'],'w')
dataFileBin = open(args['FileName']+'bin','wb')
dataFile.write(str(freq)+"\n")
dataFileBin.write(struct.pack('h',freq))
dataFile.write("# ----CTA||IF||UFRGS---- RESPIRÔMETRO LOGGER\n")
dataFile.write("# Frequencia de operação: "+str(freq)+"\n")
dataFileBin.write(struct.pack('h',freq))
# Registra horário atual
now = datetime.datetime.now()
dataFile.write("# Data do início da coleta: " + \
now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]+"\n")
dataFile.write("# Tempo estimado de coleta: {}s\n".format(args['ExecTime']))
timeCounter = 0
print("Iniciando aquisição de dados.")
while (timeCounter <= scriptTime or scriptTime == 0):
timeCounter += 1
if not(timeCounter % int(scriptTime/50)):
progressBar(int(timeCounter/scriptTime*100), 40)
print("\033[2A")
if not(timeCounter % int(scriptTime/100)):
progressBar(int(timeCounter*1.0/scriptTime*100), 40)
try:
dataLen = int(struct.unpack('B',serial.read(1))[0])
rawData = serial.read(dataLen)
dataLen = int(struct.unpack('B', comm.read(1))[0])
rawData = comm.read(dataLen)
data = struct.unpack(STRUCT_DATA, rawData)
# Arquivo de log
dataFile = open(args['FileName'],'a')
......@@ -126,10 +134,15 @@ def main(args):
dataFileBin.close()
except KeyboardInterrupt:
break
print("\nTecla de escape prescionada. Abortando")
sys.exit()
except serial.serialutil.SerialException:
print("\nComunicação serial foi interrompida. Abortando")
sys.exit()
serial.close()
print("\033[1BOperação finalizada com sucesso.")
comm.close()
print("\nOperação finalizada com sucesso.")
if __name__== '__main__':
args = validateInput()
......
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