예제 #1
0
 def __init__(self, params):
     '''
     Constructor
     '''
     super().__init__()
     self._params = params
     self._log = AT_Logging(self._params)
     return
 def __init__(self, params):
     '''
     Constructor
     '''
     super().__init__()
     self._params = params
     self._setup_directory_store()
     self._log = AT_Logging(self._params)
     self.daemon = True
     #         self._directory_initializer = dir_initializer
     return
예제 #3
0
 def __init__(self, params, log_file=''):
     super().__init__()
     self._params = params
     self._log = AT_Logging(params=self._params, log_file=log_file)
     self._lock = mp.RLock()
     self.daemon = True
     return
예제 #4
0
 def __init__(self, log_file='', default_debug_level=2):
     super().__init__()
     self._lock = threading.RLock()
     self._params = self.load_parameters()
     self._log = AT_Logging(self._params, log_file)
     self._default_debug_level = default_debug_level
     self.daemon = False
     return
예제 #5
0
 def __init__(self, params, rslt_queue, log_file):
     '''
     Constructor
     '''
     self._log_file = log_file
     self._params = params
     self._log = AT_Logging(params=self._params, log_file=log_file)
     self._rslt_queue = rslt_queue
     self._host_address = self._get_local_interface_address()
     self._set_dir_store(host_address=self._host_address,
                         port=self._params.port)
     self._open_listening_port(self._host_address)
     self._register_as_result_listener(host_address=self._host_address,
                                       port=self._client_data_port)
     self._rl_thread = AT_ResultListenerThread(
         rslt_lstner_socket_server=self._socket_srvr,
         params=self.params,
         log_file=log_file)
     return
예제 #6
0
 def __init__(self):
     '''
     Constructor
     '''
     self._params = AT_ActivityMonitorParams(self.GUI_CONF_FILE)
     self._log = AT_Logging(self._params)
     num_colors = 6
     #Setup color cycle for drawn objects
     self._colors = iter(pyplot.cm.rainbow(np.linspace(
         0, 1, num_colors)))  # @UndefinedVariable
     return
예제 #7
0
 def __init__(self, params):
     self._params = params
     self._log = AT_Logging(params=self._params, log_file=self.log_file)
     self.__rslt_data_queue = AT_ResultDataQueue(
         self._params, self.GUI_NAME, log_file=self.result_log_file)
     #Set even handlers
     self._log.log2(msg1='Registering event handlers',
                    msg2='',
                    caller=self,
                    msgty=AT_Logging.MSG_TYPE_DEBUG)
     self.__rslt_data_queue.on_data.register(self.on_data_handler)
     self.__rslt_data_queue.on_turn_apex.register(self.on_turn_apex_handler)
     self.__rslt_data_queue.on_cut.register(self.on_cut_handler)
     self.__rslt_data_queue.start()
     self._init_new_graph()
     #Save the background buffer
     self._background = self._graph_figure.canvas.copy_from_bbox(
         self._graph_axis.bbox)
     self._log.log2(msg1='Fully started',
                    msg2='',
                    caller=self,
                    msgty=AT_Logging.MSG_TYPE_DEBUG)
     return
예제 #8
0
    def __init__(self,
                 gui_name: str,
                 window_id: str,
                 glade_file: str,
                 min_window_height=600,
                 min_window_width=800):
        '''
        Constructor
        '''
        self._min_window_width = min_window_width
        self._min_window_height = min_window_height
        self._window_id = window_id
        self._glade_file = glade_file
        self._load_glade()

        self._params = AT_ResultListenerParams(self.get_conf_file())
        self._log = AT_Logging(params=self._params, log_file=self.log_file)
        self._rslt_data_queue = AT_ResultDataQueue(
            self._params, gui_name, log_file=self.result_log_file)
        #Set even handlers
        self._log.log2(msg1='Registering event handlers',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        self._rslt_data_queue.on_data.register(self.on_data_handler)
        self._rslt_data_queue.on_turn_apex.register(self.on_turn_apex_handler)
        self._rslt_data_queue.on_cut.register(self.on_cut_handler)
        self._rslt_data_queue.start()
        self._load_pole_to_cluster()
        #Save the background buffer
        #         self._background = self._graph_figure.canvas.copy_from_bbox(self._graph_axis.bbox)
        self._log.log2(msg1='Fully started',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        return
예제 #9
0
class AT_GraphingGUI(object):
    '''
    Graphs the flight path in real time.
    
    Note: Run from the command line: python3.5 -m aero_tracker.gui.at_graphing_gui
    '''

    CONF_DIR = 'conf'
    LOG_DIR = 'log'

    CONF_FILE_NAME = 'at_gui.conf'
    GUI_NAME = 'AeroTracker Flight Path'
    LOG_FILE_NAME = 'at_graph.log'
    RESULT_LOG_FILE_NAME = 'at_graph_results.log'

    _params = None
    _log = AT_Logging
    __rslt_data_queue = None
    _graph_figure = None
    _graph_axis = None
    _flight_path = None
    _annimation = None
    _colors = None
    _background = None
    _use_blit = False

    @property
    def log_file(self):
        rval = os.path.normpath(AT_GraphingGUI.get_base_dir() + os.sep +
                                self.LOG_DIR + os.sep + self.LOG_FILE_NAME)
        print('Using log file: ', rval)
        return rval

    @property
    def result_log_file(self):
        rval = os.path.normpath(AT_GraphingGUI.get_base_dir() + os.sep +
                                self.LOG_DIR + os.sep +
                                self.RESULT_LOG_FILE_NAME)
        print('Using log file: ', rval)
        return rval

    @property
    def conf_file(self):
        rval = os.path.normpath(AT_GraphingGUI.get_base_dir() + os.sep +
                                self.CONF_DIR + os.sep + self.CONF_FILE_NAME)
        return rval

    @staticmethod
    def get_conf_file():
        rval = os.path.normpath(AT_GraphingGUI.get_base_dir() + os.sep +
                                AT_GraphingGUI.CONF_DIR + os.sep +
                                AT_GraphingGUI.CONF_FILE_NAME)
        print('Using conf file: ', rval)
        return rval

    @staticmethod
    def get_base_dir():
        rval = os.getcwd()
        if (rval.endswith('gui')):
            rval = rval[:-17]
        elif (rval.endswith('aerotracker' + os.sep + 'aero_tracker')):
            rval = rval[:-13]
        return rval

    def on_data_handler(self, sender, **kwargs):
        '''
        target_id = kwargs['target_id']
        target_index = kwargs['target_index']
        '''
        #         target_id = kwargs['target_id']
        #         target_index = kwargs['target_index']
        #         self._log.log2(msg1='Data Arrived for target:', msg2=str(target_id), caller=self, msgty=AT_Logging.MSG_TYPE_DEBUG)
        return

    def on_cut_handler(self, sender, **kwargs):
        '''
        target_id
        target_index
        num_cuts
        '''
        print('Cut - Target: ' + kwargs['target_id'])
        return

    def on_turn_apex_handler(self, sender, **kwargs):
        '''
        target_id
        target_index
        lap_number
        turn_apex
        '''
        trn_apex = kwargs['turn_apex']

        #         print('Turn Apex = ' + "%.2f" % float(kwargs['turn_apex']) + \
        #             ' lap #: ' + kwargs['lap_number'] + \
        #             ' target: '+ kwargs['target_id'])
        print('Turn Apex = ' + "%.2f" % (trn_apex[2]) + \
            ' lap #: ' + str(kwargs['lap_number']) + \
            ' target: '+ kwargs['target_id'])
        return

    def init_flight_path(self):
        self._flight_path, = self._graph_axis.plot([0.0, 0.1], [0.0, 0.1],
                                                   [0.0, 0.1],
                                                   linewidth=2.0,
                                                   color='b')
        return self._flight_path,

    def update_flight_path(self, num):
        '''
        Updates the animated flight path curve.  This is called by the graph is real-time 
        to get a data point for a specific interval number.
        '''
        try:
            gx = self.__rslt_data_queue.graph_x(target_index=0)
            gy = self.__rslt_data_queue.graph_y(target_index=0)
            gz = self.__rslt_data_queue.graph_z(target_index=0)
        except Exception as ex:
            return self._flight_path

        self._flight_path.set_data(gx, gy)
        self._flight_path.set_3d_properties(gz)

        #         self._flight_path.set_data(self._lap_x, self._lap_y)
        #         self._flight_path.set_3d_properties(self._lap_z)
        #redraw
        try:
            if (self._use_blit):
                self._graph_figure.canvas.restore_region(self._background)
                self._graph_axis.draw_artist(self._flight_path)
                self._graph_figure.canvas.blit(self._graph_axis.bbox)
            else:
                plt.draw()
        except Exception as ex:
            print(ex)
            raise ex

        return self._flight_path,

    def _plot_pole(self):
        '''
        Plots the pole on the graph.
        '''
        x = np.linspace(0, 0, 2)
        y = np.linspace(0, 0, 2)
        z = np.linspace(0, 50, 2)
        self._graph_axis.plot(x, y, z, label='Pole', linewidth=3.0, color='r')
        return

    def cleanUp(self):
        if (self.__rslt_data_queue != None):
            self.__rslt_data_queue.stop()
        return

    def __init__(self, params):
        self._params = params
        self._log = AT_Logging(params=self._params, log_file=self.log_file)
        self.__rslt_data_queue = AT_ResultDataQueue(
            self._params, self.GUI_NAME, log_file=self.result_log_file)
        #Set even handlers
        self._log.log2(msg1='Registering event handlers',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        self.__rslt_data_queue.on_data.register(self.on_data_handler)
        self.__rslt_data_queue.on_turn_apex.register(self.on_turn_apex_handler)
        self.__rslt_data_queue.on_cut.register(self.on_cut_handler)
        self.__rslt_data_queue.start()
        self._init_new_graph()
        #Save the background buffer
        self._background = self._graph_figure.canvas.copy_from_bbox(
            self._graph_axis.bbox)
        self._log.log2(msg1='Fully started',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        return

    def __del__(self):
        self.cleanUp()
        return

    def _init_new_graph(self):
        '''
        Executes before the run cycle starts.
        '''
        self._log.log2(msg1='Creating new graph',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        self._graph_figure = plt.figure()
        #         self._graph_axis = self._graph_figure.add_subplot(1,1,1)
        #         self._graph_axis = p3.Axes3D(self._graph_figure)
        self._graph_axis = self._graph_figure.gca(projection='3d')

        # Setting the axes properties
        self._graph_axis.set_xlim3d([-100.0, 100.0])
        self._graph_axis.set_xlabel('X')

        self._graph_axis.set_ylim3d([-100.0, 100.0])
        self._graph_axis.set_ylabel('Y')

        self._graph_axis.set_zlim3d([0.0, 100.0])
        self._graph_axis.set_zlabel('Z')

        self._graph_axis.set_title('3D Flight Path')
        num_colors = 3
        self._colors = iter(plt.cm.rainbow(np.linspace(0, 1, num_colors)))
        #         self._colors = iter(matplotlib.cm.rainbow(np.linspace(0,1,num_colors)))

        #Draw the pole
        self._plot_pole()

        self._annimation = animation.FuncAnimation(
            self._graph_figure,
            self.update_flight_path,
            frames=200,
            init_func=self.init_flight_path,
            interval=20,
            blit=self._use_blit)

        #         plt.draw()
        plt.show(block=False)
        return
예제 #10
0
 def set_new_log(self, log_file):
     '''
     Sets a new log file.
     '''
     self._log = AT_Logging(params=self._params, log_file=log_file)
     return
class AT_DirectoryMPManagerServer(mp.Process):
    '''
    Multiprocessing Manager server Process.
    '''

    _params = None
    _directory_store = None  #single instance of data for the directory server
    _manager = None
    _manager_server = None
    _manager_port = 0
    _log = None
    #     _directory_initializer = None #process to set startup values in the directory store once started

    @property
    def manager_port(self):
        return self._manager_port

    def run(self):
        #         super().run()
        self._log.log(msg1='Manager process started',
                      caller=self,
                      msgty=AT_Logging.MSG_TYPE_INFO)
        self._serve_queue_manager(self._params.server_name, self._manager_port)
        self._log.log(msg1='Manager process exiting',
                      caller=self,
                      msgty=AT_Logging.MSG_TYPE_INFO)
        time.sleep(1)
        return

    def __init__(self, params):
        '''
        Constructor
        '''
        super().__init__()
        self._params = params
        self._setup_directory_store()
        self._log = AT_Logging(self._params)
        self.daemon = True
        #         self._directory_initializer = dir_initializer
        return

    def __del__(self):
        self.stop()

    def stop(self):
        if (self._manager_server != None):
            self._manager_server.stop()
        return

    def _setup_directory_store(self):
        self._directory_store = AT_DirectoryStore(self._log, self._params)
        AT_DirectoryMPManager.register(typeid='get_instance',
                                       callable=lambda: self._directory_store)
        self._manager_port = self._params.port
        return

    def _serve_queue_manager(self, client_address, port):
        tries = 0
        mgr_connected = False
        saddrstr = client_address + ':' + str(port)
        while ((not mgr_connected) and (tries < 10)):
            try:
                self._manager = AT_DirectoryMPManager(address=(client_address, port), \
                    authkey=bytearray(self._params.manager_auth_key,'ascii'))
                self._log.log(msg1='Getting manager server ready to start',
                              caller=self,
                              msgty=AT_Logging.MSG_TYPE_DEBUG)
                self._manager_server = self._manager.get_server()
                mgr_connected = True
            except Exception as ex:
                self._log.log2(msg1='Error opening manager port:',
                               msg2=str(ex),
                               caller=self,
                               msgty=AT_Logging.MSG_TYPE_DEBUG)
                tries += 1

        if (not mgr_connected):
            self._log.log1(
                msg1='Critical error opening manager port.  Quitting.',
                caller=self,
                msgty=AT_Logging.MSG_TYPE_ERROR)
            self.stop()
            raise AT_Exception(source=self,
                               method='_serve_queue_manager',
                               message='Critical error opening Manager port',
                               details=str(port))

        self._log.log3(msg1='Manger configured and about to start waiting for connections', \
            msg2='At:', msg3=saddrstr, caller=self, msgty=AT_Logging.MSG_TYPE_DEBUG)
        self._manager_server.serve_forever()
        return
예제 #12
0
class MonitorBase(threading.Thread):
    '''
    Base class for data and activity monitors.
    '''

    RECEIVE_SIZE = 200

    _run = False
    _data_socket = None
    _tcp_socket = None
    _params = None
    _client_data_port = 0
    _log = None
    _registered = False
    _connect_cnt = 0

    @staticmethod
    def data_recived(data, calling_process=""):
        #TODO: Finish
        return

    @staticmethod
    def connection_handle(connection, address, params):
        req_hndl = ActivityMonitorHandler(params)
        req_hndl.handle(connection, address)
        return

    def run(self):
        threading.Thread.run(self)
        tries = 0
        while ((self._run) and (tries < 100)):
            try:
                self.execute_direct()
                tries = 0
            except Exception as ex:
                self._log.log2(msg1='Failed to connect to Manager Server:',
                               msg2=str(ex),
                               caller=self,
                               msgty=AT_Logging.MSG_TYPE_ERROR)
                tries += 1
            time.sleep(.5)
        return

    def execute_direct(self):
        '''
        Directly execute inside the existing thread.  This method opens a listening port for a data publisher to connect.
        '''
        if (not self._registered):
            self._registered = self.connect_and_register()
        self._log.log2(msg1='About to wait for a connection. Cons so far:',
                       msg2=str(self._connect_cnt),
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        conn, address = self._data_socket.accept()
        thread = threading.Thread(target=MonitorBase.connection_handle,
                                  args=(conn, address, self._params))
        thread.daemon = True
        thread.start()
        self._connect_cnt += 1
        self._log.log2(msg1='Incoming connection. Cons so far:',
                       msg2=str(self._connect_cnt),
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        return

    def start(self):
        if (not self._run):
            threading.Thread.start(self)
            self._run = True
        return

    def stop(self):
        self.close_data_socket()
        self._run = False
        return

    def connect_and_register(self):
        '''
        Connect to the directory server and register as a data listener. The data listener has to open its
        own listening ports and act as a server since there can be many data processing servers parallel 
        processing the location data for various targets.
        '''
        try:
            self._openManagerSocket()
            client_ip = self._tcp_socket.getsockname(
            )[0]  #Gets the ip address of the client used to connect to the manager server
            client_port = self._open_listening_port(client_address=client_ip)

            self._tcp_socket.send(bytes(AT_Protocol.cmd_register_data_listener(client_display_name=self._params.client_display_name, \
                client_address=client_ip, client_port=client_port),'ascii'))
            resp = str(self._tcp_socket.recv(self.RECEIVE_SIZE), 'ascii')
            if ((resp != None) and (len(resp) > 0)):
                pkts = resp.split(sep=AT_Protocol.RESPONSE_TERMINATOR)
                if (len(pkts) >= 1):
                    resp = AT_Response.from_packet_bytes(pkts[0])
                    if (self._params.debug_level >= 1):
                        self._log.log4(msg1='Connection from Client:',
                                       msg2=str(client_ip),
                                       msg3='at Port:',
                                       msg4=str(client_port),
                                       caller=self,
                                       msgty=AT_Logging.MSG_TYPE_INFO)
                        self._log.log4(msg1='Status:', msg2=str(resp.data[0]), msg3='registered data servers:', \
                            msg4=str(resp.data[1]), caller=self, msgty=AT_Logging.MSG_TYPE_DEBUG)
                else:
                    #There was an error, so skip
                    ex = AT_Exception(source=self, method='connect_and_register', \
                        message='Invalid server response.', details='More than 1 response arrived to request.')
                    raise ex
                    return
        except Exception as ex:
            self._log.log(
                msg1='Failed to register with manager server as data listener.',
                caller=self,
                msgty=AT_Logging.MSG_TYPE_ERROR)
            raise ex
        finally:
            self._closeManagerSocket()
        return True

    def close_data_socket(self):
        try:
            self._data_socket.close()
        except:
            pass
        return

    def __init__(self, params):
        '''
        Constructor
        '''
        super().__init__()
        self._params = params
        self._log = AT_Logging(self._params)
        return

    def __del__(self):
        self.close_data_socket()
        return

    def _openManagerSocket(self):
        try:
            self._tcp_socket = socket.socket(socket.AF_INET,
                                             socket.SOCK_STREAM)
            #             self._tcp_socket.connect((self._manager_host_name, int(self._manager_port)))
            self._tcp_socket.connect(
                (self._params.server_name, int(self._params.port)))
        except Exception as ex:
            self._log.log4(msg1='Could not connect to manager server:', msg2=self._manager_host_name, \
                msg3='at port:', msg4=str(self._manager_port), caller=self, msgty=AT_Logging.MSG_TYPE_ERROR)
            raise ex
        return

    def _closeManagerSocket(self):
        if (self._tcp_socket != None):
            try:
                if (not self._tcp_socket._closed):
                    self._tcp_socket.close()
            except:
                pass
        self._tcp_socket = None
        return

    def _open_listening_port(self, client_address):
        connected = False
        tries = 0
        data_port = self._params.port + 1  #port to start trying at
        self._data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        while ((not connected) and (tries < 100)):
            try:
                self._data_socket.bind((client_address, data_port))
                self._data_socket.listen(1)
                connected = True
            except Exception as ex:
                tries += 1
                data_port += 1

        if (connected):
            self._client_data_port = data_port
        else:
            data_port = 0
        return data_port
예제 #13
0
class AT_GUI_Base(object):
    '''
    Standard base functionality for all AeroTracker front-end components.
    '''
    CONF_DIR = 'conf'
    LOG_DIR = 'log'
    CONF_FILE_NAME = 'at_gui.conf'
    LOG_FILE_NAME = 'at_graph.log'
    RESULT_LOG_FILE_NAME = 'at_graph_results.log'

    SOURCE_DIRECTORY = 'aero_tracker'
    GLADE_DIR = 'glade'

    _params = AT_ResultListenerParams
    _glade_bldr = Gtk.Builder()
    _window_id = 'window_id'
    _glade_file = 'glad.glade'
    _min_window_height = 600
    _min_window_width = 800
    _rslt_data_queue = AT_ResultDataQueue
    _pole_to_cluster = typing.List
    _cluster_to_pole = typing.Dict

    @property
    def glade_bldr(self):
        return self._glade_bldr

    @property
    def params(self):
        return self._params

    @property
    def log_file(self):
        rval = os.path.normpath(AT_GUI_Base.get_base_dir() + os.sep +
                                self.LOG_DIR + os.sep + self.LOG_FILE_NAME)
        print('Using log file: ', rval)
        return rval

    @property
    def result_log_file(self):
        rval = os.path.normpath(AT_GUI_Base.get_base_dir() + os.sep +
                                self.LOG_DIR + os.sep +
                                self.RESULT_LOG_FILE_NAME)
        print('Using log file: ', rval)
        return rval

    @property
    def conf_file(self):
        rval = os.path.normpath(AT_GUI_Base.get_base_dir() + os.sep +
                                self.CONF_DIR + os.sep + self.CONF_FILE_NAME)
        return rval

    @staticmethod
    def get_conf_file():
        rval = os.path.normpath(AT_GUI_Base.get_base_dir() + os.sep +
                                AT_GUI_Base.CONF_DIR + os.sep +
                                AT_GUI_Base.CONF_FILE_NAME)
        print('Using conf file: ', rval)
        return rval

    @staticmethod
    def get_base_dir():
        rval = os.getcwd()
        if (rval.endswith('gui')):
            rval = rval[:-17]
        elif (rval.endswith('aerotracker' + os.sep + 'aero_tracker')):
            rval = rval[:-13]
        return rval

    '''
    Events Section
    '''

    def on_window_delete(self, *args):
        '''
        Standard event handler for main window delete.
        '''
        self._rslt_data_queue.stop()
        Gtk.main_quit(*args)

    def on_window_show(self, *args):
        '''
        Standard event handler for main window delete.
        '''
        return

    def on_data_handler(self, sender, **kwargs):
        '''
        cluster_id = kwargs['cluster_id']
        target_id = kwargs['target_id']
        target_index = kwargs['target_index']
        '''
        #         target_id = kwargs['target_id']
        #         target_index = kwargs['target_index']
        #         self._log.log2(msg1='Data Arrived for target:', msg2=str(target_id), caller=self, msgty=AT_Logging.MSG_TYPE_DEBUG)
        return

    def on_cut_handler(self, sender, **kwargs):
        '''
        target_id
        target_index
        num_cuts
        '''
        print('Cut - Target: ' + kwargs['target_id'])
        return

    def on_turn_apex_handler(self, sender, **kwargs):
        '''
        target_id
        target_index
        lap_number
        turn_apex
        '''
        trn_apex = kwargs['turn_apex']

        #         print('Turn Apex = ' + "%.2f" % float(kwargs['turn_apex']) + \
        #             ' lap #: ' + kwargs['lap_number'] + \
        #             ' target: '+ kwargs['target_id'])
        print('Turn Apex = ' + "%.2f" % (trn_apex[2]) + \
            ' lap #: ' + str(kwargs['lap_number']) + \
            ' cluster: ' + kwargs['cluster_id'] + \
            ' target: '+ kwargs['target_id'])
        return

    def get_gui_object(self, object_id: str):
        return self.glade_bldr.get_object(object_id)

    def get_pole_from_cluster(self, cluster_id):
        return self._cluster_to_pole[cluster_id]

    def get_cluster_for_pole(self, pole_num):
        indx = pole_num - 1
        return self._pole_to_cluster[indx]

    def _load_glade(self):
        self.glade_bldr.add_from_file(self._glade_file_path())
        self.glade_bldr.connect_signals(self)
        #         window.set_size_request(self._min_window_width,self._min_window_height)
        return

    def _glade_file_path(self) -> str:
        rval = os.path.normpath(AT_GUI_Base.get_base_dir() + os.sep +
                                self.SOURCE_DIRECTORY + os.sep +
                                self.GLADE_DIR + os.sep + self._glade_file)
        return rval

    def __init__(self,
                 gui_name: str,
                 window_id: str,
                 glade_file: str,
                 min_window_height=600,
                 min_window_width=800):
        '''
        Constructor
        '''
        self._min_window_width = min_window_width
        self._min_window_height = min_window_height
        self._window_id = window_id
        self._glade_file = glade_file
        self._load_glade()

        self._params = AT_ResultListenerParams(self.get_conf_file())
        self._log = AT_Logging(params=self._params, log_file=self.log_file)
        self._rslt_data_queue = AT_ResultDataQueue(
            self._params, gui_name, log_file=self.result_log_file)
        #Set even handlers
        self._log.log2(msg1='Registering event handlers',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        self._rslt_data_queue.on_data.register(self.on_data_handler)
        self._rslt_data_queue.on_turn_apex.register(self.on_turn_apex_handler)
        self._rslt_data_queue.on_cut.register(self.on_cut_handler)
        self._rslt_data_queue.start()
        self._load_pole_to_cluster()
        #Save the background buffer
        #         self._background = self._graph_figure.canvas.copy_from_bbox(self._graph_axis.bbox)
        self._log.log2(msg1='Fully started',
                       msg2='',
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_DEBUG)
        return

    def _load_pole_to_cluster(self):
        self._cluster_to_pole = {'SP': 1, 'NP': 2}
        self._pole_to_cluster = ['SP', 'NP']
        return
예제 #14
0
class ResultListenerBase(object):
    '''
    Result Listener Base class.
    '''
    @property
    def listener_name(self) -> str:
        raise Exception("Must redefine in inheriting class")
        return

    @property
    def params(self):
        return self._params

    @property
    def handler_class(self):
        raise Exception("Must redefine in inheriting class")
        return

    _params = None
    _log = None
    _client_data_port = 0
    _host_address = ""
    _socket_srvr = None
    _rslt_queue = None
    _rl_thread = None
    _log_file = '/var/log/aerotracker/at_results.log'

    def start(self):
        #Serve and listen for incoming connections
        self._rl_thread.start()
        #         self._socket_srvr.serve_forever()
        return

    def close(self):
        if (self._rl_thread != None):
            self._rl_thread.stop()
        return

    def __init__(self, params, rslt_queue, log_file):
        '''
        Constructor
        '''
        self._log_file = log_file
        self._params = params
        self._log = AT_Logging(params=self._params, log_file=log_file)
        self._rslt_queue = rslt_queue
        self._host_address = self._get_local_interface_address()
        self._set_dir_store(host_address=self._host_address,
                            port=self._params.port)
        self._open_listening_port(self._host_address)
        self._register_as_result_listener(host_address=self._host_address,
                                          port=self._client_data_port)
        self._rl_thread = AT_ResultListenerThread(
            rslt_lstner_socket_server=self._socket_srvr,
            params=self.params,
            log_file=log_file)
        return

    def __del__(self):
        self.close()
        return

    def _set_dir_store(self, host_address, port):
        self._log.log2(msg1='Connecting to Directory Server:',
                       msg2=host_address + ':' + str(port),
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_INFO)
        dirsvr_client = AT_DirectoryServerClient(
            server_name=self._params.server_name,
            port=self._params.port,
            auth_key=self._params.manager_auth_key,
            log=self._log)
        self._dir_store = dirsvr_client.get_dirctory_store()
        return

    def _register_as_result_listener(self, host_address, port):
        self._log.log2(msg1='Registering as result listener:',
                       msg2=host_address + ':' + str(port),
                       caller=self,
                       msgty=AT_Logging.MSG_TYPE_INFO)
        self._dir_store.add_result_data_listener(
            listener_name=self.listener_name, address=host_address, port=port)
        return

    def _open_listening_port(self, server_address):
        #Start up a local multiprocessing manager server for use by the incoming sockets
        #to this data processing worker.  This has to be started before the socket listeners
        #in oder to get thh generated address and port
        self._log.log(msg1='Starting to open a listening port:',
                      caller=self,
                      msgty=AT_Logging.MSG_TYPE_INFO)
        connected = False
        tries = 0
        data_port = self._params.port + 1  #port to start trying at
        while ((not connected) and (tries < 10)):
            try:
                self._socket_srvr = AT_ResultListenerSocketServer((self._dir_store), server_address=(server_address, data_port), \
                        RequestHandlerClass=self.handler_class,
                        params=self._params,
                        terminator=AT_Protocol.DATA_TERMINATOR)
                self._socket_srvr.set_listener_address(server_address)
                self._socket_srvr.set_listener_port(data_port)
                self._socket_srvr.set_result_queue(self._rslt_queue)
                self._socket_srvr.log_file = self._log_file
                connected = True
            except Exception as ex:
                tries += 1
                data_port += 1

        if (connected):
            self._client_data_port = data_port
            self._log.log2(msg1='Successfully opened listening port on:',
                           msg2=server_address + ':' + str(data_port),
                           caller=self,
                           msgty=AT_Logging.MSG_TYPE_INFO)
        else:
            data_port = 0
            raise Exception("Could not open listening port for client.")
        return data_port

    def _get_local_interface_address(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect((self._params.server_name, self._params.port))
            addr = s.getsockname()[0]
            s.close()
        except Exception as ex:
            self.log.log2(msg1='Could not connect to directory server:',
                          msg2=str(ex),
                          caller=self,
                          msgty=AT_Logging.MSG_TYPE_ERROR)
            raise ex
        return addr
예제 #15
0
 def __init__(self, params, log_file):
     super().__init__()
     self._params = params
     self._log = AT_Logging(params=self._params,log_file=log_file)
     self._lock = threading.RLock()
     return
예제 #16
0
 def load_parameters(self):
     return AT_Logging(self._params)