MqttMonitor/MqttConnectionOptionsDialog.py

Tue, 23 Jun 2020 19:26:33 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Tue, 23 Jun 2020 19:26:33 +0200
changeset 78
a22328182bc2
parent 66
9297e94d7d77
child 84
044df16e55aa
permissions
-rw-r--r--

Removed support for Python2.

# -*- coding: utf-8 -*-

# Copyright (c) 2018 - 2020 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a dialog to enter MQTT connection options.
"""

from PyQt5.QtCore import pyqtSlot, QUuid
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QAbstractButton

from E5Gui import E5MessageBox
from E5Gui.E5PathPicker import E5PathPickerModes

from .Ui_MqttConnectionOptionsDialog import Ui_MqttConnectionOptionsDialog

from Utilities.crypto import pwConvert


class MqttConnectionOptionsDialog(QDialog, Ui_MqttConnectionOptionsDialog):
    """
    Class implementing a dialog to enter MQTT connection options.
    """
    def __init__(self, client, options=None, parent=None):
        """
        Constructor
        
        @param client reference to the MQTT client object
        @type MqttClient
        @param options dictionary containing the connection options to
            populate the dialog with. It must have the keys "ClientId",
            "Keepalive", "CleanSession", "Username", "Password", "WillTopic",
            "WillMessage", "WillQos", "WillRetain", "TlsEnable", "TlsCaCert",
            "ConnectionTimeout".
        @type dict
        @param parent reference to the parent widget
        @type QWidget
        """
        super(MqttConnectionOptionsDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.__client = client
        
        self.tlsCertsFilePicker.setMode(E5PathPickerModes.OpenFileMode)
        self.tlsCertsFilePicker.setFilters(
            self.tr("Certificate Files (*.crt *.pem);;All Files (*)"))
        
        self.__populateDefaults(options=options)
        
        self.__updateOkButton()
    
    def __updateOkButton(self):
        """
        Private method to update the enabled state of the OK button.
        """
        if (
            self.clientIdEdit.text() == "" and
            not self.cleanSessionCheckBox.isChecked()
        ):
            enable = False
            E5MessageBox.critical(
                self,
                self.tr("Invalid Connection Parameters"),
                self.tr("""An empty Client ID requires a clean session."""))
        else:
            enable = True
        
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(enable)
    
    @pyqtSlot()
    def on_generateIdButton_clicked(self):
        """
        Private slot to generate a client ID.
        """
        uuid = QUuid.createUuid()
        self.clientIdEdit.setText(uuid.toString(QUuid.WithoutBraces))
    
    @pyqtSlot(QAbstractButton)
    def on_buttonBox_clicked(self, button):
        """
        Private slot to handle the press of a button box button.
        
        @param button button that has been pressed
        @type QAbstractButton
        """
        if button == self.buttonBox.button(QDialogButtonBox.RestoreDefaults):
            self.__populateDefaults(options=None)
    
    def __populateDefaults(self, options=None):
        """
        Private method to populate the dialog.
        
        If no options dictionary is given, the dialog will be populated with
        default values.
        
        @param options dictionary containing the connection options to populate
            the dialog with. It must have the keys "ClientId", "Keepalive",
            "CleanSession", "Username", "Password", "WillTopic", "WillMessage",
            "WillQos", "WillRetain", "TlsEnable", "TlsCaCert",
            "ConnectionTimeout".
        @type dict
        """
        if options is None:
            options = self.__client.defaultConnectionOptions()
        
        # general
        self.clientIdEdit.setText(options["ClientId"])
        self.connectionTimeoutSpinBox.setValue(options["ConnectionTimeout"])
        self.keepaliveSpinBox.setValue(options["Keepalive"])
        self.cleanSessionCheckBox.setChecked(options["CleanSession"])
        
        # user credentials
        self.usernameEdit.setText(options["Username"])
        self.passwordEdit.setText(pwConvert(options["Password"], encode=False))
        
        # last will and testament
        self.willQosSpinBox.setValue(options["WillQos"])
        self.willRetainCheckBox.setChecked(options["WillRetain"])
        self.willTopicEdit.setText(options["WillTopic"])
        self.willMessageEdit.setPlainText(options["WillMessage"])
        
        # TLS parameters
        self.tlsEnableCheckBox.setChecked(options["TlsEnable"])
        self.tlsCertsFilePicker.setText(options["TlsCaCert"])
    
    def getConnectionOptions(self):
        """
        Public method get the entered connection options.
        
        @return dictionary containing the connection options. It has the keys
            "ClientId", "Keepalive", "CleanSession", "Username", "Password",
            "WillTopic", "WillMessage", "WillQos", "WillRetain", "TlsEnable",
            "TlsCaCert", "ConnectionTimeout".
        @rtype tuple of (int, dict)
        """
        return {
            "ClientId": self.clientIdEdit.text(),
            "ConnectionTimeout": self.connectionTimeoutSpinBox.value(),
            "Keepalive": self.keepaliveSpinBox.value(),
            "CleanSession": self.cleanSessionCheckBox.isChecked(),
            "Username": self.usernameEdit.text(),
            "Password": pwConvert(self.passwordEdit.text(), encode=True),
            "WillTopic": self.willTopicEdit.text(),
            "WillMessage": self.willMessageEdit.toPlainText(),
            "WillQos": self.willQosSpinBox.value(),
            "WillRetain": self.willRetainCheckBox.isChecked(),
            "TlsEnable": self.tlsEnableCheckBox.isChecked(),
            "TlsCaCert": self.tlsCertsFilePicker.text()
        }
    
    @pyqtSlot(str)
    def on_clientIdEdit_textChanged(self, clientId):
        """
        Private slot handling a change of the client ID string.
        
        @param clientId client ID
        @type str
        """
        self.__updateOkButton()
    
    @pyqtSlot(bool)
    def on_cleanSessionCheckBox_clicked(self, checked):
        """
        Private slot to handle a change of the clean session selection.
        
        @param checked current state of the clean session selection
        @type bool
        """
        self.__updateOkButton()

eric ide

mercurial