def receive_response(self, fields):
        cmd = fields["cmd"]
        print("cmd respone:{}".format(cmd))

        if cmd == Commands.REGISTER_IMAGEVIEWER:
            #1. TODO handle it in new way (below)
            print("response:REGISTER_IMAGEVIEWER")
            # data = fields["data"] # save controllerID to use
            # # will send setSize inside
            # # self.controllerID = data
            # self.image_viewer.set_controllerID(data)
            # ImageController.parseReigsterViewResp(self.m_client, data)
            self.sync_connected_queue.put(connect_response)

        # elif cmd == command_REQUEST_FILE_LIST:
        #     print("response:REQUEST_FILE_LIST:")
        #     data = fields["data"]
        #     files = data["dir"]
        #     rootDir= data["name"]

        #     self.remote_current_folder = rootDir
        #     # print("files:{};dir:{}".format(files, rootDir))
        #     self.print_file_list(rootDir, files)
        #     dprint("response:REQUEST_FILE_LIST end")
        #     self.sync_connected_queue.put("get file list resp")
        # elif cmd == command_SELECT_FILE_TO_OPEN:
        #     print("response:SELECT_FILE_TO_OPEN")
        # else:
        ApiService.instance().consume_response(fields)
    def sendRegiserView(self):
        dprint("sendRegiserView")
        # cmd = '/CartaObjects/ViewManager:registerView'
        # const cmd = Commands.REGISTER_IMAGEVIEWER; // '/CartaObjects/ViewManager:registerView';
        params = 'pluginId:ImageViewer,index:0'
        # // this.BASE_PATH = this.SEP + this.CARTA + this.SEP;
        # // return `${this.BASE_PATH + this.VIEW_MANAGER + this.SEP_COMMAND}registerView`;

        ApiService.instance().send_command(Commands.REGISTER_IMAGEVIEWER,
                                           params, self.registerview_callback)
    def registerview_callback(self, result):
        # if error:
        #     dprint(error)
        #     return
        dprint("in registerview_callback")
        dprint(result)

        data = result["data"]  # save controllerID to use
        # will send setSize inside
        # self.controllerID = data
        self.controllerID = data

        view_name = data + "/view"
        width = 637  #// TODO same as the experimental setting in ImageViewer, change later
        height = 677

        # client.call(setSizeCmd, [viewName, width, height], self.setSizeCallback)
        ApiService.instance().setup_size(view_name, width, height)
    def __init__(self, user, password):
        self.url = 'ws://127.0.0.1:3000/websocket'
        self.m_client = None
        self.m_client = None
        self.use_other_session = False
        # SessionManager.instance() = SessionManager()
        self.user = user
        self.password = password
        # self.remote_current_folder = None
        # if session != None:
        #     SessionManager.instance().use_other_session(session)
        #     self.use_other_session = True

        # dprint("test:{}".format(testtest))
        # self.sefSessionID = None
        # self.controllerID = None
        # https://stackoverflow.com/questions/43471696/sending-data-to-a-thread-in-python
        self.sync_connected_queue = queue.Queue()

        # self.numberOfImages = 0
        self.debug_image_queue = None
        # self.testimage = 0

        # if isnotebook():
        #     dprint("is notebook")

        # import matplotlib
        # matplotlib.use('TkAgg')
        # sys.exit()

        self.m_client = MeteorClient(self.url)
        # self.controllerID = None
        self.file_manager = FileManager()
        self.image_viewer = ImageViewer()
        ApiService.instance().set_client(self.m_client)

        if run_from_interactive():
            dprint("is ipython, setup matplotlib")
            plt.ion()
            plt.figure()
            plt.show()
        else:
            dprint("not ipython")
    def selectFileToOpen(self, file, folder):
        # time.sleep(10) # 10 for testing sharing session between python and browser

        home = expanduser("~")
        # print(home)
        # path = home + "/CARTA/Images/" + file
        path = folder + "/" + file

        # controllerID = state.imageController.controllerID;
        parameter = "id:" + self.controllerID + ",data:" + path
        print("query file list parameter:", parameter)
        # console.log('inject file parameter, become:', parameter);
        #
        # Meteor.call('sendCommand', Commands.SELECT_FILE_TO_OPEN, parameter, SessionManager.get_suitable_session(), (error, result) => {
        #   console.log('get select file result:', result);
        # });

        # self.image_viewer.controllerID, file, self.files().remote_current_folder
        # client.call(sendCmd, [Commands.SELECT_FILE_TO_OPEN, parameter, session], selectFile_callback)

        ApiService.instance().send_command(Commands.SELECT_FILE_TO_OPEN,
                                           parameter, self.selectFile_callback)
Beispiel #6
0
    def request_file_list(self, user_callback=None):

        # TODO do not pass session or client directly to this class, later.
        # use the way newMeteorCARTA uses, apiService
        # self.queryServerFileList(self.session_manager.get(), self.client)
        dprint("queryServerFileList")
        params = 'path:'

        data = ApiService.instance().send_command(
            Commands.REQUEST_FILE_LIST, params, self.query_file_list_callback,
            user_callback)
        print('after send request file list, return data')
        return data
    def serviceLoop(self, settings, logger):
        """Monitor service managers.

		Starts up the managers and then actively monitor their status.

		Arguments:
		  settings (json) : global settings
		"""
        activeServices = []
        watcherWaitCycle = int(settings['statusReportingInterval'])
        serviceWaitCycle = int(
            settings['waitSecondsBeforeStartingNextService'])
        exitWaitCycle = int(settings['waitSecondsBeforeExiting'])
        shutdownEvent = multiprocessing.Event()

        ## Construct each Service
        transportService = TransportService(shutdownEvent, settings)
        apiService = ApiService(shutdownEvent, settings)
        contentGatheringService = ContentGatheringService(
            shutdownEvent, settings)
        resultProcessingService = ResultProcessingService(
            shutdownEvent, settings)
        queryService = QueryService(shutdownEvent, settings)
        universalJobService = UniversalJobService(shutdownEvent, settings)
        logCollectionService = LogCollectionService(shutdownEvent, settings)

        ## Add to the list of services
        activeServices.append(transportService)
        activeServices.append(apiService)
        activeServices.append(contentGatheringService)
        activeServices.append(resultProcessingService)
        activeServices.append(queryService)
        activeServices.append(universalJobService)
        activeServices.append(logCollectionService)

        ## Conditionally start/add the local service (ServerSideService)
        if settings['startServerSideService']:
            serverSideService = ServerSideService(shutdownEvent, settings)
            activeServices.append(serverSideService)

        ## Start the services as separate processes
        for thisService in activeServices:
            thisService.start()
            logger.info('Started {} with PID {}'.format(
                thisService.name, thisService.pid))
            ## Default 2 second sleep between service starts
            time.sleep(serviceWaitCycle)

        logger.info('Status of services:')
        for thisService in activeServices:
            if not thisService.is_alive():
                logger.error('   {}: stopped with exit code [{}]'.format(
                    thisService.name, thisService.exitcode))
            else:
                logger.info('   {}: running'.format(thisService.name))

        ## Wait loop
        logger.info('Starting main loop - {}'.format(time.strftime('%X %x')))
        while True:
            try:
                if self.stopFlag:
                    raise KeyboardInterrupt()
                ## Message on any failing services
                for thisService in activeServices:
                    if not thisService.is_alive():
                        logger.error(
                            '   {}: stopped with exit code [{}]'.format(
                                thisService.name, thisService.exitcode))

                ## Avoiding join() with the processes (from the multiprocessing
                ## internals), since we're not waiting for them to finish. They
                ## will always be running, so this loop is just for monitoring
                ## and messaging. Any interrupt signals will be sent to the sub-
                ## processes, and intentional shutdown requests are handled here.
                win32event.WaitForSingleObject(self.eventFlag, 10000)

            except (KeyboardInterrupt, SystemExit):
                print('Interrrupt received; notifying services to stop...')
                logger.debug(
                    'Interrrupt received; notifying services to stop...')
                shutdownEvent.set()
                ## Wait for threads to finish graceful shutdown
                time.sleep(exitWaitCycle)
                break
            except:
                stacktrace = traceback.format_exception(
                    sys.exc_info()[0],
                    sys.exc_info()[1],
                    sys.exc_info()[2])
                logger.debug(
                    'Exception in watcher loop: {}'.format(stacktrace))
                logger.debug('Notifying services to stop...')
                shutdownEvent.set()
                time.sleep(exitWaitCycle)
                break

        ## end serviceLoop
        return