Exemple #1
0
    def set_run(self, run):
        '''
        Sets the run variable directly.
        Usually called at start up, when reading
        the run value from the ESP.

        arguments:
        - run: the run value (0 or 1) to set
        '''
        if self._run == run:
            return

        self._run = run

        if run == self.DONOT_RUN:
            # TODO: this should be an alarm
            msg = MessageBox()
            msg.critical(
                'STOPPING VENTILATION',
                'The hardware has stopped the ventilation.',
                'The microcontroller has stopped the ventilation by sending run = '
                + str(run),
                'The microcontroller has stopped the ventilation by sending run = '
                + str(run), {msg.Ok: self.show_start_button})()

        else:
            self.show_stop_button()
Exemple #2
0
    def thread_complete(self):
        '''
        Called when a thread ends.
        '''

        if self._running:
            print(
                "\033[91mERROR: The I/O thread finished! Going to start a new one...\033[0m"
            )
            self._n_attempts += 1
            self._running = False

            if self._n_attempts > 10:
                self._n_attempts = 0
                msg = MessageBox()

                # TODO: find a good exit point
                callbacks = {
                    msg.Retry: self.start_io_thread,
                    msg.Abort: lambda: sys.exit(-1)
                }

                fn = msg.critical("COMMUNICATION ERROR",
                                  "CANNOT COMMUNICATE WITH THE HARDWARE",
                                  "Check cable connections then click retry.",
                                  "COMMUNICATION ERROR", callbacks)
                fn()

            time.sleep(0.05)
            self.start_io_thread()
Exemple #3
0
    def ok_worker(self, mode):
        '''
        The callback function called when the alarm 
        or warning pop up window is closed by clicking
        on the Ok button.

        arguments:
        - mode: what this is closing, an 'alarm' or a 'warning'
        '''

        if mode not in ['alarm', 'warning']:
            raise Exception('mode must be alarm or warning.')

        if mode == 'alarm':
            self._alarm_raised = False
        else:
            self._warning_raised = False

        # Reset the alarms/warnings in the ESP
        # If the ESP connection fails at this
        # time, raise an error box
        try:
            if mode == 'alarm':
                self._esp32.reset_alarms()
            else:
                self._esp32.reset_warnings()
        except Exception as error:
            msg = MessageBox()
            fn = msg.critical("Critical",
                              "Severe hardware communication error",
                              str(error), "Communication error", {
                                  msg.Retry: lambda: self.ok_worker(mode),
                                  msg.Abort: lambda: None
                              })
            fn()
Exemple #4
0
    def toggle_lung_recruit(self):
        if self._lung_recruit:
            self._lung_recruit = False
            self._esp32.set("pause_lg", 0)
            self._lung_recruit_timer.stop()
            self.button_lung_recruit.setText("Lung\nRecruitment")
        else:
            msg = MessageBox()
            fn = msg.question(
                "Please confirm",
                "Do you want to start the Lung Recruitment procedure?", None,
                "Confirmation required", {
                    msg.Yes: lambda: True,
                    msg.No: lambda: False
                })
            answer = fn()
            if not answer:
                return

            self._lung_recruit = True
            lr_time = self._config["lung_recruit_time"]["current"]
            lr_pres = self._config["lung_recruit_pres"]["current"]
            self.button_lung_recruit.setText("Stop\nLung Recruitment\n %d" %
                                             lr_time)

            self._esp32.set("pause_lg_p", lr_pres)
            self._esp32.set("pause_lg_time", lr_time)
            self._esp32.set("pause_lg", 1)

            self._lung_recruit_timer = QtCore.QTimer()
            self._lung_recruit_timer.timeout.connect(
                self._get_lung_recruit_eta)
            self._lung_recruit_timer.start(500)
Exemple #5
0
    def _on_click_snooze(self):
        '''
        The callback function called when the alarm
        snooze button is clicked.
        '''

        if self._mode not in [WARNING, ERROR]:
            raise Exception('mode must be alarm or warning.')

        # Reset the alarms/warnings in the ESP
        # If the ESP connection fails at this
        # time, raise an error box
        try:
            if self._mode == ERROR:
                self._esp32.snooze_hw_alarm(self._code)
                self._alarm_h.snooze_alarm(self._code)
            else:
                self._esp32.reset_warnings()
                self._alarm_h.snooze_warning(self._code)
        except Exception as error:
            msg = MessageBox()
            fn = msg.critical("Critical",
                              "Severe hardware communication error",
                              str(error), "Communication error", {
                                  msg.Retry: lambda: self.ok_worker(mode),
                                  msg.Abort: lambda: None
                              })
            fn()
Exemple #6
0
    def handle_alarms(self):
        '''
        The callback method which is called periodically
        to check if the ESP raised any alarm or warning.
        If an alarm or warning is raised, a pop up
        window appears, showing the list of alarms and
        warnings. If more alarms or warnings add up, the
        window is updated automatically showing the latest
        errors.
        '''

        # Retrieve alarms and warnings from the ESP
        try:
            esp32alarm = self._esp32.get_alarms()
            esp32warning = self._esp32.get_warnings()
        except Exception as error:
            esp32alarm = None
            esp32warning = None
            err_msg = "Severe hardware communication error. "
            err_msg += "Cannot retrieve alarm and warning statuses from hardware."
            msg = MessageBox()
            fn = msg.critical("Critical", err_msg, str(error),
                              "Communication error", {
                                  msg.Retry: lambda: None,
                                  msg.Abort: lambda: None
                              })
            fn()

        #
        # ALARMS
        #
        if esp32alarm:
            errors = esp32alarm.strerror_all()
            errors_full = esp32alarm.strerror_all(append_err_no=True)

            alarm_codes = esp32alarm.get_alarm_codes()

            for alarm_code, err_str in zip(alarm_codes, errors):
                if alarm_code not in self._err_buttons:
                    btn = AlarmButton(ERROR, alarm_code, err_str,
                                      self._alarmlabel, self._snooze_btn)
                    self._alarmstack.addWidget(btn)
                    self._err_buttons[alarm_code] = btn

        #
        # WARNINGS
        #
        if esp32warning:
            errors = esp32warning.strerror_all()
            errors_full = esp32warning.strerror_all(append_err_no=True)

            warning_codes = esp32warning.get_alarm_codes()

            for warning_code, err_str in zip(warning_codes, errors):
                if warning_code not in self._war_buttons:
                    btn = AlarmButton(WARNING, warning_code, err_str,
                                      self._alarmlabel, self._snooze_btn)
                    self._alarmstack.addWidget(btn)
                    self._war_buttons[warning_code] = btn
Exemple #7
0
    def deletesetting(self):
        section_name = self.leServer.currentText()

        self.parser.remove_section(section_name)
        with open(self.inifile, 'w') as configfile:
            self.parser.write(configfile)

        self.refresh()

        MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry removed!", \
                                   "Server: {section} removed from File: {file} sucessfully.".format(section=section_name, file=self.inifile))
    def _raise_comm_error(self, message):
        """
        Opens an error window with 'message'.
        """

        # TODO: find a good exit point
        msg = MessageBox()
        msg.critical('COMMUNICATION ERROR',
                     'Error communicating with the hardware', message,
                     '** COMMUNICATION ERROR **',
                     {msg.Ok: lambda: sys.exit(-1)})()
Exemple #9
0
    def _open_backup_warning(self):
        '''
        Opens a warning message if the ventilator
        changed from PSV to PCV ventilation.
        '''
        msg = MessageBox()

        callbacks = {msg.Ok: self._acknowlege_backup}

        msg.warning("CHANGE OF MODE",
                    "The ventilator changed from PSV to PCV mode.",
                    "The microcontroller raised the backup flag.", "",
                    callbacks)()
Exemple #10
0
    def get_data(session, url, user, userPass, certificateName):
        print("{nl}URL: {url}{nl1}".format(nl=os.linesep,
                                           url=url,
                                           nl1=os.linesep))

        isSecureURL = True

        #print(url, user, userPass, certificateName)
        try:
            if len(certificateName.strip()) == 0:
                isSecureURL = False
                retry = Retry(connect=3, backoff_factor=0.5)
                adapter = HTTPAdapter(max_retries=retry)
                session.mount('http://', adapter)
            else:
                session.mount('https://', ForcedIPHTTPSAdapter())

            headers = {
                'content-type':
                'application/x-www-form-urlencoded,application/json,text/html',
                'User-Agent':
                'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
                'Accept':
                'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Cache-Control': 'max-age=0',
                'Connection': 'keep-alive'
            }

            if isSecureURL:
                response = session.get(url,
                                       auth=(user, userPass),
                                       headers=headers,
                                       timeout=5,
                                       verify=certificateName)
            else:
                response = session.get(url,
                                       auth=(user, userPass),
                                       headers=headers,
                                       timeout=5,
                                       verify=False)

            response.raise_for_status()
            items = response.json()
            response = {}
            return items
        except Exception as e:
            MessageBox.message(QMessageBox.Critical,
                               "RabbitMQ REST Connection - Error",
                               "REST API Error",
                               "Unable to retreive data: {}".format(str(e)))
            return {}
Exemple #11
0
def test_MessageBox_Question(qtbot):
    msg = MessageBox()

    def foo():
        pass

    callbacks = {msg.Ok: foo}

    msg.question("CHANGE OF MODE",
                 "The ventilator changed from PSV to PCV mode.",
                 "The microcontroller raised the backup flag.", "", callbacks,
                 True)

    assert msg is not None
    def accept(self):
        fileName = self.leFileName.text()
        if len(fileName) > 0:
            with open(fileName, 'w') as json_file:
                #json_file.write(self.messages)
                json_file.write(self.leexportedMessages.toPlainText())

                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Export Message(s)",
                    "Message(s) Exported!",
                    "Message(s) exported to {file} sucessfully.".format(
                        file=fileName))

        self.closewin()
 def confirm_stop_pressed(self):
     '''
     Opens a window which asks for confirmation
     when the Stop button is pressed.
     '''
     self.button_autoassist.setDown(False)
     currentMode = self.mode_text.upper()
     msg = MessageBox()
     ok = msg.question("**STOPPING %s MODE**" % currentMode,
                       "Are you sure you want to STOP %s MODE?" %
                        currentMode,
                        None, "IMPORTANT", { msg.Yes: lambda: True,
                        msg.No: lambda: False })()
     return ok
Exemple #14
0
 def send_signal(self, mode, pause):
     '''
     Sends signal the appropriate signal the ESP
     to pause inpiration or expiration.
     '''
     try:
         if not self._data_h.set_data(mode, int(pause)):
             raise Exception('Call to set_data failed.')
     except Exception as error:
         msg = MessageBox()
         fn = msg.critical("Critical",
                           "Severe hardware communication error",
                           str(error), "Communication error",
                           {msg.Ok: lambda: self.stop_timer()})
         fn()
Exemple #15
0
def contact_quitrule():
  """ Triggers what happens when contacts is `closed`. If the user has selected
  contacts the message box is opened with a new chat session with all the
  selected contacts. """
  selected = []
  for state, item in contactmenu.items.iteritems():
    if '[x]' in item:
      selected.append(state)
  if len(selected) > 0:
    eZMenu.menu_move_up(ignore_quitrule=True)
    # session = tuples of fingerprints
    session = tuple(contactmenu.storage[u] for u in selected)
    MessageBox.open_message_box()
    MessageBox.switch_session(session)
  else:
    eZMenu.menu_move_up(ignore_quitrule=True)
Exemple #16
0
    def build_GUI(self):
        books = ('Project', 'R2map', 'Calibration')
        self.left_frame = tk.Frame(self.root)
        self.left_frame.pack(side=tk.LEFT, fill=tk.Y, expand=0)

        self.right_frame = tk.Frame(self.root)
        self.right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.notebook = ttk.Notebook(self.left_frame)
        self.notebook.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.book1 = tk.Frame(self.notebook)
        self.notebook.add(self.book1, text='Project')
        self.book2 = tk.Frame(self.notebook)
        self.notebook.add(self.book2, text='R2map')
        self.book3 = tk.Frame(self.notebook)
        self.notebook.add(self.book3, text='Calibration')
        self.notebook.bind('<<NotebookTabChanged>>', self.notebook_changed)

        self.main_frame = tk.Frame(self.right_frame)
        self.main_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.make_project_book(self.book1)
        self.make_r2map_book(self.book2)
        self.make_calibration_book(self.book3)

        self.message_box_frame = tk.LabelFrame(self.right_frame, text='Messages')
        self.message_box_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1)
        self.messagebox = MessageBox(self.message_box_frame)
        self.messagebox.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.r2value = []
        self.dose = []
Exemple #17
0
def gen_contactsmenu(contactmenu):
  """ Generates the contacts menu. """

  contactmenu.clear_items()
  contacts = MessageBox.contact_list()
  for contact in contacts:
    status = contact['status']
    user_id = contact['user_id']
    fingerprint = contact['fingerprint']
    not_marked = '[ ]'
    button_label = user_id + ' ' + status + ' ' + not_marked

    # pressing <CR> toggles if the contact is selected ([x]) or not ([ ])
    def contact_callback(user_id, status, fingerprint):
      def mark_contact():
        state, line = eZMenu.get_item()

        if '[x]' in line:
          new_button_label = user_id + ' ' + status + ' [ ]'
        else:
          new_button_label = user_id + ' ' + status + ' [x]'
          vim.command('echo "selected fp: %s"' % fingerprint)
        contactmenu.update_item(state, new_button_label)
      return mark_contact

    contactmenu.add_item(button_label,
                         callback=contact_callback(user_id, status,
                                                   fingerprint),
                         storage=fingerprint)
    def open_comm_error(self, error):
        '''
        Opens a message window if there is a communication error.
        '''
        msg = MessageBox()

        # TODO: find a good exit point
        callbacks = {
            msg.Retry: self._restart_timer,
            msg.Abort: lambda: sys.exit(-1)
        }

        fn = msg.critical(
            "COMMUNICATION ERROR", "CANNOT COMMUNICATE WITH THE HARDWARE",
            "Check cable connections then click retry.\n" + error,
            "COMMUNICATION ERROR", callbacks)
        fn()
Exemple #19
0
def start_gui():
    """
    Launch the MVM GUI
    """
    base_dir = os.path.dirname(__file__)
    settings_file = os.path.join(base_dir, 'default_settings.yaml')

    with open(settings_file) as mvm_settings:
        config = yaml.load(mvm_settings, Loader=yaml.FullLoader)
    print('Config:', yaml.dump(config), sep='\n')

    app = QtWidgets.QApplication(sys.argv)

    esp32 = None
    if 'fakeESP32' in sys.argv:
        print('******* Simulating communication with ESP32')
        esp32 = FakeESP32Serial(config)
    else:
        while True:
            try:
                err_msg = "Cannot communicate with port %s" % config['port']
                esp32 = ESP32Serial(config)
                break
            except SerialException as error:
                msg = MessageBox()
                retry = msg.critical("Do you want to retry?",
                                     "Severe hardware communication error",
                                     str(error) + err_msg, "Communication error",
                                     {msg.Retry: lambda: True,
                                      msg.Abort: lambda: sys.exit(-1)})
                if not retry():
                    break

    if esp32 is None:
        exit(-1)

    esp32.set("wdenable", 1)

    watchdog = QtCore.QTimer()
    watchdog.timeout.connect(esp32.set_watchdog)
    watchdog.start(config["wdinterval"] * 1000)

    window = MainWindow(config, esp32)
    window.show()
    app.exec_()
    esp32.set("wdenable", 0)
Exemple #20
0
    def connect(self,
                parent,
                commandUrl,
                userName,
                userPass,
                certName,
                vhost,
                connectionName=''):
        credentials = pika.PlainCredentials(username=userName,
                                            password=userPass)

        _commandUrl = commandUrl.split(":")

        #print(commandUrl)
        serverCN = _commandUrl[1].replace("//", "")
        commandPort = _commandUrl[2]

        ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        #ssl_context.verify_mode = ssl.CERT_REQUIRED
        ssl_context.load_verify_locations(certName)

        ssl_options = pika.SSLOptions(context=ssl_context,
                                      server_hostname=serverCN)

        parameters = pika.ConnectionParameters(host=serverCN,
                                               port=commandPort,
                                               virtual_host=vhost,
                                               connection_attempts=5,
                                               retry_delay=5,
                                               credentials=credentials,
                                               heartbeat=580,
                                               blocked_connection_timeout=600,
                                               ssl_options=ssl_options,
                                               client_properties={
                                                   'connection_name':
                                                   connectionName,
                                               })
        try:
            return pika.BlockingConnection(parameters)
        except Exception as e:
            print(str(e))
            MessageBox.message(
                QMessageBox.Critical, "RabbitMQ AMQP Connection - Error",
                "AMQP Error",
                "Unable to connect to RabbitMQ: {}".format(str(e)))
            return None
    def send_signal(self, mode, pause):
        """
        Sends signal the appropriate signal the ESP
        to pause inpiration or expiration.

        arguments:
        - mode: The pause mode (either 'pause_exhale' or 'pause_inhale')
        - pause: Boolean for paused or not paused
        """
        try:
            if not self._data_h.set_data(mode, int(pause)):
                raise Exception('Call to set_data failed.')
        except Exception as error:
            msg = MessageBox()
            confirm_func = msg.critical(
                "Critical", "Severe hardware communication error", str(error),
                "Communication error", {msg.Ok: lambda: self.stop_timer(mode)})
            confirm_func()
    def set_run(self, run):
        '''
        Sets the run variable directly.
        Usually called at start up, when reading
        the run value from the ESP.
        '''
        if self.run == run:
            return

        if self.run == self.DO_RUN:
            msg = MessageBox()
            msg.critical('STOPPING VENTILATION',
                         'The hardware has stopped the ventilation.',
                         'The microcontroller has stopped the ventilation by sending run = '+str(run),
                         'The microcontroller has stopped the ventilation by sending run = '+str(run),
                         {msg.Ok: self._stop_abruptly})()

        else:
            self.toggle_start_stop()
Exemple #23
0
    def __init__(self, screen, data):
        self.screen = screen
        self.data = data

        self.stage_num = 1
        self.select_num = 0
        self.option_num = 0
        self.path = glob('stage/*/')
        self.new_path = []

        for i in range(len(self.path)):
            self.new_path.append(self.path[i].strip('stage\/'))

        StageSelect_font = pygame.font.Font("font/freesansbold.ttf", 55)
        Arrow_font = pygame.font.Font("font/freesansbold.ttf", 100)
        self.Stage_font = pygame.font.Font("font/freesansbold.ttf", 45)

        self.StageSelect_text = StageSelect_font.render("Stage Select", True, (255,255,255)) 
        self.RightArrow_text = Arrow_font.render(">", True, (255,255,255))
        self.LeftArrow_text = Arrow_font.render("<", True, (255,255,255))
        self.RightArrow_text = pygame.transform.rotate(self.RightArrow_text, 90)
        self.LeftArrow_text = pygame.transform.rotate(self.LeftArrow_text, 90)
        # ステージのテキスト情報をリストにする
        self.stage_text = [None]
        '''for i in range(3):
            text = "Stage" + str(i+1)
            self.stage_text.append(Stage_font.render(text, True, (255,255,255)))
'''
        # リストボックスの設定
        self.option_listbox = ListBox(self.screen, 50, 80, 250, 200, ['Back', 'Shop', 'Equip'], font_size=55, title="Menu")
        self.option_listbox.set_selectable([True, True, True])
        self.file_listbox = ListBox(self.screen, 940, 80, 120, 400, self.new_path, title="File")
    
        self.file_listbox.set_selectable([True, True])
        self.file_listbox()
        self.file_id = None

        # メッセージボックスの設定
        self.messagebox = MessageBox(self.screen, 130, 540, 900,  outline_color=(180,180,180), select='random')
        with open('data/message.txt', 'r', encoding='utf-8') as fp:
            self.messagebox += fp.readlines()

        self.clock = pygame.time.Clock()
def connect_esp32(config):
    try:
        if 'fakeESP32' in sys.argv:
            print('******* Simulating communication with ESP32')
            err_msg = "Cannot setup FakeESP32Serial"
            esp32 = FakeESP32Serial(config)
            esp32.set("wdenable", 1)
        else:
            err_msg = "Cannot communicate with port %s" % config['port']
            esp32 = ESP32Serial(config)
            esp32.set("wdenable", 1)
    except Exception as error:
        msg = MessageBox()
        fn = msg.critical("Do you want to retry?",
                          "Severe hardware communication error",
                          str(error) + err_msg, "Communication error",
                          { msg.Retry: lambda: connect_esp32(config),
                            msg.Abort: lambda: None})
        return fn()

    return esp32
    def __init__(self, config, esp32):
        '''
        Constructor

        arguments:
        - config: the dictionary storing the configuration
        - esp32: the esp32serial object
        '''

        self._config = config
        self._esp32 = esp32

        self._alarm_raised = False
        self._warning_raised = False

        self._msg_err = MessageBox()
        self._msg_war = MessageBox()

        self._alarm_timer = QtCore.QTimer()
        self._alarm_timer.timeout.connect(self.handle_alarms)
        self._alarm_timer.start(config["alarminterval"] * 1000)
Exemple #26
0
    def accept(self):
        webUrl = self.leUrl.text().strip()
        commandUrl = self.le1Url.text().strip()
        user = self.leUserId.text().strip()
        userPass = self.lePassword.text().strip()
        vHost = self.leVhost.text().strip()
        certName = self.leCertificateName.text().strip()
        certPass = self.leCertificatePassword.text().strip()

        protocol = True if "https" in webUrl else False

        msg =  "Please enter:{nl}Web Url{nl}Amqp Url{nl}User Id{nl}Password{nl}Passkey File and {nl}VHost.{nl}{nl}In case of https, please provide Certificate details.{nl}{nl}" \
               "Please click update setting, before clicking Ok button.".format(nl=os.linesep)

        if webUrl and commandUrl and user and userPass and vHost:
            print(protocol, certName)
            if protocol and len(certName) != 0:
                self._webUrl.emit(webUrl)
                self._commandUrl.emit(commandUrl)
                self._userId.emit(user)

                self._password.emit(self.passKeyFile, userPass)

                self._vhost.emit(vHost)
                self._certName.emit(certName)
                self._certPass.emit(certPass)

                self._cancelled.emit(False)

                self.closewin()
            else:
                MessageBox.message(QMessageBox.Information, "RabbitMQ Queue",
                                   "Configuration entry issue!", msg)
                self._cancelled.emit(True)
        else:
            MessageBox.message(QMessageBox.Information, "RabbitMQ Queue",
                               "Configuration entry issue!", msg)
            self._cancelled.emit(True)
Exemple #27
0
    def post_data(session, url, user, userPass, certificateName, body):
        print("{nl}URL: {url}{nl1}".format(nl=os.linesep,
                                           url=url,
                                           nl1=os.linesep))

        isSecureURL = True

        try:
            if len(certificateName.strip()) == 0:
                isSecureURL = False
                retry = Retry(connect=3, backoff_factor=0.5)
                adapter = HTTPAdapter(max_retries=retry)
                session.mount('http://', adapter)
            else:
                session.mount('https://', ForcedIPHTTPSAdapter())

            if isSecureURL:
                response = session.post(url,
                                        auth=(user, userPass),
                                        verify=certificateName,
                                        json=body)
            else:
                response = session.post(url,
                                        auth=(user, userPass),
                                        verify=False,
                                        json=body)

            response.raise_for_status()
            items = response.json()
            response = {}
            return items
        except Exception as e:
            MessageBox.message(QMessageBox.Critical,
                               "RabbitMQ REST Connection - Error",
                               "REST API Error",
                               "Unable to retreive data: {}".format(str(e)))
            return {}
Exemple #28
0
    def editsetting(self):

        section_name = self.leServer.currentText()

        if self.webUrlModified:

            self.webUrlModified = False

            url = self.leUrl.text().split(":")

            protocol = url[0]

            consoleUrl = url[1].replace("/", "").strip()

            portBaseUrl = url[2].split("/")

            port = portBaseUrl[0]

            baseurl = ""
            if len(portBaseUrl) > 1:
                baseurl = "/" + portBaseUrl[1] + "/"

            self.parser.set(section_name, 'protocol', protocol)
            self.parser.set(section_name, 'console.url', consoleUrl)
            self.parser.set(section_name, 'console.port', port)
            self.parser.set(section_name, 'console.baseurl', baseurl)

        if self.amqpUrlModified:

            self.amqpUrlModified = False

            url = self.le1Url.text().split(":")
            protocol = url[0]
            amqpUrl = url[1].replace("/", "").strip()
            amqpPort = url[2]

            self.parser.set(section_name, 'amqp.protocol', protocol)
            self.parser.set(section_name, 'amqp.url', amqpUrl)
            self.parser.set(section_name, 'amqp.port', amqpPort)

        if self.userIdModified:
            self.userIdModified = False
            self.parser.set(section_name, 'username',
                            self.leUserId.text().strip())

        if self.passkeyFileModified:
            self.passkeyFileModified = False
            self.parser.set(section_name, 'passkey.file',
                            self.lePassKey.text().strip())

        if self.passwordModified:
            self.passwordModified = False

            passwd = self.lePassword.text()
            #passKeyFile = "{fpath}{file}".format(fpath = self.filePath, file=self.parser.get(section_name, 'passkey.file'))
            passKeyFile = self.lePassKey.text()

            encPass = ""
            if len(passKeyFile) != 0 and len(passwd) != 0:
                encPass = encrypt.encrypt_password(passKeyFile, passwd)

            self.parser.set(section_name, 'password', encPass)

        if self.vhostModified:
            self.vhostModified = False
            self.parser.set(section_name, 'vhost', self.leVhost.text())

        if self.certNameModified:
            self.certNameModified = False
            self.parser.set(section_name, 'certificateName',
                            self.leCertificateName.text())

        if self.passkeyCertFileModified:
            self.passkeyCertFileModified = False
            self.parser.set(section_name, 'passkeycert.file',
                            self.leCertificatePassKey.text().strip())

        if self.certPassModified:
            self.certPassModified = False

            passwd = self.leCertificatePassword.text()
            #passKeyFile = "{fpath}{file}".format(fpath = self.filePath, file=self.parser.get(section_name, 'passkeycert.file'))
            #passKeyFile = ".{file}".format(file=self.parser.get(section_name, 'passkeycert.file'))
            passKeyFile = self.leCertificatePassKey.text()

            encPass = ""
            if len(passKeyFile) != 0 and len(passwd) != 0:
                encPass = encrypt.encrypt_password(passKeyFile, passwd)

            self.parser.set(section_name, 'certificatePassword', encPass)

        with open(self.inifile, 'w') as configfile:
            self.parser.write(configfile)

        self.refresh()

        #index = self.leServer.findText(section_name, Qt.MatchFixedString)
        #if index >= 0:
        #    self.leServer.setCurrentIndex(index)


        MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry updated!", \
                                   "Server: {section} update in File: {file} sucessfully.".format(section=section_name, file=self.inifile))
Exemple #29
0
    def buttonClicked(self):
        button = self.sender()
        #print(button.objectName())

        if not button: return

        buttonObjectName = button.objectName()

        if buttonObjectName == "add_setting":

            section_name = self.leAddServer.text()

            self.parser.add_section(section_name)

            self.parser.set(section_name, 'protocol',
                            self.wprotocolCombo.currentText().strip())
            self.parser.set(section_name, 'console.url',
                            self.whost.text().strip())
            self.parser.set(section_name, 'console.port',
                            self.wport.text().strip())
            self.parser.set(section_name, 'console.baseurl',
                            self.wbaseurl.text().strip())

            self.parser.set(section_name, 'amqp.protocol',
                            self.amqpCombo.currentText().strip())
            self.parser.set(section_name, 'amqp.url',
                            self.amqphost.text().strip())
            self.parser.set(section_name, 'amqp.port',
                            self.amqpport.text().strip())

            self.parser.set(section_name, 'username',
                            self.leUserId.text().strip())

            passKeyFile = self.lePassKey.text().strip()
            self.parser.set(section_name, 'passkey.file', passKeyFile)

            passwd = self.lePassword.text()
            encPass = ""
            if len(passKeyFile) != 0 and len(passwd) != 0:
                encPass = encrypt.encrypt_password(passKeyFile, passwd)
            self.parser.set(section_name, 'password', encPass)

            self.parser.set(section_name, 'vhost', self.leVhost.text().strip())
            self.parser.set(section_name, 'certificateName',
                            self.leCertificateName.text().strip())

            certPasskeyFile = self.leCertificatePassKey.text().strip()
            self.parser.set(section_name, 'passkeycert.file', certPasskeyFile)

            certpasswd = self.leCertificatePassword.text()
            encCertPass = ""
            if len(certPasskeyFile) != 0 and len(certpasswd) != 0:
                encCertPass = encrypt.encrypt_password(certPasskeyFile,
                                                       certpasswd)
            self.parser.set(section_name, 'certificatePassword', encCertPass)

            with open(self.inifile, 'w') as configfile:
                self.parser.write(configfile)

            #self.refresh()

            MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry added!", \
                                   "Server: {section} added to File: {file} sucessfully.".format(section=section_name, file=self.inifile))

            self.resetWidget()
        elif buttonObjectName == "edit_setting":
            pass
        elif buttonObjectName == "cancel_setting":
            self.resetWidget()
Exemple #30
0
    logfile = open(logfilename, 'w').close() # Clear log file
    logging.basicConfig(format='%(asctime)s %(message)s', filename=logfilename, 
            level=logging.ERROR)

    text = open(filename, 'r')
    url = text.read()
    url = convertURL(url)

    seen_posts = [] # Store which posts we've already marked as potential signups
    checkpoint = 1 # 1 to ignore OP post

    startup_delay_thread = Thread(target=delaySignUpNotifications, args=())
    startup_delay_thread.daemon = True
    startup_delay_thread.start()

    messageBox = MessageBox()

    # Initialise Pushover Client
    client = None
    if SEND_PUSH_NOTIFICATIONS:
        try:
            client = Client(getenv("USER_KEY"), api_token=getenv("API_TOKEN"), device=getenv("DEVICE"))
            print("Pushover client initialised successfully")
        except:
            logging.exception("An exception occured. Stack trace below")

    while True:
        try:
            response = requests.get(url)
            parsed_json = json.loads(response.text)
            if not thread_limit_reached_message_displayed:
Exemple #31
0
def msg_update(msg, fingerprint):
  session = (fingerprint, )
  MessageBox.append_session(session, msg)
class AlarmHandler:
    '''
    This class starts a QTimer dedicated
    to checking is there are any errors
    or warnings coming from ESP32
    '''

    def __init__(self, config, esp32):
        '''
        Constructor

        arguments:
        - config: the dictionary storing the configuration
        - esp32: the esp32serial object
        '''

        self._config = config
        self._esp32 = esp32

        self._alarm_raised = False
        self._warning_raised = False

        self._msg_err = MessageBox()
        self._msg_war = MessageBox()

        self._alarm_timer = QtCore.QTimer()
        self._alarm_timer.timeout.connect(self.handle_alarms)
        self._alarm_timer.start(config["alarminterval"] * 1000)



    def handle_alarms(self):
        '''
        The callback method which is called periodically
        to check if the ESP raised any alarm or warning.
        If an alarm or warning is raised, a pop up
        window appears, showing the list of alarms and
        warnings. If more alarms or warnings add up, the
        window is updated automatically showing the latest
        errors.
        '''

        # Retrieve alarms and warnings from the ESP
        try:
            esp32alarm = self._esp32.get_alarms()
            esp32warning = self._esp32.get_warnings()
        except Exception as error:
            esp32alarm = None
            esp32warning = None
            err_msg = "Severe hardware communication error. "
            err_msg += "Cannot retrieve alarm and warning statuses from hardware."
            msg = MessageBox()
            fn = msg.critical("Critical",
                              err_msg,
                              str(error),
                              "Communication error",
                              { msg.Retry: lambda: None,
                                msg.Abort: lambda: None })
            fn()

        #
        # ALARMS
        #
        if esp32alarm:
            errors = esp32alarm.strerror_all()
            errors_full = esp32alarm.strerror_all(append_err_no=True)

            if not self._alarm_raised:
                self._alarm_raised = True
                self._msg_err.critical("ALARM",
                             " - ".join(errors),
                             "\n".join(errors_full),
                             "Alarm received.",
                             { self._msg_err.Ignore: lambda:
                                 self.ok_worker('alarm', esp32alarm) },
                             do_not_block=True)
                self._msg_err.move(0, 100)
                self._msg_err.open()
            else:
                # If the window is already opened, just change the text
                self._msg_err.setInformativeText(" - ".join(errors))
                self._msg_err.setDetailedText("\n".join(errors_full))
                self._msg_err.raise_()


        #
        # WARNINGS
        #
        if esp32warning:
            errors = esp32warning.strerror_all()
            errors_full = esp32warning.strerror_all(append_err_no=True)

            if not self._warning_raised:
                self._warning_raised = True
                self._msg_war.warning("WARNING",
                             " - ".join(errors),
                             "\n".join(errors_full),
                             "Warning received.",
                             { self._msg_war.Ok: lambda:
                                 self.ok_worker('warning', esp32warning) },
                             do_not_block=True)
                self._msg_war.move(0, 300)
                self._msg_war.open()
            else:
                # If the window is already opened, just change the text
                self._msg_war.setInformativeText(" - ".join(errors))
                self._msg_war.setDetailedText("\n".join(errors_full))
                self._msg_war.raise_()


    def ok_worker(self, mode, raised_ones):
        '''
        The callback function called when the alarm
        or warning pop up window is closed by clicking
        on the Ok button.

        arguments:
        - mode: what this is closing, an 'alarm' or a 'warning'
        '''

        if mode not in ['alarm', 'warning']:
            raise Exception('mode must be alarm or warning.')

        if mode == 'alarm':
            self._alarm_raised = False
        else:
            self._warning_raised = False

        # Reset the alarms/warnings in the ESP
        # If the ESP connection fails at this
        # time, raise an error box
        try:
            if mode == 'alarm':
                for alarm_code in raised_ones.unpack():
                    self._esp32.snooze_hw_alarm(alarm_code)
            else:
                self._esp32.reset_warnings()
        except Exception as error:
            msg = MessageBox()
            fn = msg.critical("Critical",
                              "Severe hardware communication error",
                              str(error),
                              "Communication error",
                              { msg.Retry: lambda: self.ok_worker(mode),
                                msg.Abort: lambda: None })
            fn()

    def raise_alarm(self):
        '''
        Raises an alarm in the ESP
        '''
        self._esp32.raise_gui_alarm()

    def stop_alarm(self, code):
        '''
        Stops an alarm in the ESP
        '''
        self._esp32.reset_alarms()
    def handle_alarms(self):
        '''
        The callback method which is called periodically
        to check if the ESP raised any alarm or warning.
        If an alarm or warning is raised, a pop up
        window appears, showing the list of alarms and
        warnings. If more alarms or warnings add up, the
        window is updated automatically showing the latest
        errors.
        '''

        # Retrieve alarms and warnings from the ESP
        try:
            esp32alarm = self._esp32.get_alarms()
            esp32warning = self._esp32.get_warnings()
        except Exception as error:
            esp32alarm = None
            esp32warning = None
            err_msg = "Severe hardware communication error. "
            err_msg += "Cannot retrieve alarm and warning statuses from hardware."
            msg = MessageBox()
            fn = msg.critical("Critical",
                              err_msg,
                              str(error),
                              "Communication error",
                              { msg.Retry: lambda: None,
                                msg.Abort: lambda: None })
            fn()

        #
        # ALARMS
        #
        if esp32alarm:
            errors = esp32alarm.strerror_all()
            errors_full = esp32alarm.strerror_all(append_err_no=True)

            if not self._alarm_raised:
                self._alarm_raised = True
                self._msg_err.critical("ALARM",
                             " - ".join(errors),
                             "\n".join(errors_full),
                             "Alarm received.",
                             { self._msg_err.Ignore: lambda:
                                 self.ok_worker('alarm', esp32alarm) },
                             do_not_block=True)
                self._msg_err.move(0, 100)
                self._msg_err.open()
            else:
                # If the window is already opened, just change the text
                self._msg_err.setInformativeText(" - ".join(errors))
                self._msg_err.setDetailedText("\n".join(errors_full))
                self._msg_err.raise_()


        #
        # WARNINGS
        #
        if esp32warning:
            errors = esp32warning.strerror_all()
            errors_full = esp32warning.strerror_all(append_err_no=True)

            if not self._warning_raised:
                self._warning_raised = True
                self._msg_war.warning("WARNING",
                             " - ".join(errors),
                             "\n".join(errors_full),
                             "Warning received.",
                             { self._msg_war.Ok: lambda:
                                 self.ok_worker('warning', esp32warning) },
                             do_not_block=True)
                self._msg_war.move(0, 300)
                self._msg_war.open()
            else:
                # If the window is already opened, just change the text
                self._msg_war.setInformativeText(" - ".join(errors))
                self._msg_war.setDetailedText("\n".join(errors_full))
                self._msg_war.raise_()
    def buttonClicked(self):
        button = self.sender()
        #print(button.objectName())

        if not button: return

        buttonObjectName = button.objectName()

        exTableModel = self.exargstablemodelview.model()
        qTableModel = self.qargstablemodelview.model()
        bindingTableModel = self.bindingargstablemodelview.model()

        if buttonObjectName == "addExArgsKey":
            data = [[]]
            self.addRow(exTableModel, data)
            self.exchangeadd = True
        elif buttonObjectName == "delExArgsKey":
            del exTableModel.arraydata[self.tableSelectedRow]
            exTableModel.changeData(exTableModel.arraydata)

            self.exArgsDelButton.setEnabled(False)
        elif buttonObjectName == "addQArgsKey":
            data1 = [[]]
            self.addRow(qTableModel, data1)
            self.queueadd = True
        elif buttonObjectName == "delQArgsKey":
            del qTableModel.arraydata[self.tableSelectedRow]
            qTableModel.changeData(qTableModel.arraydata)

            self.qArgsDelButton.setEnabled(False)
        elif buttonObjectName == "addBindArgsKey":
            data2 = [[]]
            self.addRow(bindingTableModel, data2)
            self.bindadd = True
        elif buttonObjectName == "delBindArgsKey":
            del bindingTableModel.arraydata[self.tableSelectedRow]
            bindingTableModel.changeData(bindingTableModel.arraydata)

            self.bindingArgsDelButton.setEnabled(False)
        elif buttonObjectName == "addExchange":
            #exchange_declare(exchange, exchange_type='direct', passive=False, durable=False, auto_delete=False, internal=False, arguments=None, callback=None)

            exchange = self.exName.text()
            exchange_type = str(self.exType.currentText())
            durable = True if str(
                self.durability.currentText()) == "Durable" else False
            auto_delete = False if str(
                self.autoDelete.currentText()) == "No" else True
            internal = False if str(
                self.internal.currentText()) == "No" else True

            exTableModel.removeRowsWithEmptyColumns()
            arguments = dict(exTableModel.arraydata)
            if arguments == {}:
                arguments = None

            #print(exchange, exchange_type, durable, auto_delete, internal, arguments)
            try:
                channel = self.eqbConnection.channel()
                channel.exchange_declare(exchange=exchange,
                                         exchange_type=exchange_type,
                                         durable=durable,
                                         auto_delete=auto_delete,
                                         internal=internal,
                                         arguments=arguments)
                if channel.is_open:
                    channel.close()

                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Exchange",
                    "Exchange Created!",
                    "{exch} has been created.".format(exch=exchange))

                self.elist = RestFunctions.exchange_list(
                    RestFunctions, self, self.sessionAvailable, self.session,
                    self._webUrl, self._userId, self._password, self._certName)

                for item in self.elist:
                    name = item["name"]
                    if len(name) == 0 or name.find(
                            self._userId.lower().replace("_", "")) > -1:
                        if (len(name) != 0):
                            self.source.addItem(str(name))
                self._refresh.emit(True)
            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip(
                ) + ". Check Queue naming policy with your administrator."
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Exchange Creation - Error ({})".format(error[0]),
                    text, infoText)

        elif buttonObjectName == "delExchange":
            #exchange_delete(exchange=None, if_unused=False, callback=None)
            try:
                channel = self.eqbConnection.channel()

                exchange = self.exName.text()
                exch_exist = channel.exchange_declare(exchange=exchange,
                                                      passive=True)

                if exch_exist:
                    channel.exchange_delete(exchange=exchange)

                    MessageBox.message(
                        QMessageBox.Information, "RabbitMQ Exchange",
                        "Exchange Deleted!",
                        "{exch} has been deleted.".format(exch=exchange))

                    self.elist = RestFunctions.exchange_list(
                        RestFunctions, self, self.sessionAvailable,
                        self.session, self._webUrl, self._userId,
                        self._password, self._certName)

                    for item in self.elist:
                        name = item["name"]
                        if len(name) == 0 or name.find(
                                self._userId.lower().replace("_", "")) > -1:
                            if (len(name) != 0):
                                self.source.addItem(str(name))
                    self._refresh.emit(True)

                if channel.is_open:
                    channel.close()

            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip()
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Exchange Deletion - Error ({})".format(error[0]),
                    text, infoText)
        elif buttonObjectName == "addQueue":
            queue = self.qName.text()
            durable = True if str(
                self.qDurability.currentText()) == "Durable" else False
            auto_delete = False if str(
                self.qAutoDelete.currentText()) == "No" else True

            qTableModel.removeRowsWithEmptyColumns()
            arguments = dict(qTableModel.arraydata)

            if arguments == {}:
                arguments = None

            try:
                channel = self.eqbConnection.channel()

                channel.queue_declare(queue=queue,
                                      durable=durable,
                                      auto_delete=auto_delete,
                                      arguments=arguments)
                if channel.is_open:
                    channel.close()

                MessageBox.message(QMessageBox.Information, "RabbitMQ Queue",
                                   "Queue Created!",
                                   "{que} has been added.".format(que=queue))

                self.qlist = RestFunctions.queue_list(
                    RestFunctions, self, self.sessionAvailable, self.session,
                    self._webUrl, self._userId, self._password, self._certName)
                for item in self.qlist:
                    name = item["name"]
                    if len(name) == 0 or name.find(
                            self._userId.lower().replace("_", "")) > -1:
                        if (len(name) != 0):
                            self.target.addItem(str(name))
                self._refresh.emit(True)
            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip(
                ) + ". Check Queue naming policy with your administrator."
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Queue Creation - Error ({})".format(error[0]),
                    text, infoText)

        elif buttonObjectName == "delQueue":
            try:
                channel = self.eqbConnection.channel()
                queue = self.qName.text()

                queue_exist = channel.queue_declare(queue=queue, passive=True)

                if queue_exist:
                    channel.queue_delete(queue=queue)

                    MessageBox.message(
                        QMessageBox.Information, "RabbitMQ Queue",
                        "Queue Deleted!",
                        "{que} has been deleted.".format(que=queue))

                    self.qlist = RestFunctions.queue_list(
                        RestFunctions, self, self.sessionAvailable,
                        self.session, self._webUrl, self._userId,
                        self._password, self._certName)
                    for item in self.qlist:
                        name = item["name"]
                        if len(name) == 0 or name.find(
                                self._userId.lower().replace("_", "")) > -1:
                            if (len(name) != 0):
                                self.target.addItem(str(name))
                    self._refresh.emit(True)

                if channel.is_open:
                    channel.close()

            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip()
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Queue Deletion - Error ({})".format(error[0]),
                    text, infoText)
            self._refresh.emit(True)
        elif buttonObjectName == "purgeQueue":
            try:
                channel = self.eqbConnection.channel()
                queue = self.qName.text()

                queue_exist = channel.queue_declare(queue=queue, passive=True)

                if queue_exist:
                    channel.queue_purge(queue=queue)

                    MessageBox.message(
                        QMessageBox.Information, "RabbitMQ Queue",
                        "Queue Purged!",
                        "{que} has been purged.".format(que=queue))

                    self._refresh.emit(True)
                if channel.is_open:
                    channel.close()
            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip()
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Queue Purge - Error ({})".format(error[0]), text,
                    infoText)

        elif buttonObjectName == "addBind":

            destination = self.target.currentText()
            source = self.source.currentText()
            routing_key = self.rkey.text()

            bindingTableModel.removeRowsWithEmptyColumns()
            arguments = dict(bindingTableModel.arraydata)
            if arguments == {}:
                arguments = None

            if self.exchange2exchange.isChecked():

                if len(routing_key) == 0:
                    routing_key = ''

                channel = self.eqbConnection.channel()
                channel.exchange_bind(destination=destination,
                                      source=source,
                                      routing_key=routing_key,
                                      arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Binding",
                    "Exchange to Exchange Binding!",
                    "Binding created between Exchange:{exch1} and Exchange:{exch2}."
                    .format(exch1=destination, exch2=source))

                self._refresh.emit(True)

                if channel.is_open:
                    channel.close()
            elif self.exchange2queue.isChecked():
                if len(routing_key) == 0:
                    routing_key = None

                channel = self.eqbConnection.channel()
                channel.queue_bind(queue=destination,
                                   exchange=source,
                                   routing_key=routing_key,
                                   arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Binding",
                    "Queue to Exchange Binding!",
                    "Binding created between Queue:{que} and Exchange:{exch1}."
                    .format(que=destination, exch1=source))
                self._refresh.emit(True)
                if channel.is_open:
                    channel.close()

        elif buttonObjectName == "unBind":

            destination = self.target.currentText()
            source = self.source.currentText()
            routing_key = self.rkey.text()

            bindingTableModel.removeRowsWithEmptyColumns()
            arguments = dict(bindingTableModel.arraydata)
            if arguments == {}:
                arguments = None

            if self.exchange2exchange.isChecked():

                if len(routing_key) == 0:
                    routing_key = ''

                channel = self.eqbConnection.channel()
                channel.exchange_unbind(destination=destination,
                                        source=source,
                                        routing_key=routing_key,
                                        arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ UnBinding",
                    "Exchange to Exchange UnBinding!",
                    "Binding removed between Exchange:{exch1} and Exchange:{exch2}."
                    .format(exch1=destination, exch2=source))

                self._refresh.emit(True)
                if channel.is_open:
                    channel.close()
            elif self.exchange2queue.isChecked():

                if len(routing_key) == 0:
                    routing_key = None

                channel = self.eqbConnection.channel()
                channel.queue_unbind(queue=destination,
                                     exchange=source,
                                     routing_key=routing_key,
                                     arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ UnBinding",
                    "Queue to Exchange UnBinding!",
                    "Binding removed between Queue:{que} and Exchange:{exch1}."
                    .format(que=destination, exch1=source))
                self._refresh.emit(True)
                if channel.is_open:
                    channel.close()
Exemple #35
0
class Gellies(GUIFramework):
    menuitems = (
        'File- &Exit/Ctrl+q/self.quit',
    )
    def __init__(self, root):
        GUIFramework.__init__(self, root)
        self.root = root
        self.build_GUI()
        self.r2mapsID = None

    def build_GUI(self):
        books = ('Project', 'R2map', 'Calibration')
        self.left_frame = tk.Frame(self.root)
        self.left_frame.pack(side=tk.LEFT, fill=tk.Y, expand=0)

        self.right_frame = tk.Frame(self.root)
        self.right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.notebook = ttk.Notebook(self.left_frame)
        self.notebook.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.book1 = tk.Frame(self.notebook)
        self.notebook.add(self.book1, text='Project')
        self.book2 = tk.Frame(self.notebook)
        self.notebook.add(self.book2, text='R2map')
        self.book3 = tk.Frame(self.notebook)
        self.notebook.add(self.book3, text='Calibration')
        self.notebook.bind('<<NotebookTabChanged>>', self.notebook_changed)

        self.main_frame = tk.Frame(self.right_frame)
        self.main_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.make_project_book(self.book1)
        self.make_r2map_book(self.book2)
        self.make_calibration_book(self.book3)

        self.message_box_frame = tk.LabelFrame(self.right_frame, text='Messages')
        self.message_box_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1)
        self.messagebox = MessageBox(self.message_box_frame)
        self.messagebox.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.r2value = []
        self.dose = []


    def make_project_book(self, book):
        self.project_panel = ProjectManager(book, 'projectinfo')
        self.project_panel.register(self)

        self.img_frame = tk.LabelFrame(self.main_frame, text='Dicom images')
        self.img_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.dicom_img = ImagePanel(self.img_frame, 'main_img', wl=True, toolbar=True, info=True, cb=True)
        self.dicom_img.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def make_r2map_book(self, book):
        #toolbaritems = ('Save$icons/Save$tk.FLAT$self.saveR2$tk.LEFT$Save R2 parameters',
        #                'Exit$icons/Exit$tk.FLAT$self.quit$tk.RIGHT$Exit')
        #button_bar = self.make_button_bar(book, toolbaritems, tk.TOP)
        #button_bar.pack(side=tk.TOP, fill=tk.X, expand=0)

        self.r2map_panel = R2MapPanel(book, self.project_panel, 'r2mappanel')
        self.r2map_panel.pack(side=tk.TOP, fill=tk.Y, expand=1)
        self.r2map_panel.register(self)

        self.r2map_dicom_frame = tk.LabelFrame(self.main_frame, text='Dicom image')
        self.r2map_dicom_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        self.r2map_dicom_img = ImagePanel(self.r2map_dicom_frame, 'r2map_dicom_frame', wl=True, toolbar=True, info=False, cb=True)
        self.r2map_dicom_img.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.r2map_dicom_img.register(self)

        self.r2map_frame = tk.LabelFrame(self.main_frame, text='R2map')
        self.r2map_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        self.r2map_img = ImagePanel(self.r2map_frame, 'r2map_frame', wl=True, toolbar=True, info=False, cb=True)
        self.r2map_img.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def make_calibration_book(self, book):
        self.calibration_panel = CalibrationPanel(book, 'calibrationpanel')
        self.calibration_panel.pack(side=tk.TOP, fill=tk.Y, expand=1)
        self.calibration_panel.register(self)

        self.calibration_r2map_frame = tk.LabelFrame(self.main_frame, text='R2map')
        self.calibration_r2map_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        self.calibration_r2map_img = ImagePanel(self.calibration_r2map_frame, 'calr2mapimg', wl=True, toolbar=True, info=False, cb=True)
        self.calibration_r2map_img.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.calibration_r2map_img.register(self)

        self.calibration_dosemap_frame = tk.LabelFrame(self.main_frame, text='Dose map')
        self.calibration_dosemap_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        self.calibration_dosemap_img = ImagePanel(self.calibration_dosemap_frame, 'caldosemapimg', wl=True, toolbar=True, info=False, cb=True)
        self.calibration_dosemap_img.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.calibration_dosemap_img.register(self)

    def notebook_changed(self, event):
        book = self.notebook.index(self.notebook.select())
        print(book)
        if book == 0:
            print('Book 1')
            for child in self.main_frame.winfo_children():
                child.pack_forget()
            self.img_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        if book == 1:
            print('Book 2')
            for child in self.main_frame.winfo_children()[:-1]:
                child.pack_forget()
            self.r2map_dicom_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
            self.r2map_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        if book == 2:
            print('Book 3')
            for child in self.main_frame.winfo_children():
                child.pack_forget()
            self.calibration_r2map_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
            self.calibration_dosemap_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

    def quit(self):
        self.root.quit()

    def update_(self, name, event):
        print(name, event)
        if name == 'projectinfo':
            if event == 'NewProject':
                self.messagebox.config(state=tk.NORMAL)
                self.messagebox.delete(1.0,tk.END)
                self.messagebox.insert(tk.END, '>> ')
                self.messagebox.config(state=tk.DISABLED)
                for item in self.r2map_panel.r2map_tree.get_children():
                    for child in self.r2map_panel.r2map_tree.children(item):
                        self.r2map_panel.r2map_tree.delete(child)
                    self.r2map_panel.r2map_tree.delete(item)
            if event == 'OpenProject':
                self.messagebox.config(state=tk.NORMAL)
                self.messagebox.delete(1.0,tk.END)
                self.messagebox.insert(tk.END, '>> Open ')
                self.messagebox.insert(tk.END, self.project_panel.get_project_name())
                self.messagebox.insert(tk.END, ' project.')
                self.messagebox.config(state=tk.DISABLED)
                for item in self.r2map_panel.r2map_tree.get_children():
                    for child in self.r2map_panel.r2map_tree.children(item):
                        self.r2map_panel.r2map_tree.delete(child)
                    self.r2map_panel.r2map_tree.delete(item)
                for key in sorted(self.project_panel.dicom_files):
                    id = self.r2map_panel.r2map_tree.insert('', 'end', text=key)
                    i=0
                    for item in self.project_panel.dicom_files[key]:
                        self.r2map_panel.r2map_tree.insert(id, 'end', text=str(i), values=(item.SeriesNumber, item.SeriesDescription, item.EchoTime))
                        i += 1
                if self.project_panel.meta_data['r2maps']:
                    self.r2mapsID = self.r2map_panel.r2map_tree.insert('', 'end', text='R2maps')
                    for key in self.project_panel.meta_data['r2maps']:
                        i=0
                        id = self.r2map_panel.r2map_tree.insert(self.r2mapsID, 'end', text=key)
                        self.r2maps = np.load(self.project_panel.project_dir+'/r2map'+'key')
                        for item in self.project_panel.meta_data['r2maps'][key]:
                            self.r2map_panel.r2map_tree.insert(id, 'end', text = str(i))
                            i += 1
            if event == 'ReadDicom':
                self.messagebox.config(state=tk.NORMAL)
                self.messagebox.insert(tk.END, '\n>> Read dicom files.')
                self.messagebox.config(state=tk.DISABLED)
        if name == 'projectinfo.treepanel':
            project_tree = self.project_panel.get_project_tree()
            if event == '<<TreeviewSelect>>':
                selection = project_tree.selection()[0]
                parent = project_tree.parent(selection)
                print(name, event, selection, parent)
                if parent:
                    self.dicom_img.set_images(self.project_panel.get_dicom_images()[parent])
                    self.dicom_img.set_indexOfImg(int(project_tree.item(project_tree.selection())['text']))
                    self.dicom_img.show_images()
                else:
                    self.dicom_img.set_images(self.project_panel.get_dicom_images()[selection])
            if event == 'delete_item':
                temp = {}
                for item in project_tree.get_children():
                    key = project_tree.item(item)['text']
                    temp[key] = self.project_panel.get_dicom_path()[key]
                self.project_panel.set_meta_data('dicom_dict', temp)

        if name == 'projectinfo.projectinfo':
            if event == 'Save':
                self.messagebox.config(state=tk.NORMAL)
                self.messagebox.insert(tk.END, '\n>> Save project data.')
                self.messagebox.config(state=tk.DISABLED)
            if event == 'Modify':
                self.messagebox.config(state=tk.NORMAL)
                self.messagebox.insert(tk.END, '\n>> Modify project data.')
                self.messagebox.config(state=tk.DISABLED)

        if name == 'r2projectpanel':
            if event == '<<TreeviewSelect>>':
                selection = self.r2map_panel.r2map_tree.selection()[0]
                parent = self.r2map_panel.r2map_tree.parent(selection)
                if parent:
                    self.r2map_dicom_img.set_images(self.project_panel.get_dicom_images()[parent])
                    self.r2map_dicom_img.set_indexOfImg(int(self.r2map_panel.r2map_tree.item(self.r2map_panel.r2map_tree.selection())['text']))
                    self.r2map_dicom_img.show_images()
                else:
                    self.r2map_dicom_img.set_images(self.project_panel.get_dicom_images()[selection])

        if name == 'r2mappanel':
            if event == 'r2mapping':
                if self.r2map_panel.map_algoritm.get() == 'Polyfit':
                    self.r2maping()
        if name == 'r2map_dicom_frame':
            if event == '<DrawRectangle>':
                print('OK')
                points = self.r2map_dicom_img.getRectanglePoints()
                self.r2map_panel.lx0.set(int(points[0]))
                self.r2map_panel.lx1.set(int(points[1]))
                self.r2map_panel.ly0.set(int(points[2]))
                self.r2map_panel.ly1.set(int(points[3]))

        if name == 'calibrationpanel':
            if event == 'calr2maptree.<<TreeviewSelect>>':
                selection = self.calibration_panel.r2maptree.selection()[0]
                self.calibration_r2map_img.set_images(self.r2maps)
            if event == 'addvalue':
                x0 = int(self.calibration_r2map_img.x0)
                x1 = int(self.calibration_r2map_img.x1)
                y0 = int(self.calibration_r2map_img.y0)
                y1 = int(self.calibration_r2map_img.y1)
                print(x0,x1,y1,y0)
                id = self.calibration_r2map_img.indexOfImg
                average = np.median(self.r2maps[id, y1:y0,x0:x1])
                print(self.r2maps[id, x0:x1,y1:y0])
                #sd = np.std(self.r2maps[id, x0:x1,y1:y0])
                print('Mean = '+str(average))
                #print('Std = '+str(sd))
                i = len(self.r2value)
                self.calibration_panel.spreadsheet.cells['R2'+str(i+1)].insert(0, average)
                self.r2value.append(average)
                self.calibration_dosemap_img.set_images(self.r2maps[:, x1:x0,y0:y1])
                self.calibration_dosemap_img.set_indexOfImg(id)
                self.calibration_dosemap_img.show_images()


    def r2maping(self):
        self.pixels = []
        self.te = []
        for item in self.r2map_panel.r2map_tree.get_children():
            self.pixels.append(self.project_panel.dicom_images[item])
            self.te.append(self.project_panel.project_tree.item(item)['text'])
        print(self.te)

        row = np.shape(self.pixels[0][0])[0]
        column = np.shape(self.pixels[0][0])[0]
        nSlice = np.shape(self.pixels[0])[0]
        print('Slice ' + str(nSlice))
        r2maps = []
        sigma = []
        images = self.pixels

        col0 = int(self.r2map_dicom_img.x0)
        col1 = int(self.r2map_dicom_img.x1)
        row0 = int(self.r2map_dicom_img.y0)
        row1 = int(self.r2map_dicom_img.y1)
        for s in range(0,nSlice):
            print(s)
            r2map = np.zeros((row, column))
            for i in range(row0,row1):
                for j in range(col0,col1):
                    temp = []
                    for item in self.pixels:
                        if item[s][i,j]!=0:
                            temp.append(np.log(item[s][i,j]))
                        else: temp.append(0)
                    slope = np.polyfit(self.te, temp,1)
                    r2map[i,j] = -slope[0]

            r2maps.append(r2map)

        #self.project_panel.meta_data['r2maps']['key'] = self.project_panel.project_dir+'/r2map'+'key'
        #with open(self.project_panel.project_dir+'/'+self.project_panel.project_name+'.dat', 'wb') as outfile:
        #    pickle.dump(self.project_panel.meta_data, outfile, protocol=pickle.HIGHEST_PROTOCOL)
        self.r2maps = np.array(r2maps)
        np.save(self.project_panel.project_dir+'/r2map'+'key', self.r2maps)
        self.r2map_img.set_images(self.r2maps)
        self.r2map_img.show_images()
        n = len(self.calibration_panel.r2maptree.get_children())
        self.calibration_panel.r2maptree.insert('', 'end', text=str(n+1), value=('', 'Polyfit'))