PluginMqttMonitor.py

Thu, 28 May 2020 17:36:58 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Thu, 28 May 2020 17:36:58 +0200
changeset 77
a580238d85de
parent 75
5e760c5c20af
child 78
a22328182bc2
permissions
-rw-r--r--

Changed fail message.

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

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

"""
Module implementing the MQTT Monitor plug-in.
"""

from __future__ import unicode_literals

import os
import json

from PyQt5.QtCore import Qt, QObject, QTranslator, QCoreApplication
from PyQt5.QtGui import QKeySequence

from E5Gui.E5Application import e5App
from E5Gui.E5Action import E5Action

import UI.PixmapCache
import Preferences

# Start-Of-Header
name = "MQTT Monitor Plugin"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "1.2.3"
className = "MqttMonitorPlugin"
packageName = "MqttMonitor"
shortDescription = "Plug-in implementing a tool to connect to a MQTT broker"
longDescription = (
    """Plug-in implementing a tool to connect to a MQTT broker, subscribe"""
    """ to topics, present received messages and publish messages."""
    """ It displays broker statistics (the $SYS/# topic tree) and"""
    """ log messages of the underlying paho-mqtt client. This tool"""
    """ support unencrypted connections (port 1883) as well as encrypted"""
    """ SSL/TLS connections (port 8883)\n\n"""
    """Note: The paho-mqtt Python package must be installed."""
)
needsRestart = False
pyqtApi = 2
python2Compatible = True
# End-Of-Header

error = ""
    

def exeDisplayData():
    """
    Module function to support the display of some executable info.
    
    @return dictionary containing the data to query the presence of
        the executable
    @rtype dict
    """
    try:
        import paho.mqtt
        version = paho.mqtt.__version__
    except ImportError:
        version = QCoreApplication.translate(
            "MqttMonitorPlugin", "(package not available)")
    
    data = {
        "programEntry": False,
        "header": QCoreApplication.translate("MqttMonitorPlugin", "MQTT"),
        "text": QCoreApplication.translate("MqttMonitorPlugin", "paho-mqtt"),
        "version": version,
    }
    
    return data


def prepareUninstall():
    """
    Module function to prepare for an uninstallation.
    """
    Preferences.Prefs.settings.remove(MqttMonitorPlugin.PreferencesKey)


class MqttMonitorPlugin(QObject):
    """
    Class implementing the MQTT Monitor plug-in.
    """
    PreferencesKey = "MqttMonitor"
    
    def __init__(self, ui):
        """
        Constructor
        
        @param ui reference to the user interface object
        @type UI.UserInterface
        """
        super(MqttMonitorPlugin, self).__init__(ui)
        self.__ui = ui
        self.__initialize()
        
        self.__defaults = {
            "RecentBrokersWithPort": "[]",      # JSON formatted empty list
            "BrokerProfiles": "{}",             # JSON formatted empty dict
            # __IGNORE_WARNING_M613__
            "MostRecentProfile": "",            # most recently used profile
        }
        
        self.__translator = None
        self.__loadTranslator()
    
    def __initialize(self):
        """
        Private slot to (re)initialize the plugin.
        """
        self.__widget = None
    
    def activate(self):
        """
        Public method to activate this plug-in.
        
        @return tuple of None and activation status
        @rtype bool
        """
        global error
        error = ""     # clear previous error
        
        try:
            import paho.mqtt        # __IGNORE_WARNING__
        except ImportError:
            error = self.tr("The 'paho-mqtt' package is not available.")
            return None, False
        
        from MqttMonitor.MqttMonitorWidget import MqttMonitorWidget
        
        try:
            usesDarkPalette = e5App().usesDarkPalette()
        except AttributeError:
            from PyQt5.QtGui import QPalette
            palette = e5App().palette()
            lightness = palette.color(QPalette.Window).lightness()
            usesDarkPalette = lightness <= 128
        if usesDarkPalette:
           iconSuffix = "dark"
        else:
            iconSuffix = "light"
        
        self.__widget = MqttMonitorWidget(self, iconSuffix)
        self.__ui.addSideWidget(
            self.__ui.RightSide, self.__widget,
            UI.PixmapCache.getIcon(
                os.path.join("MqttMonitor", "icons",
                             "mqtt22-{0}".format(iconSuffix))),
            self.tr("MQTT Monitor"))
        
        self.__activateAct = E5Action(
            self.tr('MQTT Monitor'),
            self.tr('M&QTT Monitor'),
            QKeySequence(self.tr("Alt+Shift+Q")),
            0, self,
            'mqtt_monitor_activate')
        self.__activateAct.setStatusTip(self.tr(
            "Switch the input focus to the MQTT Monitor window."))
        self.__activateAct.setWhatsThis(self.tr(
            """<b>Activate MQTT Monitor</b>"""
            """<p>This switches the input focus to the MQTT Monitor"""
            """ window.</p>"""
        ))
        self.__activateAct.triggered.connect(self.__activateWidget)
        
        self.__ui.addE5Actions([self.__activateAct], 'ui')
        menu = self.__ui.getMenu("subwindow")
        menu.addAction(self.__activateAct)
        
        return None, True
    
    def deactivate(self):
        """
        Public method to deactivate this plug-in.
        """
        menu = self.__ui.getMenu("subwindow")
        menu.removeAction(self.__activateAct)
        self.__ui.removeE5Actions([self.__activateAct], 'ui')
        self.__ui.removeSideWidget(self.__widget)
        
        self.__initialize()
    
    def __loadTranslator(self):
        """
        Private method to load the translation file.
        """
        if self.__ui is not None:
            loc = self.__ui.getLocale()
            if loc and loc != "C":
                locale_dir = os.path.join(
                    os.path.dirname(__file__), "MqttMonitor", "i18n")
                translation = "mqttmonitor_{0}".format(loc)
                translator = QTranslator(None)
                loaded = translator.load(translation, locale_dir)
                if loaded:
                    self.__translator = translator
                    e5App().installTranslator(self.__translator)
                else:
                    print("Warning: translation file '{0}' could not be"
                          " loaded.".format(translation))
                    print("Using default.")
    
    def __activateWidget(self):
        """
        Private slot to handle the activation of the MQTT Monitor.
        """
        try:
            uiLayoutType = self.__ui.getLayoutType()
        except AttributeError:
            # backward compatibility for eric < 18.08
            uiLayoutType = self.__ui.layoutType
        
        if uiLayoutType == "Toolboxes":
            self.__ui.rToolboxDock.show()
            self.__ui.rToolbox.setCurrentWidget(self.__widget)
        elif uiLayoutType == "Sidebars":
            self.__ui.rightSidebar.show()
            self.__ui.rightSidebar.setCurrentWidget(self.__widget)
        else:
            self.__widget.show()
        self.__widget.setFocus(Qt.ActiveWindowFocusReason)
    
    def getPreferences(self, key):
        """
        Public method to retrieve the various settings.
        
        @param key the key of the value to get
        @return the requested setting
        """
        if key in ["RecentBrokersWithPort", "BrokerProfiles"]:
            return json.loads(Preferences.Prefs.settings.value(
                self.PreferencesKey + "/" + key, self.__defaults[key]))
        else:
            return Preferences.Prefs.settings.value(
                self.PreferencesKey + "/" + key, self.__defaults[key])
    
    def setPreferences(self, key, value):
        """
        Public method to store the various settings.
        
        @param key the key of the setting to be set (string)
        @param value the value to be set
        """
        if key in ["RecentBrokersWithPort", "BrokerProfiles"]:
            Preferences.Prefs.settings.setValue(
                self.PreferencesKey + "/" + key, json.dumps(value))
        else:
            Preferences.Prefs.settings.setValue(
                self.PreferencesKey + "/" + key, value)

#
# eflag: noqa = M801

eric ide

mercurial