def __init__(self, host, console, hal): t = threading.Thread(target=self.run_server) self.payload = { 'image': '', 'lap': '', 'map': '', 'v': '', 'w': '', 'text_buffer': '' } self.server = None self.client = None self.host = host # Image variables self.image_to_be_shown = None self.image_to_be_shown_updated = False self.image_show_lock = threading.Lock() self.acknowledge = False self.acknowledge_lock = threading.Lock() # Take the console object to set the same websocket and client self.console = console self.hal = hal t.start() # Create the lap object pose3d_object = ListenerPose3d("/F1ROS/odom") self.lap = Lap(pose3d_object) self.map = Map(pose3d_object)
def _parse_lap_results(self, buffer_, position): """Parse the lap result section.""" logging.info('Parsing lap results section.') len_ = (buffer_[position + 2] << 4) + buffer_[position + 1] self.report.lr_data_seg = self._bcd2hex(buffer_[position + 4]) self.report.lr_data_min = self._bcd2hex(buffer_[position + 5]) self.report.lr_data_hour = self._bcd2hex(buffer_[position + 6]) self.report.lr_data_day = self._bcd2hex(buffer_[position + 7]) self.report.lr_data_month = self._bcd2hex(buffer_[position + 8]) self.report.lr_data_year = self._bcd2hex(buffer_[position + 9]) + 2000 lap_offset = 10 id_ = 0 while lap_offset < len_ + 3: lap = Lap(id_) lap.seg = self._bcd2hex(buffer_[position + lap_offset]) lap.min = self._bcd2hex(buffer_[position + lap_offset + 1]) lap.hour = self._bcd2hex(buffer_[position + lap_offset + 2]) lap.hr = buffer_[position + lap_offset + 3] self.report.laps.append(lap) lap_offset = lap_offset + 7 id_ = id_ + 1 final_byte = position + len_ + 4 logging.debug(map(hex, buffer_[position:final_byte])) return final_byte
def test_get_last_lap(self): lap1 = Lap("1", "1:02.852", "44,275", "23:49:08.277") lap2 = Lap("2", "1:02.852", "44,275", "23:49:08.277") self.assertIsNone(self.__pilot.get_last_lap()) self.__pilot.add_lap(lap2) self.__pilot.add_lap(lap1) self.assertEqual(lap2, self.__pilot.get_last_lap())
def __init__(self, host): rospy.init_node("GUI") self.payload = {'image': '','lap': '', 'map': '', 'v':'','w':''} self.server = None self.client = None self.host = host # Image variable self.shared_image = SharedImage("guiimage") # Get HAL variables self.shared_v = SharedValue("velocity") self.shared_w = SharedValue("angular") # Create the lap object pose3d_object = ListenerPose3d("/F1ROS/odom") self.lap = Lap(pose3d_object) self.map = Map(pose3d_object) # Event objects for multiprocessing self.ack_event = multiprocessing.Event() self.cli_event = multiprocessing.Event() # Start server thread t = threading.Thread(target=self.run_server) t.start()
def get_pilot_data(self): log_file = open("log.txt", "r") first_line = True list_of_pilots = {} for line in log_file: if first_line: first_line = not first_line continue log_line = LogLine(line) if log_line.get_pilot_code() in list_of_pilots: pilot = list_of_pilots.get(log_line.get_pilot_code()) else: pilot = Pilot(log_line.get_pilot_code(), log_line.get_pilot_name()) list_of_pilots[pilot.get_code()] = pilot lap = Lap(log_line.get_lap_number(), log_line.get_lap_time(), log_line.get_lap_average_speed(), log_line.get_lap_hour()) pilot.add_lap(lap) log_file.close() return list_of_pilots
class TestLap(unittest.TestCase): @classmethod def setUp(self): self.__lap = Lap("1", "1:02.852", "44,275", "23:49:08.277") def test_get_number(self): self.assertEqual(1, self.__lap.get_number()) def test_get_average_speed(self): self.assertEqual(44.275, self.__lap.get_average_speed()) def test_get_time(self): temp_timedelta = timedelta(minutes=1, seconds=2, microseconds=852000) self.assertEqual(temp_timedelta, self.__lap.get_time()) def test_get_hour(self): temp_datetime = datetime(year=1900, month=1, day=1, hour=23, minute=49, second=8, microsecond=277000) self.assertEqual(temp_datetime, self.__lap.get_hour())
def __init__(self, host, console): t = threading.Thread(target=self.run_server) self.payload = {'canvas': None, 'image': '', 'shape': []} self.server = None self.client = None self.host = host self.payload_lock = threading.Lock() # Take the console object to set the same websocket and client self.console = console t.start() # Create the lap object pose3d_object = ListenerPose3d("/F1ROS/odom") self.lap = Lap(pose3d_object) self.map = Map(pose3d_object)
def test_sum_lap_time(self): lap1 = Lap("1", "1:02.852", "44,275", "23:49:08.277") lap2 = Lap("2", "1:02.851", "44,275", "23:49:08.277") self.__pilot.add_lap(lap2) self.__pilot.add_lap(lap1) self.assertEqual(lap2.get_time() + lap1.get_time(), self.__pilot.sum_lap_time())
def test_get_interval_from_pilot(self): lap1 = Lap("1", "1:02.852", "44,275", "23:49:08.277") lap2 = Lap("2", "1:02.851", "63,235", "23:49:08.277") pilot2 = Pilot("037", "R.MASSA") self.assertEqual("N/D", self.__pilot.get_interval_from_pilot(pilot2)) self.__pilot.add_lap(lap2) self.__pilot.add_lap(lap1) lap1 = Lap("1", "1:02.852", "44,275", "23:49:08.277") lap2 = Lap("2", "1:02.851", "63,235", "23:49:08.277") pilot2.add_lap(lap2) pilot2.add_lap(lap1) pilot3 = Pilot("037", "R.MASSA") lap1 = Lap("1", "1:02.852", "44,275", "23:49:08.277") pilot3.add_lap(lap1) self.assertEqual(timedelta(), self.__pilot.get_interval_from_pilot(pilot2)) self.assertEqual("N/D", self.__pilot.get_interval_from_pilot(pilot3))
def add_lap(self, racer_id, time, begin): if racer_id not in self.racers: return -1 lap = Lap(time, self.new_lap_id(), begin) if not self.racers[racer_id].add_lap(lap): return -1 self.count += 1 self.total += time self.top_laps.put((time, (racer_id, lap.id))) if self.top_laps.qsize() > 30: pq = PriorityQueue() while pq.qsize() < 30: pq.put(self.top_laps.get()) self.top_laps = pq return lap.id
class GUI: # Initialization function # The actual initialization def __init__(self, host, console, hal): t = threading.Thread(target=self.run_server) self.payload = { 'image': '', 'lap': '', 'map': '', 'v': '', 'w': '', 'text_buffer': '' } self.server = None self.client = None self.host = host # Image variables self.image_to_be_shown = None self.image_to_be_shown_updated = False self.image_show_lock = threading.Lock() self.acknowledge = False self.acknowledge_lock = threading.Lock() # Take the console object to set the same websocket and client self.console = console self.hal = hal t.start() # Create the lap object pose3d_object = ListenerPose3d("/F1ROS/odom") self.lap = Lap(pose3d_object) self.map = Map(pose3d_object) # Explicit initialization function # Class method, so user can call it without instantiation @classmethod def initGUI(cls, host, console): # self.payload = {'image': '', 'shape': []} new_instance = cls(host, console) return new_instance # Function to prepare image payload # Encodes the image as a JSON string and sends through the WS def payloadImage(self): self.image_show_lock.acquire() image_to_be_shown_updated = self.image_to_be_shown_updated image_to_be_shown = self.image_to_be_shown self.image_show_lock.release() image = image_to_be_shown payload = {'image': '', 'shape': ''} if (image_to_be_shown_updated == False): return payload shape = image.shape frame = cv2.imencode('.JPEG', image)[1] encoded_image = base64.b64encode(frame) payload['image'] = encoded_image.decode('utf-8') payload['shape'] = shape self.image_show_lock.acquire() self.image_to_be_shown_updated = False self.image_show_lock.release() return payload # Function for student to call def showImage(self, image): self.image_show_lock.acquire() self.image_to_be_shown = image self.image_to_be_shown_updated = True self.image_show_lock.release() # Function to get the client # Called when a new client is received def get_client(self, client, server): self.client = client self.console.set_websocket(self.server, self.client) # Function to get value of Acknowledge def get_acknowledge(self): self.acknowledge_lock.acquire() acknowledge = self.acknowledge self.acknowledge_lock.release() return acknowledge # Function to get value of Acknowledge def set_acknowledge(self, value): self.acknowledge_lock.acquire() self.acknowledge = value self.acknowledge_lock.release() # Update the gui def update_gui(self): # Payload Image Message payload = self.payloadImage() self.payload["image"] = json.dumps(payload) # Payload Lap Message lapped = self.lap.check_threshold() self.payload["lap"] = "" if (lapped != None): self.payload["lap"] = str(lapped) # Payload Map Message pos_message = str(self.map.getFormulaCoordinates()) self.payload["map"] = pos_message # Payload V Message v_message = str(self.hal.motors.data.vx) self.payload["v"] = v_message # Payload W Message w_message = str(self.hal.motors.data.az) self.payload["w"] = w_message # Payload Console Messages message_buffer = self.console.get_text_to_be_displayed() self.payload["text_buffer"] = json.dumps(message_buffer) message = "#gui" + json.dumps(self.payload) self.server.send_message(self.client, message) # Function to read the message from websocket # Gets called when there is an incoming message from the client def get_message(self, client, server, message): # Acknowledge Message for GUI Thread if (message[:4] == "#ack"): self.set_acknowledge(True) # Message for Console elif (message[:4] == "#con"): self.console.prompt(message) # Activate the server def run_server(self): self.server = WebsocketServer(port=2303, host=self.host) self.server.set_fn_new_client(self.get_client) self.server.set_fn_message_received(self.get_message) self.server.run_forever() # Function to reset def reset_gui(self): self.lap.reset() self.map.reset()
def test_get_average_match_speed(self): lap1 = Lap("1", "1:02.852", "44,275", "23:49:08.277") lap2 = Lap("2", "1:02.851", "63,235", "23:49:08.277") self.__pilot.add_lap(lap2) self.__pilot.add_lap(lap1) self.assertEqual(53.755, self.__pilot.get_average_match_speed())
def test_add_lap(self): lap = Lap("1", "1:02.852", "44,275", "23:49:08.277") self.__pilot.add_lap(lap) self.assertEqual(lap, self.__pilot.get_last_lap())
class GUI: # Initialization function # The actual initialization def __init__(self, host, console): t = threading.Thread(target=self.run_server) self.payload = {'canvas': None, 'image': '', 'shape': []} self.server = None self.client = None self.host = host self.payload_lock = threading.Lock() # Take the console object to set the same websocket and client self.console = console t.start() # Create the lap object pose3d_object = ListenerPose3d("/F1ROS/odom") self.lap = Lap(pose3d_object) self.map = Map(pose3d_object) # Explicit initialization function # Class method, so user can call it without instantiation @classmethod def initGUI(cls, host, console): # self.payload = {'image': '', 'shape': []} new_instance = cls(host, console) return new_instance # Function for student to call # Encodes the image as a JSON string and sends through the WS def showImage(self, image): shape = image.shape frame = cv2.imencode('.JPEG', image)[1] encoded_image = base64.b64encode(frame) self.payload_lock.acquire() self.payload['image'] = encoded_image.decode('utf-8') self.payload['shape'] = shape self.payload_lock.release() # Function to get the client # Called when a new client is received def get_client(self, client, server): self.client = client self.console.set_websocket(self.server, self.client) # Update the gui def update_gui(self): self.payload_lock.acquire() message = "#img" + json.dumps(self.payload) self.payload_lock.release() lapped = self.lap.check_threshold() lap_message = "" if (lapped != None): lap_message = "#lap" + str(lapped) pos_message = str(self.map.getFormulaCoordinates()) pos_message = "#map" + pos_message try: self.server.send_message(self.client, message) self.server.send_message(self.client, pos_message) if (lap_message != ""): self.server.send_message(self.client, lap_message) except: pass # Activate the server def run_server(self): self.server = WebsocketServer(port=2303, host=self.host) self.server.set_fn_new_client(self.get_client) self.server.set_fn_message_received(self.console.prompt) self.server.run_forever() # Function to reset def reset_gui(self): self.lap.reset() self.map.reset()
def setUp(self): self.__lap = Lap("1", "1:02.852", "44,275", "23:49:08.277")
class GUI: # Initialization function # The actual initialization def __init__(self, host): rospy.init_node("GUI") self.payload = {'image': '','lap': '', 'map': '', 'v':'','w':''} self.server = None self.client = None self.host = host # Image variable self.shared_image = SharedImage("guiimage") # Get HAL variables self.shared_v = SharedValue("velocity") self.shared_w = SharedValue("angular") # Create the lap object pose3d_object = ListenerPose3d("/F1ROS/odom") self.lap = Lap(pose3d_object) self.map = Map(pose3d_object) # Event objects for multiprocessing self.ack_event = multiprocessing.Event() self.cli_event = multiprocessing.Event() # Start server thread t = threading.Thread(target=self.run_server) t.start() # Function to prepare image payload # Encodes the image as a JSON string and sends through the WS def payloadImage(self): image = self.shared_image.get() payload = {'image': '', 'shape': ''} shape = image.shape frame = cv2.imencode('.JPEG', image)[1] encoded_image = base64.b64encode(frame) payload['image'] = encoded_image.decode('utf-8') payload['shape'] = shape return payload # Function to get the client # Called when a new client is received def get_client(self, client, server): self.client = client self.cli_event.set() print(client, 'connected') # Update the gui def update_gui(self): # Payload Image Message payload = self.payloadImage() self.payload["image"] = json.dumps(payload) # Payload Lap Message lapped = self.lap.check_threshold() self.payload["lap"] = "" if(lapped != None): self.payload["lap"] = str(lapped) # Payload Map Message pos_message = str(self.map.getFormulaCoordinates()) self.payload["map"] = pos_message # Payload V Message v_message = str(self.shared_v.get()) self.payload["v"] = v_message # Payload W Message w_message = str(self.shared_w.get()) self.payload["w"] = w_message message = "#gui" + json.dumps(self.payload) self.server.send_message(self.client, message) # Function to read the message from websocket # Gets called when there is an incoming message from the client def get_message(self, client, server, message): # Acknowledge Message for GUI Thread if(message[:4] == "#ack"): # Set acknowledgement flag self.ack_event.set() # Pause message elif(message[:5] == "#paus"): self.lap.pause() # Unpause message elif(message[:5] == "#resu"): self.lap.unpause() # Reset message elif(message[:5] == "#rest"): self.reset_gui() # Function that gets called when the connected closes def handle_close(self, client, server): print(client, 'closed') # Activate the server def run_server(self): self.server = WebsocketServer(port=2303, host=self.host) self.server.set_fn_new_client(self.get_client) self.server.set_fn_message_received(self.get_message) self.server.set_fn_client_left(self.handle_close) self.server.run_forever() # Function to reset def reset_gui(self): self.lap.reset() self.map.reset()