MqttMonitorWidget: added capability to save the received messages and log messages to a file.

Sat, 15 Sep 2018 12:12:01 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Sat, 15 Sep 2018 12:12:01 +0200
changeset 50
8e9e83221c15
parent 49
a7e370d20ab3
child 51
b865211461c7

MqttMonitorWidget: added capability to save the received messages and log messages to a file.

MqttMonitor/MqttMonitorWidget.py file | annotate | diff | comparison | revisions
MqttMonitor/MqttMonitorWidget.ui file | annotate | diff | comparison | revisions
diff -r a7e370d20ab3 -r 8e9e83221c15 MqttMonitor/MqttMonitorWidget.py
--- a/MqttMonitor/MqttMonitorWidget.py	Sat Sep 15 12:01:20 2018 +0200
+++ b/MqttMonitor/MqttMonitorWidget.py	Sat Sep 15 12:12:01 2018 +0200
@@ -18,11 +18,11 @@
 import collections
 import copy
 
-from PyQt5.QtCore import pyqtSlot, Qt, QTimer
+from PyQt5.QtCore import pyqtSlot, Qt, QTimer, QFileInfo
 from PyQt5.QtGui import QFont, QTextCursor, QBrush
 from PyQt5.QtWidgets import QWidget, QDialog
 
-from E5Gui import E5MessageBox
+from E5Gui import E5MessageBox, E5FileDialog
 from E5Gui.E5PathPicker import E5PathPickerModes
 
 from .Ui_MqttMonitorWidget import Ui_MqttMonitorWidget
@@ -75,7 +75,6 @@
         
         # TODO: Messages Edit improvements:
         #   1. add capability to search
-        #   2. add capability to save contents to a file
         
         for logLevel in (MqttClient.LogDisabled,
                          MqttClient.LogDebug,
@@ -90,7 +89,6 @@
         
         # TODO: Log Edit improvements:
         #   1. add capability to search
-        #   2. add configuration capability for colors
         
         self.__logMessagesBackgrounds = {
             MqttClient.LogDebug: QBrush(Qt.white),
@@ -555,7 +553,7 @@
                 f = open(payloadFile, "rb")
                 payloadStr = f.read()
                 f.close()
-            except (IOError, OSError) as err:
+            except EnvironmentError as err:
                 E5MessageBox.critical(
                     self,
                     self.tr("Read Payload from File"),
@@ -619,6 +617,120 @@
                 # successfully sent
                 self.__setBrokerStatusSubscribed(True)
     
+    @pyqtSlot(int)
+    def on_messagesEdit_blockCountChanged(self, newBlockCount):
+        """
+        Private slot handling changes of received messages.
+        
+        @param newBlockCount (ignored)
+        @type int
+        """
+        enable = not self.messagesEdit.document().isEmpty()
+        self.saveMessagesButton.setEnabled(enable)
+        self.clearMessagesButton.setEnabled(enable)
+    
+    @pyqtSlot()
+    def on_saveMessagesButton_clicked(self):
+        """
+        Private slot to save the received messages.
+        """
+        fn, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
+            self,
+            self.tr("Save Messages"),
+            "",
+            self.tr("Messages Files (*.txt);;All Files (*)"),
+            "",
+            E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
+        
+        if fn:
+            if fn.endswith("."):
+                fn = fn[:-1]
+            
+            ext = QFileInfo(fn).suffix()
+            if not ext:
+                ex = selectedFilter.split("(*")[1].split(")")[0]
+                if ex:
+                    fn += ex
+            if QFileInfo(fn).exists():
+                res = E5MessageBox.yesNo(
+                    self,
+                    self.tr("Save Messages"),
+                    self.tr("<p>The file <b>{0}</b> already exists."
+                            " Overwrite it?</p>").format(fn),
+                    icon=E5MessageBox.Warning)
+                if not res:
+                    return
+            
+            fn = Utilities.toNativeSeparators(fn)
+            try:
+                f = open(fn, "w")
+                f.write(self.messagesEdit.toPlainText())
+                f.close()
+            except EnvironmentError as err:
+                E5MessageBox.critical(
+                    self,
+                    self.tr("Save Messages"),
+                    self.tr("""<p>The file <b>{0}</b> could not be written."""
+                            """</p><p>Reason: {1}</p>""").format(
+                        fn, str(err)))
+    
+    @pyqtSlot(int)
+    def on_logEdit_blockCountChanged(self, newBlockCount):
+        """
+        Private slot handling changes of received messages.
+        
+        @param newBlockCount (ignored)
+        @type int
+        """
+        enable = not self.logEdit.document().isEmpty()
+        self.saveLogMessagesButton.setEnabled(enable)
+        self.clearLogMessagesButton.setEnabled(enable)
+    
+    @pyqtSlot()
+    def on_saveLogMessagesButton_clicked(self):
+        """
+        Private slot to save the log messages.
+        """
+        fn, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
+            self,
+            self.tr("Save Log Messages"),
+            "",
+            self.tr("Log Files (*.log);;All Files (*)"),
+            "",
+            E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
+        
+        if fn:
+            if fn.endswith("."):
+                fn = fn[:-1]
+            
+            ext = QFileInfo(fn).suffix()
+            if not ext:
+                ex = selectedFilter.split("(*")[1].split(")")[0]
+                if ex:
+                    fn += ex
+            if QFileInfo(fn).exists():
+                res = E5MessageBox.yesNo(
+                    self,
+                    self.tr("Save Log Messages"),
+                    self.tr("<p>The file <b>{0}</b> already exists."
+                            " Overwrite it?</p>").format(fn),
+                    icon=E5MessageBox.Warning)
+                if not res:
+                    return
+            
+            fn = Utilities.toNativeSeparators(fn)
+            try:
+                f = open(fn, "w")
+                f.write(self.logEdit.toPlainText())
+                f.close()
+            except EnvironmentError as err:
+                E5MessageBox.critical(
+                    self,
+                    self.tr("Save Log Messages"),
+                    self.tr("""<p>The file <b>{0}</b> could not be written."""
+                            """</p><p>Reason: {1}</p>""").format(
+                        fn, str(err)))
+    
     #######################################################################
     ## Utility methods
     #######################################################################
diff -r a7e370d20ab3 -r 8e9e83221c15 MqttMonitor/MqttMonitorWidget.ui
--- a/MqttMonitor/MqttMonitorWidget.ui	Sat Sep 15 12:01:20 2018 +0200
+++ b/MqttMonitor/MqttMonitorWidget.ui	Sat Sep 15 12:12:01 2018 +0200
@@ -320,6 +320,9 @@
             <property name="toolTip">
              <string>Enter the string data to be sent</string>
             </property>
+            <property name="tabChangesFocus">
+             <bool>true</bool>
+            </property>
            </widget>
           </item>
           <item>
@@ -435,6 +438,19 @@
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_4">
          <item>
+          <widget class="QPushButton" name="saveMessagesButton">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="toolTip">
+            <string>Press to save the received messages to a file</string>
+           </property>
+           <property name="text">
+            <string>Save</string>
+           </property>
+          </widget>
+         </item>
+         <item>
           <spacer name="horizontalSpacer">
            <property name="orientation">
             <enum>Qt::Horizontal</enum>
@@ -448,7 +464,10 @@
           </spacer>
          </item>
          <item>
-          <widget class="QPushButton" name="messagesClearButton">
+          <widget class="QPushButton" name="clearMessagesButton">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
            <property name="toolTip">
             <string>Press to clear the list of received messages</string>
            </property>
@@ -519,8 +538,8 @@
            <rect>
             <x>0</x>
             <y>0</y>
-            <width>344</width>
-            <height>840</height>
+            <width>339</width>
+            <height>670</height>
            </rect>
           </property>
           <layout class="QFormLayout" name="formLayout">
@@ -1285,6 +1304,19 @@
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_16">
          <item>
+          <widget class="QPushButton" name="saveLogMessagesButton">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="toolTip">
+            <string>Press to save the received log messages to a file</string>
+           </property>
+           <property name="text">
+            <string>Save</string>
+           </property>
+          </widget>
+         </item>
+         <item>
           <spacer name="horizontalSpacer_4">
            <property name="orientation">
             <enum>Qt::Horizontal</enum>
@@ -1298,7 +1330,10 @@
           </spacer>
          </item>
          <item>
-          <widget class="QPushButton" name="logClearButton">
+          <widget class="QPushButton" name="clearLogMessagesButton">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
            <property name="toolTip">
             <string>Press to clear the list of received log messages</string>
            </property>
@@ -1315,7 +1350,7 @@
           <string>Select to scroll to the most recently received log message</string>
          </property>
          <property name="text">
-          <string>Follow received messages</string>
+          <string>Follow received log messages</string>
          </property>
          <property name="checked">
           <bool>true</bool>
@@ -1368,19 +1403,21 @@
   <tabstop>publishButton</tabstop>
   <tabstop>clearPublishCheckBox</tabstop>
   <tabstop>messagesEdit</tabstop>
-  <tabstop>messagesClearButton</tabstop>
+  <tabstop>saveMessagesButton</tabstop>
+  <tabstop>clearMessagesButton</tabstop>
   <tabstop>followMessagesCheckBox</tabstop>
   <tabstop>brokerStatusButton</tabstop>
   <tabstop>scrollArea</tabstop>
   <tabstop>logLevelComboBox</tabstop>
   <tabstop>logEdit</tabstop>
-  <tabstop>logClearButton</tabstop>
+  <tabstop>saveLogMessagesButton</tabstop>
+  <tabstop>clearLogMessagesButton</tabstop>
   <tabstop>followLogMessagesCheckBox</tabstop>
  </tabstops>
  <resources/>
  <connections>
   <connection>
-   <sender>messagesClearButton</sender>
+   <sender>clearMessagesButton</sender>
    <signal>clicked()</signal>
    <receiver>messagesEdit</receiver>
    <slot>clear()</slot>
@@ -1412,7 +1449,7 @@
    </hints>
   </connection>
   <connection>
-   <sender>logClearButton</sender>
+   <sender>clearLogMessagesButton</sender>
    <signal>clicked()</signal>
    <receiver>logEdit</receiver>
    <slot>clear()</slot>

eric ide

mercurial