PluginMqttMonitor.py

branch
eric7
changeset 123
3d7e63ed4fd1
parent 120
11753aef9237
child 127
8982ef7b7d67
equal deleted inserted replaced
122:28d69b9e1b6a 123:3d7e63ed4fd1
24 # Start-Of-Header 24 # Start-Of-Header
25 name = "MQTT Monitor Plugin" 25 name = "MQTT Monitor Plugin"
26 author = "Detlev Offenbach <detlev@die-offenbachs.de>" 26 author = "Detlev Offenbach <detlev@die-offenbachs.de>"
27 autoactivate = True 27 autoactivate = True
28 deactivateable = True 28 deactivateable = True
29 version = "10.2.1" 29 version = "10.2.2"
30 className = "MqttMonitorPlugin" 30 className = "MqttMonitorPlugin"
31 packageName = "MqttMonitor" 31 packageName = "MqttMonitor"
32 shortDescription = "Plug-in implementing a tool to connect to a MQTT broker" 32 shortDescription = "Plug-in implementing a tool to connect to a MQTT broker"
33 longDescription = ( 33 longDescription = (
34 """Plug-in implementing a tool to connect to a MQTT broker, subscribe""" 34 """Plug-in implementing a tool to connect to a MQTT broker, subscribe"""
48 48
49 49
50 def createMqttPage(configDlg): 50 def createMqttPage(configDlg):
51 """ 51 """
52 Module function to create the autocompletion configuration page. 52 Module function to create the autocompletion configuration page.
53 53
54 @param configDlg reference to the configuration dialog 54 @param configDlg reference to the configuration dialog
55 @type ConfigurationWidget 55 @type ConfigurationWidget
56 @return reference to the configuration page 56 @return reference to the configuration page
57 @rtype AutoCompletionRopePage 57 @rtype AutoCompletionRopePage
58 """ 58 """
59 global mqttPluginObject 59 global mqttPluginObject
60 from MqttMonitor.ConfigurationPage.MqttPage import MqttPage 60 from MqttMonitor.ConfigurationPage.MqttPage import MqttPage
61 61
62 page = MqttPage(mqttPluginObject) 62 page = MqttPage(mqttPluginObject)
63 return page 63 return page
64 64
65 65
66 def getConfigData(): 66 def getConfigData():
67 """ 67 """
68 Module function returning data as required by the configuration dialog. 68 Module function returning data as required by the configuration dialog.
69 69
70 @return dictionary containing the relevant data 70 @return dictionary containing the relevant data
71 @rtype dict 71 @rtype dict
72 """ 72 """
73 usesDarkPalette = ericApp().usesDarkPalette() 73 usesDarkPalette = ericApp().usesDarkPalette()
74 iconSuffix = "dark" if usesDarkPalette else "light" 74 iconSuffix = "dark" if usesDarkPalette else "light"
75 75
76 return { 76 return {
77 "mqttPage": [ 77 "mqttPage": [
78 QCoreApplication.translate("MqttMonitorPlugin", "MQTT Monitor"), 78 QCoreApplication.translate("MqttMonitorPlugin", "MQTT Monitor"),
79 os.path.join( 79 os.path.join("MqttMonitor", "icons", "mqtt22-{0}".format(iconSuffix)),
80 "MqttMonitor", "icons", "mqtt22-{0}".format(iconSuffix)), 80 createMqttPage,
81 createMqttPage, None, None], 81 None,
82 None,
83 ],
82 } 84 }
83 85
84 86
85 def exeDisplayData(): 87 def exeDisplayData():
86 """ 88 """
87 Module function to support the display of some executable info. 89 Module function to support the display of some executable info.
88 90
89 @return dictionary containing the data to query the presence of 91 @return dictionary containing the data to query the presence of
90 the executable 92 the executable
91 @rtype dict 93 @rtype dict
92 """ 94 """
93 try: 95 try:
94 import paho.mqtt 96 import paho.mqtt
97
95 version = paho.mqtt.__version__ 98 version = paho.mqtt.__version__
96 except ImportError: 99 except ImportError:
97 version = QCoreApplication.translate( 100 version = QCoreApplication.translate(
98 "MqttMonitorPlugin", "(package not available)") 101 "MqttMonitorPlugin", "(package not available)"
99 102 )
103
100 return { 104 return {
101 "programEntry": False, 105 "programEntry": False,
102 "header": QCoreApplication.translate("MqttMonitorPlugin", "MQTT"), 106 "header": QCoreApplication.translate("MqttMonitorPlugin", "MQTT"),
103 "text": QCoreApplication.translate("MqttMonitorPlugin", "paho-mqtt"), 107 "text": QCoreApplication.translate("MqttMonitorPlugin", "paho-mqtt"),
104 "version": version, 108 "version": version,
114 118
115 class MqttMonitorPlugin(QObject): 119 class MqttMonitorPlugin(QObject):
116 """ 120 """
117 Class implementing the MQTT Monitor plug-in. 121 Class implementing the MQTT Monitor plug-in.
118 """ 122 """
123
119 PreferencesKey = "MqttMonitor" 124 PreferencesKey = "MqttMonitor"
120 125
121 def __init__(self, ui): 126 def __init__(self, ui):
122 """ 127 """
123 Constructor 128 Constructor
124 129
125 @param ui reference to the user interface object 130 @param ui reference to the user interface object
126 @type UI.UserInterface 131 @type UI.UserInterface
127 """ 132 """
128 super().__init__(ui) 133 super().__init__(ui)
129 self.__ui = ui 134 self.__ui = ui
130 self.__initialize() 135 self.__initialize()
131 136
132 self.__defaults = { 137 self.__defaults = {
133 "RecentBrokersWithPort": "[]", # JSON formatted empty list 138 "RecentBrokersWithPort": "[]", # JSON formatted empty list
134 "BrokerProfiles": "{}", # JSON formatted empty dict 139 "BrokerProfiles": "{}", # JSON formatted empty dict
135 # __IGNORE_WARNING_M613__ 140 # __IGNORE_WARNING_M613__
136 "MostRecentProfile": "", # most recently used profile 141 "MostRecentProfile": "", # most recently used profile
137 "PublishProperties": "{}", # JSON formatted empty dict 142 "PublishProperties": "{}", # JSON formatted empty dict
138 # __IGNORE_WARNING_M613__ 143 # __IGNORE_WARNING_M613__
139 "SubscribeProperties": "{}", # JSON formatted empty dict 144 "SubscribeProperties": "{}", # JSON formatted empty dict
140 # __IGNORE_WARNING_M613__ 145 # __IGNORE_WARNING_M613__
141 "UnsubscribeProperties": "{}", # JSON formatted empty dict 146 "UnsubscribeProperties": "{}", # JSON formatted empty dict
142 # __IGNORE_WARNING_M613__ 147 # __IGNORE_WARNING_M613__
143 "DefaultProtocol": MqttProtocols.MQTTv311, 148 "DefaultProtocol": MqttProtocols.MQTTv311,
144 "RecentBrokersNumber": 20, 149 "RecentBrokersNumber": 20,
145 "RecentTopicsNumber": 20, 150 "RecentTopicsNumber": 20,
146 "RecentTopics": "[]", # JSON formatted empty list 151 "RecentTopics": "[]", # JSON formatted empty list
147 } 152 }
148 153
149 self.__translator = None 154 self.__translator = None
150 self.__loadTranslator() 155 self.__loadTranslator()
151 156
152 def __initialize(self): 157 def __initialize(self):
153 """ 158 """
154 Private slot to (re)initialize the plugin. 159 Private slot to (re)initialize the plugin.
155 """ 160 """
156 self.__widget = None 161 self.__widget = None
157 162
158 def activate(self): 163 def activate(self):
159 """ 164 """
160 Public method to activate this plug-in. 165 Public method to activate this plug-in.
161 166
162 @return tuple of None and activation status 167 @return tuple of None and activation status
163 @rtype tuple of (None, bool) 168 @rtype tuple of (None, bool)
164 """ 169 """
165 global error, mqttPluginObject 170 global error, mqttPluginObject
166 error = "" # clear previous error 171 error = "" # clear previous error
167 mqttPluginObject = self 172 mqttPluginObject = self
168 173
169 try: 174 try:
170 import paho.mqtt # __IGNORE_WARNING__ 175 import paho.mqtt # __IGNORE_WARNING__
171 except ImportError: 176 except ImportError:
172 error = self.tr("The 'paho-mqtt' package is not available.") 177 error = self.tr("The 'paho-mqtt' package is not available.")
173 return None, False 178 return None, False
174 179
175 from MqttMonitor.MqttMonitorWidget import MqttMonitorWidget 180 from MqttMonitor.MqttMonitorWidget import MqttMonitorWidget
176 181
177 usesDarkPalette = ericApp().usesDarkPalette() 182 usesDarkPalette = ericApp().usesDarkPalette()
178 iconSuffix = "dark" if usesDarkPalette else "light" 183 iconSuffix = "dark" if usesDarkPalette else "light"
179 184
180 self.__widget = MqttMonitorWidget(self, usesDarkPalette) 185 self.__widget = MqttMonitorWidget(self, usesDarkPalette)
181 iconName = ( 186 iconName = (
182 "sbMqttMonitor96" 187 "sbMqttMonitor96"
183 if self.__ui.getLayoutType() == "Sidebars" else 188 if self.__ui.getLayoutType() == "Sidebars"
184 "mqtt22-{0}".format(iconSuffix) 189 else "mqtt22-{0}".format(iconSuffix)
185 ) 190 )
186 self.__ui.addSideWidget( 191 self.__ui.addSideWidget(
187 self.__ui.RightSide, self.__widget, 192 self.__ui.RightSide,
188 UI.PixmapCache.getIcon( 193 self.__widget,
189 os.path.join("MqttMonitor", "icons", iconName)), 194 UI.PixmapCache.getIcon(os.path.join("MqttMonitor", "icons", iconName)),
190 self.tr("MQTT Monitor")) 195 self.tr("MQTT Monitor"),
191 196 )
197
192 self.__activateAct = EricAction( 198 self.__activateAct = EricAction(
193 self.tr('MQTT Monitor'), 199 self.tr("MQTT Monitor"),
194 self.tr('M&QTT Monitor'), 200 self.tr("M&QTT Monitor"),
195 QKeySequence(self.tr("Alt+Shift+Q")), 201 QKeySequence(self.tr("Alt+Shift+Q")),
196 0, self, 202 0,
197 'mqtt_monitor_activate') 203 self,
198 self.__activateAct.setStatusTip(self.tr( 204 "mqtt_monitor_activate",
199 "Switch the input focus to the MQTT Monitor window.")) 205 )
200 self.__activateAct.setWhatsThis(self.tr( 206 self.__activateAct.setStatusTip(
201 """<b>Activate MQTT Monitor</b>""" 207 self.tr("Switch the input focus to the MQTT Monitor window.")
202 """<p>This switches the input focus to the MQTT Monitor""" 208 )
203 """ window.</p>""" 209 self.__activateAct.setWhatsThis(
204 )) 210 self.tr(
211 """<b>Activate MQTT Monitor</b>"""
212 """<p>This switches the input focus to the MQTT Monitor"""
213 """ window.</p>"""
214 )
215 )
205 self.__activateAct.triggered.connect(self.__activateWidget) 216 self.__activateAct.triggered.connect(self.__activateWidget)
206 217
207 self.__ui.addEricActions([self.__activateAct], 'ui') 218 self.__ui.addEricActions([self.__activateAct], "ui")
208 menu = self.__ui.getMenu("subwindow") 219 menu = self.__ui.getMenu("subwindow")
209 menu.addAction(self.__activateAct) 220 menu.addAction(self.__activateAct)
210 221
211 return None, True 222 return None, True
212 223
213 def deactivate(self): 224 def deactivate(self):
214 """ 225 """
215 Public method to deactivate this plug-in. 226 Public method to deactivate this plug-in.
216 """ 227 """
217 menu = self.__ui.getMenu("subwindow") 228 menu = self.__ui.getMenu("subwindow")
218 menu.removeAction(self.__activateAct) 229 menu.removeAction(self.__activateAct)
219 self.__ui.removeEricActions([self.__activateAct], 'ui') 230 self.__ui.removeEricActions([self.__activateAct], "ui")
220 self.__ui.removeSideWidget(self.__widget) 231 self.__ui.removeSideWidget(self.__widget)
221 232
222 self.__initialize() 233 self.__initialize()
223 234
224 def __loadTranslator(self): 235 def __loadTranslator(self):
225 """ 236 """
226 Private method to load the translation file. 237 Private method to load the translation file.
227 """ 238 """
228 if self.__ui is not None: 239 if self.__ui is not None:
229 loc = self.__ui.getLocale() 240 loc = self.__ui.getLocale()
230 if loc and loc != "C": 241 if loc and loc != "C":
231 locale_dir = os.path.join( 242 locale_dir = os.path.join(
232 os.path.dirname(__file__), "MqttMonitor", "i18n") 243 os.path.dirname(__file__), "MqttMonitor", "i18n"
244 )
233 translation = "mqttmonitor_{0}".format(loc) 245 translation = "mqttmonitor_{0}".format(loc)
234 translator = QTranslator(None) 246 translator = QTranslator(None)
235 loaded = translator.load(translation, locale_dir) 247 loaded = translator.load(translation, locale_dir)
236 if loaded: 248 if loaded:
237 self.__translator = translator 249 self.__translator = translator
238 ericApp().installTranslator(self.__translator) 250 ericApp().installTranslator(self.__translator)
239 else: 251 else:
240 print("Warning: translation file '{0}' could not be" 252 print(
241 " loaded.".format(translation)) 253 "Warning: translation file '{0}' could not be"
254 " loaded.".format(translation)
255 )
242 print("Using default.") 256 print("Using default.")
243 257
244 def __activateWidget(self): 258 def __activateWidget(self):
245 """ 259 """
246 Private slot to handle the activation of the MQTT Monitor. 260 Private slot to handle the activation of the MQTT Monitor.
247 """ 261 """
248 uiLayoutType = self.__ui.getLayoutType() 262 uiLayoutType = self.__ui.getLayoutType()
249 263
250 if uiLayoutType == "Toolboxes": 264 if uiLayoutType == "Toolboxes":
251 self.__ui.rToolboxDock.show() 265 self.__ui.rToolboxDock.show()
252 self.__ui.rToolbox.setCurrentWidget(self.__widget) 266 self.__ui.rToolbox.setCurrentWidget(self.__widget)
253 elif uiLayoutType == "Sidebars": 267 elif uiLayoutType == "Sidebars":
254 self.__ui.rightSidebar.show() 268 self.__ui.rightSidebar.show()
255 self.__ui.rightSidebar.setCurrentWidget(self.__widget) 269 self.__ui.rightSidebar.setCurrentWidget(self.__widget)
256 else: 270 else:
257 self.__widget.show() 271 self.__widget.show()
258 self.__widget.setFocus(Qt.FocusReason.ActiveWindowFocusReason) 272 self.__widget.setFocus(Qt.FocusReason.ActiveWindowFocusReason)
259 273
260 def getPreferences(self, key): 274 def getPreferences(self, key):
261 """ 275 """
262 Public method to retrieve the various settings. 276 Public method to retrieve the various settings.
263 277
264 @param key key of the setting 278 @param key key of the setting
265 @type str 279 @type str
266 @return value of the requested setting 280 @return value of the requested setting
267 @rtype Any 281 @rtype Any
268 """ 282 """
269 if key in ("RecentBrokersWithPort", "BrokerProfiles", 283 if key in (
270 "SubscribeProperties", "UnsubscribeProperties", 284 "RecentBrokersWithPort",
271 "PublishProperties", "RecentTopics"): 285 "BrokerProfiles",
272 return json.loads(Preferences.Prefs.settings.value( 286 "SubscribeProperties",
273 self.PreferencesKey + "/" + key, self.__defaults[key])) 287 "UnsubscribeProperties",
274 elif key in ("DefaultProtocol", ): 288 "PublishProperties",
275 return MqttProtocols(int(Preferences.Prefs.settings.value( 289 "RecentTopics",
276 self.PreferencesKey + "/" + key, self.__defaults[key]))) 290 ):
277 elif key in ("DefaultProtocol", "RecentBrokersNumber", 291 return json.loads(
278 "RecentTopicsNumber"): 292 Preferences.Prefs.settings.value(
279 return int(Preferences.Prefs.settings.value( 293 self.PreferencesKey + "/" + key, self.__defaults[key]
280 self.PreferencesKey + "/" + key, self.__defaults[key])) 294 )
295 )
296 elif key in ("DefaultProtocol",):
297 return MqttProtocols(
298 int(
299 Preferences.Prefs.settings.value(
300 self.PreferencesKey + "/" + key, self.__defaults[key]
301 )
302 )
303 )
304 elif key in ("DefaultProtocol", "RecentBrokersNumber", "RecentTopicsNumber"):
305 return int(
306 Preferences.Prefs.settings.value(
307 self.PreferencesKey + "/" + key, self.__defaults[key]
308 )
309 )
281 else: 310 else:
282 return Preferences.Prefs.settings.value( 311 return Preferences.Prefs.settings.value(
283 self.PreferencesKey + "/" + key, self.__defaults[key]) 312 self.PreferencesKey + "/" + key, self.__defaults[key]
284 313 )
314
285 def setPreferences(self, key, value): 315 def setPreferences(self, key, value):
286 """ 316 """
287 Public method to store the various settings. 317 Public method to store the various settings.
288 318
289 @param key key of the setting to be set 319 @param key key of the setting to be set
290 @type str 320 @type str
291 @param value value to be set 321 @param value value to be set
292 @type Any 322 @type Any
293 """ 323 """
294 if key in ("RecentBrokersWithPort", "BrokerProfiles", 324 if key in (
295 "SubscribeProperties", "UnsubscribeProperties", 325 "RecentBrokersWithPort",
296 "PublishProperties", "RecentTopics"): 326 "BrokerProfiles",
327 "SubscribeProperties",
328 "UnsubscribeProperties",
329 "PublishProperties",
330 "RecentTopics",
331 ):
297 Preferences.Prefs.settings.setValue( 332 Preferences.Prefs.settings.setValue(
298 self.PreferencesKey + "/" + key, json.dumps(value)) 333 self.PreferencesKey + "/" + key, json.dumps(value)
299 elif key in ("DefaultProtocol", ): 334 )
335 elif key in ("DefaultProtocol",):
300 Preferences.Prefs.settings.setValue( 336 Preferences.Prefs.settings.setValue(
301 self.PreferencesKey + "/" + key, int(value)) 337 self.PreferencesKey + "/" + key, int(value)
338 )
302 else: 339 else:
303 Preferences.Prefs.settings.setValue( 340 Preferences.Prefs.settings.setValue(self.PreferencesKey + "/" + key, value)
304 self.PreferencesKey + "/" + key, value)
305 341
306 342
307 def installDependencies(pipInstall): 343 def installDependencies(pipInstall):
308 """ 344 """
309 Function to install dependencies of this plug-in. 345 Function to install dependencies of this plug-in.
310 346
311 @param pipInstall function to be called with a list of package names. 347 @param pipInstall function to be called with a list of package names.
312 @type function 348 @type function
313 """ 349 """
314 try: 350 try:
315 import paho.mqtt # __IGNORE_WARNING__ 351 import paho.mqtt # __IGNORE_WARNING__
316 except ImportError: 352 except ImportError:
317 pipInstall(["paho-mqtt"]) 353 pipInstall(["paho-mqtt"])
318 354
355
319 # 356 #
320 # eflag: noqa = M801 357 # eflag: noqa = M801

eric ide

mercurial