def createEmptyLayer(self):
        try:
            telemetryLayer.instance().checkBrokerConfig()
        except BrokerNotSynced:
            Log.progress("Please save any broker configurations first")
        except BrokersNotDefined:
            Log.progress("Please configure your MQTT Brokers first - see Plugin -> Telemetry Layer -> Configure")
            return

        dlg = layerConfig(self)
        result = dlg.exec_()
        if result == 0:  # object will be garbage collected
            return False

        geomType = 'Point' + '?crs=proj4:' + QgsProject.instance().readEntry("SpatialRefSys", "/ProjectCRSProj4String")[
            0]  # dodana linia - from Menory Layer Module
        broker = dlg.getBroker()
        topicType = dlg.getTopicType()
        layer = QgsVectorLayer(geomType, topicType, 'memory')  # zmieniona linia

        tLayer = self.initLayer(layer, broker, topicType)
        # self._iface.legendInterface().setCurrentLayer(layer)
        Log.debug("telemetrylayermanager - set Current Layer")

        self.rebuildLegend()
        layer.triggerRepaint()
示例#2
0
    def createEmptyLayer(self):
        try:
            telemetryLayer.instance().checkBrokerConfig()
        except BrokerNotSynced:
            Log.progress("Please save any broker configurations first")
        except BrokersNotDefined:
            Log.progress(
                "Please configure your MQTT Brokers first - see Plugin -> Telemetry Layer -> Configure"
            )
            return

        dlg = layerConfig(self)
        result = dlg.exec_()
        if result == 0:  # object will be garbage collected
            return False

        geomType = 'Point' + '?crs=proj4:' + QgsProject.instance().readEntry(
            "SpatialRefSys", "/ProjectCRSProj4String")[
                0]  # dodana linia - from Menory Layer Module
        broker = dlg.getBroker()
        topicManager = dlg.getTopicManager()
        layer = QgsVectorLayer(geomType, topicManager.name(),
                               'memory')  # zmieniona linia

        tLayer = self.initLayer(layer, broker, topicManager)
        # self._iface.legendInterface().setCurrentLayer(layer)
        # Log.debug("telemetrylayermanager - set Current Layer")

        self.rebuildLegend()
        layer.triggerRepaint()
    def legendDblClicked(self, item):

        model = QgsLayerTreeModel(QgsProject.instance().layerTreeRoot())
        node = model.index2node(item)
        if self._isBrokerGroup(node):
            bid = node.customProperty(TLayer.kBrokerId, -1)
            broker = Brokers.instance().find(bid)
            if broker is not None:
                telemetryLayer.instance().show(broker)
            else:
                # handle missing broker
                pass
示例#4
0
    def legendDblClicked(self, item):

        model = QgsLayerTreeModel(QgsProject.instance().layerTreeRoot())
        node = model.index2node(item)
        if self._isBrokerGroup(node):
            bid = node.customProperty(TLayer.kBrokerId, -1)
            broker = Brokers.instance().find(bid)
            if broker is not None:
                telemetryLayer.instance().show(broker)
            else:
                # handle missing broker
                pass
示例#5
0
    def applyFeature(self,feature):
        found = False
        if feature.id() > 0 and not feature.id() in self.establishedFeatures:
#            Log.debug("No feature to Apply") # must be an Add
            self._lastFid = feature.id()
            if self._deferredEdit:
                self._deferredEdit = False
                self._deferredTimer = QTimer()
                self._deferredTimer.setSingleShot(True)
                self._deferredTimer.timeout.connect(lambda:telemetryLayer.instance().showEditFeature(self.layer(),feature.id()))
                self._deferredTimer.start(100)
            return
        
        fid = next(iter(self.layer().selectedFeaturesIds()),None)
        if not fid:
            return
            
        feat = next(self.layer().getFeatures(QgsFeatureRequest(fid)), None)

        try:
            fmap = self._layer.dataProvider().fieldNameMap()
            fmax = self._layer.dataProvider().fieldNameIndex("context")

            for key,fieldId in fmap.iteritems():
                if key in ['qos','visible'] or fieldId > fmax:
                #   Log.debug("changing value " + key + " " + str(feat[key]) + " to " + str(feature[key]))
                   self._layer.changeAttributeValue(feat.id(), fieldId, feature[key])
            self._layer.deleteFeature(feature.id())
            self._layer.commitChanges()
            self._layer.deselect(self.layer().selectedFeaturesIds())
            
        except Exception as e:
            Log.debug("Error applying feature " + str(e))
示例#6
0
    def applyFeature(self, feature):
        found = False
        if feature.id() > 0 and not feature.id() in self.establishedFeatures:
            #            Log.debug("No feature to Apply") # must be an Add
            self._lastFid = feature.id()
            if self._deferredEdit:
                self._deferredEdit = False
                self._deferredTimer = QTimer()
                self._deferredTimer.setSingleShot(True)
                self._deferredTimer.timeout.connect(
                    lambda: telemetryLayer.instance().showEditFeature(
                        self.layer(), feature.id()))
                self._deferredTimer.start(100)
            return

        fid = next(iter(self.layer().selectedFeaturesIds()), None)
        if not fid:
            return

        feat = next(self.layer().getFeatures(QgsFeatureRequest(fid)), None)

        try:
            fmap = self._layer.dataProvider().fieldNameMap()
            fmax = self._layer.dataProvider().fieldNameIndex("context")

            for key, fieldId in fmap.iteritems():
                if key in ['qos', 'visible'] or fieldId > fmax:
                    #   Log.debug("changing value " + key + " " + str(feat[key]) + " to " + str(feature[key]))
                    self._layer.changeAttributeValue(feat.id(), fieldId,
                                                     feature[key])
            self._layer.deleteFeature(feature.id())
            self._layer.commitChanges()
            self._layer.deselect(self.layer().selectedFeaturesIds())

        except Exception as e:
            Log.debug("Error applying feature " + str(e))
示例#7
0
    def addFeature(self, fid):
        Log.debug("Add Feature")
        if fid < 0 and not self._fid:
            self._fid = fid
        elif fid >= 0 or fid == self._fid:
            # handle roll back
            #self._fid = None
            return None

        # Look Up broker and topicType

        feat = QgsFeature(fid)
        try:
            telemetryLayer.instance().checkBrokerConfig()
            tlAddFeature = AddFeature(self.topicManager())
            result = tlAddFeature.exec_()
            if result == 0:
                self._layer.deleteFeature(fid)
                self._layer.commitChanges()
                return None

            topic   = tlAddFeature.getTopic()
            visible = tlAddFeature.getVisible()
            qos     = tlAddFeature.getQoS()
            
            self._deferredEdit =  tlAddFeature.getEdit()
            
            attrs = [topic['name'],
                    topic['topic'],
                    qos,
                    topic['topic'],  # gets updated with topic
                    "No updates",
                    int(time.time()),
                    int(time.time()),
                    self.isRunning(),
                    visible,
                    'map']
            
            # merge with custom attributes
            feat.setAttributes(self.topicManager().setAttributes(self._layer,attrs))

            self._layer.updateFeature(feat)
            self._layer.commitChanges()
            self._feat = feat
            
        except BrokerNotSynced:
            Log.progress("Please save any unsaved Broker configurations first")
            self._layer.deleteFeature(fid)
            self._layer.commitChanges()
        except BrokersNotDefined:
            Log.progress("You have no Brokers defined")
            self._layer.deleteFeature(fid)
            self._layer.commitChanges()
        except Exception as e:
            Log.debug(e)
            self._layer.deleteFeature(fid)
            self._layer.commitChanges()
            return None
        finally:
            pass

        return feat
示例#8
0
    def addFeature(self, fid):
        Log.debug("Add Feature")
        if fid < 0 and not self._fid:
            self._fid = fid
        elif fid >= 0 or fid == self._fid:
            # handle roll back
            #self._fid = None
            return None

        # Look Up broker and topicType

        feat = QgsFeature(fid)
        try:
            telemetryLayer.instance().checkBrokerConfig()
            tlAddFeature = AddFeature(self.topicManager())
            result = tlAddFeature.exec_()
            if result == 0:
                self._layer.deleteFeature(fid)
                self._layer.commitChanges()
                return None

            topic = tlAddFeature.getTopic()
            visible = tlAddFeature.getVisible()
            qos = tlAddFeature.getQoS()

            self._deferredEdit = tlAddFeature.getEdit()

            attrs = [
                topic['name'],
                topic['topic'],
                qos,
                topic['topic'],  # gets updated with topic
                "No updates",
                int(time.time()),
                int(time.time()),
                self.isRunning(),
                visible,
                'map'
            ]

            # merge with custom attributes
            feat.setAttributes(self.topicManager().setAttributes(
                self._layer, attrs))

            self._layer.updateFeature(feat)
            self._layer.commitChanges()
            self._feat = feat

        except BrokerNotSynced:
            Log.progress("Please save any unsaved Broker configurations first")
            self._layer.deleteFeature(fid)
            self._layer.commitChanges()
        except BrokersNotDefined:
            Log.progress("You have no Brokers defined")
            self._layer.deleteFeature(fid)
            self._layer.commitChanges()
        except Exception as e:
            Log.debug(e)
            self._layer.deleteFeature(fid)
            self._layer.commitChanges()
            return None
        finally:
            pass

        return feat
class TelemetryLayerPlugin(QObject):
    """
    Plugin Class - providing hook into QGIS core; starting point for setup and teardown;
    including creation of menu/icon actions.
    
    Todo: Alternative host name selection
    Username password for MQTT Broker
    """
    def __init__(self, iface):
        # Save reference to the QGIS interface
        super(TelemetryLayerPlugin, self).__init__(iface)
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        sys.path.append(os.path.join(self.plugin_dir, "topicmanagers"))

        self.layerManager = None
        self.installed = False
        self.configureDlg = None
        self.plugin_basename = str(os.path.basename(self.plugin_dir))
        self.state = "Init"

        # Initialise Settings and Log handlers
        try:
            Settings(self)
            Log(self)
            Log.debug("Loading Topic Managers")
            TopicManagerFactory(iface)
            Log.debug("Topic Managers Loaded")
            Brokers(os.path.join(self.plugin_dir, 'data'))
            Log.debug("Brokers Loaded")

        except Exception as e:
            Log.critical("Error on Plugin initialization " + str(e))
            exc_type, exc_value, exc_traceback = sys.exc_info()
            Log.debug(
                repr(
                    traceback.format_exception(exc_type, exc_value,
                                               exc_traceback)))

        # initialize locale
        self.translator = QTranslator()

        if QSettings().value("locale/userLocale"):
            locale = QSettings().value("locale/userLocale")[0:2]
            localePath = os.path.join(self.plugin_dir, 'i18n',
                                      'telemetrylayer_{}.qm'.format(locale))
            if os.path.exists(localePath):
                self.translator.load(localePath)

        if qVersion() > '4.3.3':
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):

        # Create action that will start plugin configuration
        self.aboutA = QAction(
            QIcon(":/plugins/" + self.plugin_basename + "/icons/agsense.png"),
            "About", self.iface.mainWindow())  # Replace or Add About
        # connect the action to the run method
        self.aboutA.triggered.connect(self.about)

        self.configureA = QAction(
            QIcon(":/plugins/" + self.plugin_basename + "/icons/icon.png"),
            "Configure", self.iface.mainWindow())  # Replace or Add About
        # connect the action to the run method
        self.configureA.triggered.connect(self.configure)

        # From New Memory Layer plugin
        lMenuTitle = 'New Telemetry Layer...'

        self.newLayerA = QAction(
            QIcon(":/plugins/" + self.plugin_basename + "/icons/icon.png"),
            lMenuTitle, self.iface.mainWindow())
        QObject.connect(self.newLayerA, SIGNAL("triggered()"),
                        self.createLayer)
        self.iface.newLayerMenu().addAction(self.newLayerA)  # API >= 1.9
        self.iface.registerMainWindowAction(self.newLayerA, "Shift+Ctrl+T")

        try:
            Log.debug("Loading Layer Manager")
            self.layerManager = layerManager(self)
            Log.debug("Layer Manager Loaded")
            self.telemetryLayer = TelemetryLayer(self)
            Log.debug(Settings.getMeta("name") + ": Loaded")
            self.iface.projectRead.connect(self.layerManager.rebuildLegend)
            self.iface.newProjectCreated.connect(
                self.layerManager.rebuildLegend)
            Brokers.instance().brokersLoaded.connect(
                self.layerManager.brokersLoaded)

            #Log.debug(TelemetryLayer.instance()._layerManager.getTLayers(False).iteritems())
        except Exception as e:
            Log.critical(
                Settings.getMeta("name") +
                ": There was a problem loading the layer manager")
            exc_type, exc_value, exc_traceback = sys.exc_info()
            Log.debug(
                repr(
                    traceback.format_exception(exc_type, exc_value,
                                               exc_traceback)))

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.aboutA)
        self.iface.addToolBarIcon(self.configureA)
        self.iface.addPluginToMenu(u"&Telemetry Layer", self.aboutA)
        self.iface.addPluginToMenu(u"&Telemetry Layer", self.configureA)
        self.installed = True

        mw = self.iface.mainWindow()

    # lgd.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu);

    def unload(self):
        # Remove the plugin menu item and icon
        if not self.installed:
            return

        try:
            self.runTeardown()

            self.iface.removePluginMenu(u"&Telemetry Layer", self.aboutA)
            self.iface.removePluginMenu(u"&Telemetry Layer", self.configureA)
            self.iface.removeToolBarIcon(self.aboutA)
            self.iface.removeToolBarIcon(self.configureA)
            self.iface.newLayerMenu().removeAction(
                self.newLayerA)  # API >= 1.9
            self.iface.projectRead.disconnect(self.layerManager.rebuildLegend)
            self.iface.newProjectCreated.disconnect(
                self.layerManager.rebuildLegend)

            #Brokers.instance().brokersLoaded.disconnect(self.layerManager.brokersLoaded)
        except Exception as e:
            Log.debug(e)
            pass
        finally:
            if self.layerManager:
                self.layerManager.deleteLater()
            if self.telemetryLayer:
                self.telemetryLayer.deleteLater()
            if Brokers:
                Brokers.instance().deleteLater()
            TopicManagerFactory.tearDown()
            gc.collect()
            Log.debug("Plugin unloaded")

    def runTeardown(self):
        try:
            self.layerManager.tearDown()
            self.telemetryLayer.tearDown()

        except Exception as e:
            Log.debug(e)
            pass

    def about(self):

        webbrowser.open(Settings.getMeta("homepage"))

    #        for broker in Brokers.instance().list():
    #            Log.debug(broker.topicManager())
    #        return

    def configure(self):
        self.telemetryLayer.instance().show()

    def createLayer(self):
        if self.layerManager is not None:
            self.layerManager.createEmptyLayer()

    def freshInstall(self):
        version = Settings.get('version')
        current = Settings.getMeta('version')
        return current != version
class TelemetryLayerPlugin(QObject):
    """
    Plugin Class - providing hook into QGIS core; starting point for setup and teardown;
    including creation of menu/icon actions.
    
    Todo: Alternative host name selection
    Username password for MQTT Broker
    """

  
    def __init__(self, iface):
        # Save reference to the QGIS interface
        super(TelemetryLayerPlugin, self).__init__(iface)
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        sys.path.append(os.path.join(self.plugin_dir, "topicmanagers"))
        
        self.layerManager = None
        self.installed = False
        self.configureDlg = None
        self.plugin_basename = str(os.path.basename(self.plugin_dir))
        self.state="Init"

        # Initialise Settings and Log handlers
        try:
            Settings(self)
            Log(self)
            Log.debug("Loading Topic Managers")
            TopicManagerFactory(iface)
            Log.debug("Topic Managers Loaded")
            Brokers(os.path.join(self.plugin_dir, 'data'))
            Log.debug("Brokers Loaded")


        except Exception as e:
            Log.critical("Error on Plugin initialization " + str(e))
            exc_type, exc_value, exc_traceback = sys.exc_info()
            Log.debug(repr(traceback.format_exception(exc_type, exc_value,
                                                      exc_traceback)))

        # initialize locale
        self.translator = QTranslator()

        if QSettings().value("locale/userLocale"):
            locale = QSettings().value("locale/userLocale")[0:2]
            localePath = os.path.join(self.plugin_dir, 'i18n', 'telemetrylayer_{}.qm'.format(locale))
            if os.path.exists(localePath):
                self.translator.load(localePath)

        if qVersion() > '4.3.3':
            QCoreApplication.installTranslator(self.translator)


    def initGui(self):
        # Tree Widget test
        Log.debug("initGUI")

        # Create action that will start plugin configuration
        self.aboutA = QAction(
            QIcon(":/plugins/" + self.plugin_basename + "/icons/agsense.png"),
            "About", self.iface.mainWindow())  # Replace or Add About
        # connect the action to the run method
        self.aboutA.triggered.connect(self.about)

        self.configureA = QAction(
            QIcon(":/plugins/" + self.plugin_basename + "/icons/icon.png"),
            "Configure", self.iface.mainWindow())  # Replace or Add About
        # connect the action to the run method
        self.configureA.triggered.connect(self.configure)


        # From New Memory Layer plugin
        lMenuTitle = 'New Telemetry Layer...'

        self.newLayerA = QAction(
            QIcon(":/plugins/" + self.plugin_basename + "/icons/icon.png"),
            lMenuTitle, self.iface.mainWindow())
        QObject.connect(self.newLayerA, SIGNAL("triggered()"), self.createLayer)
        self.iface.newLayerMenu().addAction(self.newLayerA)  # API >= 1.9
        self.iface.registerMainWindowAction(self.newLayerA, "Shift+Ctrl+T")

        try:
            Log.debug("Loading Layer Manager")
            self.layerManager = layerManager(self)
            Log.debug("Layer Manager Loaded")
            self.telemetryLayer = TelemetryLayer(self)
            Log.debug(Settings.getMeta("name") + ": Loaded")
            self.iface.projectRead.connect(self.layerManager.rebuildLegend)
            self.iface.newProjectCreated.connect(self.layerManager.rebuildLegend)
            Brokers.instance().brokersLoaded.connect(self.layerManager.brokersLoaded)
        except Exception as e:
            Log.critical(Settings.getMeta("name") + ": There was a problem loading the layer manager")
            exc_type, exc_value, exc_traceback = sys.exc_info()
            Log.debug(repr(traceback.format_exception(exc_type, exc_value,
                                                      exc_traceback)))

        
        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.aboutA)
        self.iface.addToolBarIcon(self.configureA)
        self.iface.addPluginToMenu(u"&Telemetry Layer", self.aboutA)
        self.iface.addPluginToMenu(u"&Telemetry Layer", self.configureA)
        self.installed = True

        mw = self.iface.mainWindow()

    # lgd.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu);


    def unload(self):
        # Remove the plugin menu item and icon
        if not self.installed:
            return

        try:
            self.runTeardown()

            self.iface.removePluginMenu(u"&Telemetry Layer", self.aboutA)
            self.iface.removePluginMenu(u"&Telemetry Layer", self.configureA)
            self.iface.removeToolBarIcon(self.aboutA)
            self.iface.removeToolBarIcon(self.configureA)
            self.iface.newLayerMenu().removeAction(self.newLayerA)  # API >= 1.9
            self.iface.projectRead.disconnect(self.layerManager.rebuildLegend)
            self.iface.newProjectCreated.disconnect(self.layerManager.rebuildLegend)

            TopicManagerFactory.unregisterAll()
            #Brokers.instance().brokersLoaded.disconnect(self.layerManager.brokersLoaded)
        except Exception as e:
            Log.debug(e)
            TopicManagerFactory.unregisterAll()
            pass
        finally:
            if  self.layerManager:
                self.layerManager.deleteLater()
            if  self.telemetryLayer:
                self.telemetryLayer.deleteLater()
            if Brokers:
                Brokers.instance().deleteLater()
            gc.collect()
            Log.debug("Plugin unloaded")


    def runTeardown(self):
        try:
            self.layerManager.tearDown()
            self.telemetryLayer.tearDown()

        except Exception as e:
            Log.debug(e)
            pass

    def about(self):

        webbrowser.open(Settings.getMeta("homepage"))

    #        for broker in Brokers.instance().list():
    #            Log.debug(broker.topicManager())
    #        return


    def configure(self):
        self.telemetryLayer.instance().show()


    def createLayer(self):
        if self.layerManager is not None:
            self.layerManager.createEmptyLayer()

    def freshInstall(self):
        version = Settings.get('version')
        current = Settings.getMeta('version')
        return current != version