I need you to make my code follow the pep8 naming convention and make it more readable,…
- User
I need you to make my code follow the pep8 naming convention and make it more readable, I'll send you a block of code for each message, and you'll reply with the fixed block of code.
icm4300 over IIO (industrial io) library
##TODO LIST:
import time import os import signal #needed to catch CTRL+C and close the accelerometer properly import struct #necessario per "spacchettare" i dati binari ricevuti dall'accelerometro import ctypes from queue import Queue from datetime import datetime, timedelta, timezone
debug = True
Differenza in secondi tra tempo UTC e tempo GPS
GPS_TIME_TO_UTC_LEAP_SECONDS = 18
Definisco alcune costanti globali per rendere più comodo il riferimento ad accelerometri e giroscopi
"Indice" dei sensori:
ACCELEROMETER_DEVICE_INDEX = 0 GYROSCOPE_DEVICE_INDEX = 1
Possibili valori per la scala dell'accelerometro e del giroscopio:
ACCEL_FSR_2G = GYRO_FSR_250DPS = 0 ACCEL_FSR_4G = GYRO_FSR_500DPS = 1 ACCEL_FSR_8G = GYRO_FSR_1000DPS = 2 ACCEL_FSR_16G = GYRO_FSR_2000DPS = 3
Possibili valori per l'output data rate (ODR) dell'accelerometro e del giroscopio
ACCEL_ODR_12_5Hz = GYRO_ODR_12_5Hz = 12 ACCEL_ODR_25Hz = GYRO_ODR_25Hz = 25 ACCEL_ODR_50Hz = GYRO_ODR_50Hz = 50 ACCEL_ODR_100Hz = GYRO_ODR_100Hz = 100 ACCEL_ODR_200Hz = GYRO_ODR_200Hz = 200 ACCEL_ODR_400Hz = GYRO_ODR_400Hz = 400 ACCEL_ODR_800Hz = GYRO_ODR_800Hz = 800 #Il bus IIO sembra non sufficiente per supportare entrambi i sensori a 800+ hz. Possibile che le modalità ad alta velocità siano usabili solo su bus SPI. ACCEL_ODR_1600Hz = GYRO_ODR_1600Hz = 1600
Valori dell'header dei vari tipi di pacchetto mandati dall'accelerometro
ACCEL_HDR = 1 GYRO_HDR = 2 EMPTY_MARKER = 17 END_MARKER = 18
Dimensioni dei vari tipi di pacchetto mandati dall'accelerometro
ACCEL_DATA_SZ = 24 GYRO_DATA_SZ = 24 EMPTY_MARKER_SZ = 8 END_MARKER_SZ = 8
Queue di output
dataQueue = Queue(maxsize=0) #queue "illimitata"
Definisco alcune funzioni helper per scrivere sul "sysfs" (i "dispoitivi virtuali" sul filesystem configurati dal driver iio nel kernel linux)
def getParameter(path): try: with open(path, 'r') as param: return param.read() except Exception: print("Errore di I/O durante la lettura del parametro") #TODO: impostare come debug return False
def setParameter(path, value): value = str(value) #stiamo scrivendo su un "dispositivo a caratteri", anche valori numerici vanno scritti come stringa try: if debug: with open(path, 'r') as param: currentValue = param.read() print(f"Valore attuale di {path}: {currentValue}")
with open(path,'w') as param: if debug: print(f"Scrivendo il valore a: {value}") param.write(value) with open(path, 'r') as param: updatedValue = param.read() # Sanity check: se il valore attuale non è quello che abbiamo impostato qualcosa è andato storto e potremmo avere parametri inaspettati nella config dell'accelerometro if updatedValue.strip() != value: if debug: print( f"Scrittura fallita: valore attuale: {value} | valore desiderato: {updatedValue}" ) return False except Exception: print("Errore di I/O durante la scrittura del parametro") #TODO: impostare come debug return False return True#I range di giroscopio e accelerometro sono particolari: si setta un valore indice da 0 a 3, ma si legge il valore nell'unità di misura "reale" (G o DPS) def setParameterNoCheck(path, value): #questa funzione imposta il parametro ma non ne verifica la corretta applicazione. Dovrà venir verificata a mano value = str(value) #stiamo scrivendo su un "dispositivo a caratteri", anche valori numerici vanno scritti come stringa try: with open(path,'w') as param: if debug: print(f"Scrivendo il valore a: {value}") param.write(value)
except Exception: print("Errore di I/O durante la scrittura del parametro") #TODO: impostare come debug return False return TrueQuesta funzione ritorna la matrice di orientamento del sensore sotto forma di lista
def getSensorOrientationMatrix(sensor): if str(sensor) == str(ACCELEROMETER_DEVICE_INDEX): # se mi sto riferendo all'accelerometro orientationMatrix = getParameter('/sys/bus/iio/devices/iio:device0/info_accel_matrix') if str(sensor) == str(GYROSCOPE_DEVICE_INDEX): # se mi sto riferendo al giroscopio orientationMatrix = getParameter('/sys/bus/iio/devices/iio:device0/info_anglvel_matrix')
if orientationMatrix is False: #se la matrice è "False" qualcosa è andato storto return False #Faccio il parsing della matrice in una lista di interi: return [int(x) for x in orientationMatrix.split(",")]Questa funzione abilita (1) o disabilita (0) il buffer. Ritorna True se l'operazione ha avuto successo, altrimenti ritorna False
def setBufferEnabledState(state): if state not in [0, 1]: return False state = str(state) return setParameter('/sys/bus/iio/devices/iio:device0/buffer/enable', state)
Questa funzione imposta la dimensione del buffer dell'accelerometro. Ritorna True se l'operazione ha avuto successo, altrimenti ritorna False
def setBufferSampleSize(sampleSize): if sampleSize < 0 or sampleSize > 32768: return False state = str(sampleSize) return setParameter( '/sys/bus/iio/devices/iio:device0/buffer/length', sampleSize )
- Assistant
ICM4300 over IIO (industrial IO) library
##TODO LIST:
import time import os import signal #needed to catch CTRL+C and close the accelerometer properly import struct #necessary to "unpack" binary data received from the accelerometer import ctypes from queue import Queue from datetime import datetime, timedelta, timezone
debug = True
Difference in seconds between UTC and GPS time
GPS_TIME_TO_UTC_LEAP_SECONDS = 18
Define some global constants for easier access to accelerometers and gyroscopes
Sensor "index":
ACCELEROMETER_DEVICE_INDEX = 0 GYROSCOPE_DEVICE_INDEX = 1
Possible values for the accelerometer and gyroscope scale:
ACCEL_FSR_2G = GYRO_FSR_250DPS = 0 ACCEL_FSR_4G = GYRO_FSR_500DPS = 1 ACCEL_FSR_8G = GYRO_FSR_1000DPS = 2 ACCEL_FSR_16G = GYRO_FSR_2000DPS = 3
Possible values for the output data rate (ODR) of the accelerometer and gyroscope
ACCEL_ODR_12_5_HZ = GYRO_ODR_12_5_HZ = 12 ACCEL_ODR_25_HZ = GYRO_ODR_25_HZ = 25 ACCEL_ODR_50_HZ = GYRO_ODR_50_HZ = 50 ACCEL_ODR_100_HZ = GYRO_ODR_100_HZ = 100 ACCEL_ODR_200_HZ = GYRO_ODR_200_HZ = 200 ACCEL_ODR_400_HZ = GYRO_ODR_400_HZ = 400 ACCEL_ODR_800_HZ = GYRO_ODR_800_HZ = 800 #IIO bus seems not fast enough to support both sensors at 800+ hz. High-speed modes may only be usable on SPI bus. ACCEL_ODR_1600_HZ = GYRO_ODR_1600_HZ = 1600
Header values of different package types sent by the accelerometer
ACCEL_HDR = 1 GYRO_HDR = 2 EMPTY_MARKER = 17 END_MARKER = 18
Sizes of different package types sent by the accelerometer
ACCEL_DATA_SZ = 24 GYRO_DATA_SZ = 24 EMPTY_MARKER_SZ = 8 END_MARKER_SZ = 8
Output Queue
data_queue = Queue(maxsize=0) #unlimited queue
Define some helper functions to write on "sysfs" (the "virtual devices" on the configured file system by the IIO driver in the Linux kernel)
def get_parameter(path): try: with open(path, 'r') as param: return param.read() except Exception: print("I/O error during parameter reading") #TODO: set as debug return False
def set_parameter(path, value): value = str(value) #we write on a "character device", even numeric values must be written as a string try: if debug: with open(path, 'r') as param: current_value = param.read() print(f"Current value of {path}: {current_value}")
with open(path, 'w') as param: if debug: print(f"Writing value to: {value}") param.write(value) with open(path, 'r') as param: updated_value = param.read() # Sanity check: if the current value is not the one we set, something went wrong and we might have unexpected parameters in the accelerometer config if updated_value.strip() != value: if debug: print( f"Writing failed: current value: {value} | desired value: {updated_value}" ) return False except Exception: print("I/O error during parameter writing") #TODO: set as debug return False return TrueThe gyroscope and accelerometer ranges are particular: an index value is set from 0 to 3, but the value in the "real" measurement unit (G or DPS) is read
def set_parameter_no_check(path, value): #this function sets the parameter but does not check its correct application. It will have to be checked manually value = str(value) #we write on a "character device", even numeric values must be written as a string try: with open(path, 'w') as param: if debug: print(f"Writing value to: {value}") param.write(value)
except Exception: print("I/O error during parameter writing") #TODO: set as debug return False return TrueThis function returns the sensor orientation matrix as a list
def get_sensor_orientation_matrix(sensor): if str(sensor) == str(ACCELEROMETER_DEVICE_INDEX): # if referring to the accelerometer orientation_matrix = get_parameter('/sys/bus/iio/devices/iio:device0/info_accel_matrix') if str(sensor) == str(GYROSCOPE_DEVICE_INDEX): # if referring to the gyroscope orientation_matrix = get_parameter('/sys/bus/iio/devices/iio:device0/info_anglvel_matrix')
if orientation_matrix is False: #if the matrix is "False" something went wrong return False #Parse the matrix into a list of integers: return [int(x) for x in orientation_matrix.split(",")]This function enables (1) or disables (0) the buffer. Returns True if the operation is successful, otherwise returns False
def set_buffer_enabled_state(state): if state not in [0, 1]: return False state = str(state) return set_parameter('/sys/bus/iio/devices/iio:device0/buffer/enable', state)
This function sets the buffer size of the accelerometer. Returns True if the operation is successful, otherwise returns False
def set_buffer_sample_size(sample_size): if sample_size < 0 or sample_size > 32768: return False state = str(sample_size) return set_parameter( '/sys/bus/iio/devices/iio:device0/buffer/length', sample_size )