Skip to content

Instantly share code, notes, and snippets.

@dangpzanco
Last active June 27, 2018 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dangpzanco/3456567200a9baa25dd7bace697850a6 to your computer and use it in GitHub Desktop.
Save dangpzanco/3456567200a9baa25dd7bace697850a6 to your computer and use it in GitHub Desktop.
Script em Python 3.6+ para ler os dados do KICO em modo RX. É um loop infinito, para parar o loop crie um arquivo chamado "kico.unlock" no mesmo diretório que o script estiver.
import serial
import sys
import csv
import pathlib
from datetime import datetime
def list_serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
:reference:
https://stackoverflow.com/a/14224477/2801287
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
with serial.Serial(port) as s:
result.append(port)
except (OSError, serial.SerialException):
pass
return result
# List all the available serial ports
serial_ports = list_serial_ports()
if len(serial_ports) == 0:
print('No serial ports available!')
sys.exit()
else:
print(f'Available serial ports: {serial_ports}')
# Only run loop if locked (kico.unlock does not exist)
# TO STOP THE LOOP YOU MUST CREATE A FILE CALLED 'kico.unlock'
# ON THE SAME DIRECTORY AS THIS PYTHON SCRIPT
unlock = False
# Set KICO's serial port (change this index if there are multiple devices)
kico_port = serial_ports[0]
# CSV header keynames (in order)
keys = ['index', 'time', 'rssi', 'error_rssi']
# Initialize dictionary from keys (with 0)
data = dict.fromkeys(keys, 0)
data['rssi'] = -120
# Get timestamp
timestamp = datetime.now().isoformat().replace(':','')
# Set CSV filename
csv_name = 'kico_data' + timestamp + '.csv'
# Just write the CSV header
with open(csv_name, 'w', newline='') as f:
w = csv.DictWriter(f, keys)
w.writeheader()
# Statistics
error_count = 0
while not unlock:
# Indexing
data['index'] += 1
data['time'] = datetime.now().isoformat()
# Error indicator
data['error_rssi'] = 0
with serial.Serial(kico_port, baudrate=115200) as ser:
# Try to read the RSSI data, if it fails keep the last RSSI value
try:
val = str(ser.readline()).split(' ')[-1].replace('\\r\\n\'','')
data['rssi'] = int(float(val))
except ValueError as e:
data['error_rssi'] = 1
error_count += 1
# Save dictionary to a CSV line and print line (as a list)
with open(csv_name, 'a', newline='') as f:
w = csv.DictWriter(f, keys)
w.writerow(data)
print(list(w._dict_to_list(data)))
# Check if the loop should stop (unlock the logged data)
if pathlib.Path('kico.unlock').exists():
unlock = True
print('Collected {i} RSSI values with {e} error(s) ({p}% error rate).'.format(
i=data['index'],e=error_count,p=error_count/data['index']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment