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

ADD: python requeriments, ATT:storeBinData

parent 5ce38a43
.build .build
sources/python/ sources/python/
sources/*.log
sources/*.logbin
...@@ -15,7 +15,8 @@ help: ...@@ -15,7 +15,8 @@ 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 " 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: install-debian-deps:
sudo apt-get install -y python3 supervisor curl dialog sudo apt-get install -y python3 supervisor curl dialog
...@@ -26,48 +27,23 @@ install-pip3: ...@@ -26,48 +27,23 @@ install-pip3:
rm get-pip.py rm get-pip.py
install-python-deps: install-pip3 install-python-deps: install-pip3
sudo pip3 install -U virtualenv sudo pip3 install -r scripts/requirements.pip
install-platformio: install-platformio:
sudo python -c "$$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)" 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 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: firmware:
python3 scripts/run_platformio.py python3 scripts/run_platformio.py
serial: check-venv serial:
${VENVPY} scripts/init_serial.py --loop python3 scripts/init_serial.py --loop
pyserial: check-venv
${VENVPY} -i scripts/init_serial.py
syncrtc:
${VENVPY} scripts/init_serial.py --syncrtc
boardhash: pyserial:
${VENVPY} scripts/getboardhash.py python3 -i scripts/init_serial.py
run: check-venv run:
${VENVPY} logger/run.py python3 logger/run.py
...@@ -36,7 +36,8 @@ sobre a licença GPL v3, como também os arquivos: ...@@ -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 /* Criando estruturas de dados para definir como será enviado os
dados de comunicação*/ dados de comunicação*/
struct{ struct{
short int controlFlag = 0xAAAA; byte controlFlag01 = 0xAA;
byte controlFlag02 = 0xAA;
short int frequency = FREQUENCY;; short int frequency = FREQUENCY;;
}headerStruct; }headerStruct;
...@@ -54,12 +55,7 @@ Interface interface(&measures, 1000.0/FREQUENCY); ...@@ -54,12 +55,7 @@ Interface interface(&measures, 1000.0/FREQUENCY);
void setup(){ void setup(){
/* Iniciando comunicação serial*/ /* Iniciando comunicação serial*/
Serial.begin(115200); Serial.begin(115200);
while(!Serial){
}
delay(50);
commHeader.send(); commHeader.send();
delay(50);
} }
void loop(){ void loop(){
......
pyserial==3.0.1
pythondialog==3.2.0
...@@ -15,9 +15,11 @@ def get_plataformio_serial_ports(): ...@@ -15,9 +15,11 @@ def get_plataformio_serial_ports():
''' '''
serial_raw = shexec("platformio serialports list").splitlines() serial_raw = shexec("platformio serialports list").splitlines()
if serial_raw == []:
return [("ERRO", "ERRO: nenhuma porta serial encontrada")]
else:
serial_ports = [serial_raw[i-1] serial_ports = [serial_raw[i-1]
for i,x in enumerate(serial_raw) if '----' in x] for i,x in enumerate(serial_raw) if '----' in x]
return [(x,x) for x in serial_ports] return [(x,x) for x in serial_ports]
...@@ -69,6 +71,7 @@ def exec_dialog_select_board(): ...@@ -69,6 +71,7 @@ def exec_dialog_select_board():
def platformio_setup(source_dir, build_dir='.build'): def platformio_setup(source_dir, build_dir='.build'):
board_name = exec_dialog_select_board() board_name = exec_dialog_select_board()
serial_port = exec_dialog_select_serial_port() serial_port = exec_dialog_select_serial_port()
if serial_port != "ERRO":
os.system(""" os.system("""
rm -rf {build_dir} && rm -rf {build_dir} &&
mkdir -p {build_dir} && mkdir -p {build_dir} &&
...@@ -77,7 +80,8 @@ def platformio_setup(source_dir, build_dir='.build'): ...@@ -77,7 +80,8 @@ def platformio_setup(source_dir, build_dir='.build'):
cp -r ../{source_dir}/* src/. && cp -r ../{source_dir}/* src/. &&
platformio run -t upload --upload-port {serial_port} platformio run -t upload --upload-port {serial_port}
""".format(**locals()).strip()) """.format(**locals()).strip())
else:
os.system("clear")
platformio_setup(source_dir=SOURCE_DIR) platformio_setup(source_dir=SOURCE_DIR)
This diff is collapsed.
...@@ -25,9 +25,9 @@ ...@@ -25,9 +25,9 @@
''' '''
STRUCT_DATA = 'h' 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 import sys, serial, datetime, os, time, struct
...@@ -58,13 +58,7 @@ def validateInput(): ...@@ -58,13 +58,7 @@ def validateInput():
def initSerial(port, baud): def initSerial(port, baud):
# Iniciando comunicação serial # Iniciando comunicação serial
ser = serial.Serial(port, baudrate = baud, ser = serial.Serial(port, baud)
bytesize = serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=None,
xonxoff=0,
rtscts=0)
# Limpando buffer para retirar as medidas feitas antes de iniciar o software # Limpando buffer para retirar as medidas feitas antes de iniciar o software
ser.dtr = False # Desliga DTR ser.dtr = False # Desliga DTR
time.sleep(1) time.sleep(1)
...@@ -78,44 +72,58 @@ def progressBar(percent, lenght): ...@@ -78,44 +72,58 @@ def progressBar(percent, lenght):
DOC dos ANSII caracters: DOC dos ANSII caracters:
http://ascii-table.com/ansi-escape-sequences.php 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)) notHighlight = " "*(lenght-2- len(highlight))
print("\033[{}D\t|\033[1;42m{}\033[0;0m{}| {}%".format(lenght+20, highlight, printString = "\t"+"\033[47m"+" "+"\033[42m"+"{}".format(highlight)+ \
notHighlight, percent)) "\033[0;0m"+"{}".format(notHighlight)+ "\033[47m"+" "\
"\033[0;32m"+"\t{}%".format(percent)+"\033[0;0m"
print(printString, end='\r')
def main(args): def main(args):
serial = initSerial(args['SerialPort'], args['BaudRate'])
# Recebendo HEADER de controle
print("Lendo cabeçalho de controle...")
while True: while True:
try: try:
dataLen = int(struct.unpack('B', serial.read(1))[0]) comm = initSerial(args['SerialPort'], args['BaudRate'])
rawData = serial.read(dataLen) # 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) 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 break
print("Leitura falhou. Reiniciando.") print("Leitura falhou. Reiniciando.")
except: except KeyboardInterrupt:
print("Leitura falhou. Reiniciando.") 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)) print("Frequência de operação é de {} Hz.".format(freq))
scriptTime = int(freq*args['ExecTime']) scriptTime = int(freq*args['ExecTime'])
dataFile = open(args['FileName'],'w') dataFile = open(args['FileName'],'w')
dataFileBin = open(args['FileName']+'bin','wb') 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 timeCounter = 0
print("Iniciando aquisição de dados.") print("Iniciando aquisição de dados.")
while (timeCounter <= scriptTime or scriptTime == 0): while (timeCounter <= scriptTime or scriptTime == 0):
timeCounter += 1 timeCounter += 1
if not(timeCounter % int(scriptTime/50)): if not(timeCounter % int(scriptTime/100)):
progressBar(int(timeCounter/scriptTime*100), 40) progressBar(int(timeCounter*1.0/scriptTime*100), 40)
print("\033[2A")
try: try:
dataLen = int(struct.unpack('B',serial.read(1))[0]) dataLen = int(struct.unpack('B', comm.read(1))[0])
rawData = serial.read(dataLen) rawData = comm.read(dataLen)
data = struct.unpack(STRUCT_DATA, rawData) data = struct.unpack(STRUCT_DATA, rawData)
# Arquivo de log # Arquivo de log
dataFile = open(args['FileName'],'a') dataFile = open(args['FileName'],'a')
...@@ -126,10 +134,15 @@ def main(args): ...@@ -126,10 +134,15 @@ def main(args):
dataFileBin.close() dataFileBin.close()
except KeyboardInterrupt: 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() comm.close()
print("\033[1BOperação finalizada com sucesso.") print("\nOperação finalizada com sucesso.")
if __name__== '__main__': if __name__== '__main__':
args = validateInput() 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