def get_readings(self, readings, num): """Description: method gets string message from the comm controller and try parses it into float :param: List of readings :param: Number of readings :returns: List of appended readings or single reading :raise: ValueError if number provided is invalid """ def get(): """Description: methods get single reading from device""" temp = StaticUtils.float_try_parse(self.comm_serial.read_buffer()) while (temp is None) or (not temp[1]): StaticUtils.print_message( CMD_ERROR, "Failed to float parse (get): " + temp) temp = StaticUtils.float_try_parse( self.comm_serial.read_buffer()) if (temp is not None) and (temp[1]): return round(temp[0], 2) if (readings is not None) and (num > 0): while num > 0: readings.append(int(get() * 100)) num -= 1 else: StaticUtils.print_message( CMD_ERROR, "Failed to check provided arguments (get_reading): [" + str(readings) + "] [" + str(num)) readings = [] return readings
def get_port_details(device_num): """Description: method gets serial port details""" def is_valid_input(message): """Description: method checks if provided input is valid""" def is_valid_serial(port): """Description: method checks if provided serial name is valid""" return (comm_utils.SERIAL_PORT_START_UNIX in port) or \ (comm_utils.SERIAL_PORT_START_WIN in port) if not ((not message) or (message == "")): message = message.split(':') if is_valid_serial(message[0]): if len(message) == 3: if (StaticUtils.int_try_parse(message[1])[1]) and\ (StaticUtils.int_try_parse(message[2])[1]): return True elif len(message) == 2: if (StaticUtils.int_try_parse(message[1]))[1]: return True return False temp = None # ask for a valid command until received while not is_valid_input(temp): StaticUtils.print_message(comm_utils.CMD_ERROR, comm_utils.INVALID_PORT_EXCEPTION) temp = input( "Device %d, Specify device port, baudrate (opt. timeout)" "\n{PORT}:{BAUDRATE}:{TIMEOUT}\n" % device_num) return temp
def assign_port(port, baudrate, time=3): """Description: method creates serial port object""" try: serial_port = Serial(port, baudrate, timeout=time) return serial_port except SerialException as e: StaticUtils.print_message(CMD_ERROR, str(e)) return None
def run(self): """Description: threads runnable method""" while self.board.state != game_utils.EXIT: while self.is_open() and self.board.state == game_utils.IN_GAME: if (StaticUtils.get_millis() - self.started) > 500: self.reading = self.get_readings([], 1)[0] self.started = StaticUtils.get_millis() # close serial on exit self.close()
def serial_open(self): """Description: method opens serial port""" if not self.serial.is_open: self.serial.open() StaticUtils.print_message( CMD_OK, "Serial port " + self.port + " have been opened.") else: StaticUtils.print_message(CMD_ERROR, comm_utils.OPENED_CONNECTION_EXCEPTION)
def calibrate_device(self): """Description: method calibrates middle point of the device""" StaticUtils.print_message(comm_utils.CMD_OK, "Calibrating Player " + self.name) self.device.open() self.device.calibrate() self.device.close() StaticUtils.print_message( comm_utils.CMD_RESPONSE, "Player middle point: " + self.device.middle_point)
def get(): """Description: methods get single reading from device""" temp = StaticUtils.float_try_parse(self.comm_serial.read_buffer()) while (temp is None) or (not temp[1]): StaticUtils.print_message( CMD_ERROR, "Failed to float parse (get): " + temp) temp = StaticUtils.float_try_parse( self.comm_serial.read_buffer()) if (temp is not None) and (temp[1]): return round(temp[0], 2)
def calibrate_min(self): """Description: method calibrates device minimum point""" StaticUtils.print_message(comm_utils.CMD_OK, "Calibrating Player " + self.name) self.device.open() self.device.calibrate_min() self.device.close() self.device.minimum_point = 75328 StaticUtils.print_message( comm_utils.CMD_RESPONSE, "Player " + self.name + " minimum point is -- " + str(self.device.minimum_point))
def check_equal_ports(name_1, name_2): """Description: function checks if port names are identical :param name_1: Port 1 name :param name_2: Port 2 name """ while name_1[0] == name_2[0]: StaticUtils.print_message(comm_utils.CMD_ERROR, comm_utils.IDENTICAL_PORTS_EXCEPTION) name_1 = get_port_details(1) name_2 = get_port_details(2) name_1 = name_1.split(':') name_2 = name_2.split(':')
def write_serial(self, str_msg): """Description: method send the message over opened serial port :param: Message to send """ msg = str_msg.encode('utf-8', 'ignore') try: self.serial.write(msg) except SerialException: StaticUtils.print_message(CMD_ERROR, comm_utils.CONNECTION_EXCEPTION) except TypeError: StaticUtils.print_message(CMD_ERROR, "Failed to send bytes: " + str(msg))
def read_buffer(self): """Description: method reads incoming messages on the opened serial port :return: Decoded message read from the buffer """ msg = "" try: if self.serial.inWaiting(): msg = self.serial.readline() msg = msg.decode('utf-8', 'ignore') msg = msg[:6] print("Parsed message: " + msg) except SerialException: StaticUtils.print_message(CMD_ERROR, "Failed to read buffer") return msg
def transform_to_pixel(self, reading): """Description: method transforms device readings into player pad position :param: Device reading :return: Pad pixel position or None in exception """ try: coord_y = int( (reading - self.device.minimum_point) * 100 / (self.device.maximum_point - self.device.minimum_point)) return int((game_utils.B_HEIGHT - self.height - (game_utils.OFFSET_HEIGHT * 2)) * coord_y * .01) except TypeError: StaticUtils.print_message(comm_utils.CMD_ERROR, "Bad reading: " + str(reading)) return None
def is_valid_input(message): """Description: method checks if provided input is valid""" def is_valid_serial(port): """Description: method checks if provided serial name is valid""" return (comm_utils.SERIAL_PORT_START_UNIX in port) or \ (comm_utils.SERIAL_PORT_START_WIN in port) if not ((not message) or (message == "")): message = message.split(':') if is_valid_serial(message[0]): if len(message) == 3: if (StaticUtils.int_try_parse(message[1])[1]) and\ (StaticUtils.int_try_parse(message[2])[1]): return True elif len(message) == 2: if (StaticUtils.int_try_parse(message[1]))[1]: return True return False
def __init__(self, args, board): threading.Thread.__init__(self) self.comm_serial = CommSerial(args) self.board = board self.minimum_point = 0 self.maximum_point = 1 self.reading = 0 self.started = StaticUtils.get_millis() self.middle_point = 0
def calibrate(self): """Description: method takes 100 reading from the device and calculates middle point""" # prepare readings list readings = self.get_readings([], comm_utils.CALIBRATION_DATA_SIZE) # find regular mean reg_mean = StaticUtils.mean(readings) # sort readings and find median value StaticUtils.merge_sort(readings, 0, len(readings) - 1) median = StaticUtils.median(readings) # format readings from extreme values and find trimmed mean readings = StaticUtils.format_readings( readings, int(comm_utils.CALIBRATION_DATA_SIZE * .2)) trim_mean = StaticUtils.mean(readings) self.middle_point = (reg_mean + median + trim_mean) / 3 self.reading = self.middle_point
def calibrate_max(self): """Description: method takes 5 readings and sets maximum point""" self.maximum_point = StaticUtils.mean(self.get_readings([], 5))
def serial_close(self): """Description: method closes serial port""" self.serial.close() StaticUtils.print_message( CMD_OK, "Serial port " + self.port + " have been closed.")
def start_game(): """Description: method starts game""" def get_port_details(device_num): """Description: method gets serial port details""" def is_valid_input(message): """Description: method checks if provided input is valid""" def is_valid_serial(port): """Description: method checks if provided serial name is valid""" return (comm_utils.SERIAL_PORT_START_UNIX in port) or \ (comm_utils.SERIAL_PORT_START_WIN in port) if not ((not message) or (message == "")): message = message.split(':') if is_valid_serial(message[0]): if len(message) == 3: if (StaticUtils.int_try_parse(message[1])[1]) and\ (StaticUtils.int_try_parse(message[2])[1]): return True elif len(message) == 2: if (StaticUtils.int_try_parse(message[1]))[1]: return True return False temp = None # ask for a valid command until received while not is_valid_input(temp): StaticUtils.print_message(comm_utils.CMD_ERROR, comm_utils.INVALID_PORT_EXCEPTION) temp = input( "Device %d, Specify device port, baudrate (opt. timeout)" "\n{PORT}:{BAUDRATE}:{TIMEOUT}\n" % device_num) return temp def check_equal_ports(name_1, name_2): """Description: function checks if port names are identical :param name_1: Port 1 name :param name_2: Port 2 name """ while name_1[0] == name_2[0]: StaticUtils.print_message(comm_utils.CMD_ERROR, comm_utils.IDENTICAL_PORTS_EXCEPTION) name_1 = get_port_details(1) name_2 = get_port_details(2) name_1 = name_1.split(':') name_2 = name_2.split(':') StaticUtils.print_banner() # get serial ports details port1_check, port2_check = False, True port1, port2 = None, None while not port1_check or not port2_check: port1 = get_port_details(1) # port2 = get_port_details(2) port1 = port1.split(':') # port2 = port2.split(':') # check_equal_ports(port1[0], port2[0]) try: test_comm_serial = Serial(port1[0], int(port1[1])) test_comm_serial.close() port1_check = True except SerialException as e: StaticUtils.print_message(comm_utils.CMD_ERROR, str(e)) # try: # test_comm_serial = Serial(port2[0], int(port2[1])) # test_comm_serial.close() # port3_check = True # except SerialException as e: # StaticUtils.print_message(str(e)) board = Board(port1, port2=[]) board.run()