import atexit from enum import Enum from compLib.LogstashLogging import Logging from compLib.MetricsLogging import MetricsLogging from compLib.Spi import Spi, Register MOTOR_COUNT = 4 encoder_start_values = [0] * (MOTOR_COUNT + 1) class Encoder(object): """Class used to read the encoders """ @staticmethod def read_raw(port: int) -> int: """Read raw encoder from a specified port. Will not be reset to 0 at start. :param port: Port, which the motor is connected to. Between 1 and 4 :raises: IndexError :return: Current encoder position """ if port <= 0 or port > MOTOR_COUNT: raise IndexError("Invalid encoder port specified!") if port == 1: return Spi.read(Register.MOTOR_1_POS_B3, 4) elif port == 2: return Spi.read(Register.MOTOR_2_POS_B3, 4) elif port == 3: return Spi.read(Register.MOTOR_3_POS_B3, 4) elif port == 4: return Spi.read(Register.MOTOR_4_POS_B3, 4) @staticmethod def read(port: int) -> int: """Read encoder from a specified port :param port: Port, which the motor is connected to. Between 1 and 4 :raises: IndexError :return: Current encoder position """ if port <= 0 or port > MOTOR_COUNT: raise IndexError("Invalid encoder port specified!") diff = Encoder.read_raw(port) - encoder_start_values[port] if diff > 2 ** 31: diff -= 2 ** 32 MetricsLogging.put("Encoder", diff, port) return diff @staticmethod def clear(port: int): """Reset encoder position to 0 :param port: Port, which the motor is connected to. Between 1 and 4 :raises: IndexError """ if port <= 0 or port > MOTOR_COUNT: raise IndexError("Invalid encoder port specified!") encoder_start_values[port] = Encoder.read_raw(port) @staticmethod def clear_all(): """Reset all encoder positions to 0 """ for i in range(1, MOTOR_COUNT + 1): encoder_start_values[i] = Encoder.read_raw(i)