Beispiel #1
0
 def _gpsfound(self, gpsConnection):
     log("GPS found")
     self.gpsConn = gpsConnection
     self.gpsConn.nmeaSentenceReceived.connect(self.parse_data)
     # self.gpsConn.stateChanged.connect(self.gpsStateChanged)
     self.isConnected = True
     QgsGPSConnectionRegistry.instance().registerConnection(self.gpsConn)
Beispiel #2
0
    def gpsStateChanged(self, gpsInfo: QgsGpsInformation):
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)

        map_pos = QgsPointXY(gpsInfo.longitude, gpsInfo.latitude)
        self.latlong_position = map_pos

        if self.crs:
            transform = QgsCoordinateTransform(self.wgs84CRS, self.crs,
                                               QgsProject.instance())
            try:
                map_pos = transform.transform(map_pos)
            except QgsCsException:
                log("Transform exception")
                return

            if self.position is None:
                self.firstfix.emit(map_pos, gpsInfo)

            self.info = gpsInfo

            if (datetime.now() - self._gpsupdate_last
                ).total_seconds() > self._gpsupdate_frequency:
                self.gpsposition.emit(map_pos, gpsInfo)
                self._gpsupdate_last = datetime.now()

            self._position = map_pos
            self.elevation = gpsInfo.elevation
Beispiel #3
0
    def gpsStateChanged(self, gpsInfo):
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)

        map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude)
        self.latlong_position = map_pos

        if self.crs:
            transform = QgsCoordinateTransform(self.wgs84CRS, self.crs)
            try:
                map_pos = transform.transform(map_pos)
            except QgsCsException:
                log("Transform exception")
                return

            if self.postion is None:
                self.firstfix.emit(map_pos, gpsInfo)

            self.info = gpsInfo
            self.gpsposition.emit(map_pos, gpsInfo)
            self.postion = map_pos
            self.elevation = gpsInfo.elevation
Beispiel #4
0
    def gpsStateChanged(self, gpsInfo):
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)


        map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude)
        self.latlong_position = map_pos

        if self.crs:
            transform = QgsCoordinateTransform(self.wgs84CRS, self.crs)
            try:
                map_pos = transform.transform(map_pos)
            except QgsCsException:
                log("Transform exception")
                return

            if self.postion is None:
                self.firstfix.emit(map_pos, gpsInfo)

            self.info = gpsInfo

            if (datetime.now()-self._gpsupdate_last).total_seconds() > self._gpsupdate_frequency:
                self.gpsposition.emit(map_pos, gpsInfo)
                self._gpsupdate_last = datetime.now()

            self.postion = map_pos
            self.elevation = gpsInfo.elevation
Beispiel #5
0
    def gpsStateChanged(self, gpsInfo):
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)


        map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude)

        if self.crs:
            transform = QgsCoordinateTransform(self.wgs84CRS, self.crs)
            try:
                map_pos = transform.transform(map_pos)
            except QgsCsException:
                log("Transform exception")
                return

            if self.postion is None:
                self.firstfix.emit(map_pos, gpsInfo)

            self.gpspostion.emit(map_pos, gpsInfo)
            self.postion = map_pos
            self.elevation = gpsInfo.elevation
Beispiel #6
0
 def _gpsfound(self, gpsConnection):
     log("GPS found")
     self.gpsConn = gpsConnection
     self.gpsConn.nmeaSentenceReceived.connect(self.parse_data)
     # self.gpsConn.stateChanged.connect(self.gpsStateChanged)
     self.isConnected = True
     QgsGPSConnectionRegistry.instance().registerConnection(self.gpsConn)
Beispiel #7
0
    def check_for_update_events(self, widget, value):
        if not self.feature:
            return

        from qgis.core import QgsExpression, QgsExpressionContext, QgsExpressionContextScope
        # If we don't have any events for this widgets just get out now
        if not widget.id in self.events:
            return

        events = self.events[widget.id]
        events = [
            event for event in events if event['event'].lower() == 'update'
        ]
        if not events:
            return

        feature = self.to_feature(no_defaults=True)

        for event in events:
            action = event['action'].lower()
            targetid = event['target']
            if targetid == widget.id:
                utils.log(
                    "Can't connect events to the same widget. ID {}".format(
                        targetid))
                continue

            widget = self.get_widget_from_id(targetid)

            if not widget:
                utils.log(
                    "Can't find widget for id {} in form".format(targetid))
                continue

            condition = event['condition']
            expression = event['value']

            context = QgsExpressionContext()
            scope = QgsExpressionContextScope()
            scope.setVariable("value", value)
            scope.setVariable("field", widget.field)
            context.setFeature(feature)
            context.appendScope(scope)

            conditionexp = QgsExpression(condition)
            exp = QgsExpression(expression)

            if action.lower() == "show":
                widget.hidden = not conditionexp.evaluate(context)
            if action.lower() == "hide":
                widget.hidden = conditionexp.evaluate(context)
            if action == 'widget expression':
                if conditionexp.evaluate(context):
                    newvalue = self.widget_default(field, feature=feature)
                    widget.setvalue(newvalue)
            if action == 'set value':
                if conditionexp.evaluate(context):
                    newvalue = exp.evaluate(context)
                    widget.setvalue(newvalue)
 def copy(self, src, dest):
     try:
         shutil.copytree(src, dest)
     except OSError as e:
         # If the error was caused because the source wasn't a directory
         if e.errno == errno.ENOTDIR:
             shutil.copy(src, dst)
         else:
             utils.log('Directory not copied. Error: %s' % e)#print('Directory not copied. Error: %s' % e)
Beispiel #9
0
 def getPanels(self):
     for module in glob.iglob(os.path.join(self.folder, "_panels", '*.py')):
         modulename = os.path.splitext(os.path.basename(module))[0]
         try:
             panelmod = imp.load_source(modulename, module)
             yield panelmod.createPanel()
         except ImportError as err:
             log("Panel import error {}".format(err))
         except AttributeError:
             log("No createPanel defined on module {}".format(module))
Beispiel #10
0
    def disconnectGPS(self):
        if self.isConnected:
            self.gpsConn.stateChanged.disconnect(self.gpsStateChanged)
            self.gpsConn.close()

        log("GPS disconnect")
        self.isConnected = False
        self.postion = None
        QgsGPSConnectionRegistry.instance().unregisterConnection(self.gpsConn)
        self.gpsdisconnected.emit()
Beispiel #11
0
 def getPanels(self):
     for module in glob.iglob(os.path.join(self.folder, "_panels", '*.py')):
         modulename = os.path.splitext(os.path.basename(module))[0]
         try:
             panelmod = imp.load_source(modulename, module)
             yield panelmod.createPanel()
         except ImportError as err:
             log("Panel import error {}".format(err))
         except AttributeError:
             log("No createPanel defined on module {}".format(module))
Beispiel #12
0
    def disconnectGPS(self):
        if self.isConnected:
            self.gpsConn.stateChanged.disconnect(self.gpsStateChanged)
            self.gpsConn.close()

        log("GPS disconnect")
        self.isConnected = False
        self.postion = None
        QgsGPSConnectionRegistry.instance().unregisterConnection(self.gpsConn)
        self.gpsdisconnected.emit()
Beispiel #13
0
 def _loadmodule(self):
     projectfolder = os.path.abspath(os.path.join(self.folder, '..'))
     projectname = os.path.basename(projectfolder)
     name = "{project}.{formfolder}".format(project=projectname, formfolder=self.name)
     try:
         self._module = importlib.import_module(name)
     except ImportError as err:
         log(sys.path)
         log(err)
         self.errors.append(err.message)
         self._module = None
Beispiel #14
0
    def check_for_update_events(self, widget, value):
        if not self.feature:
            return

        from qgis.core import QgsExpression, QgsExpressionContext, QgsExpressionContextScope
        # If we don't have any events for this widgets just get out now
        if not widget.id in self.events:
            return

        events = self.events[widget.id]
        events = [event for event in events if event['event'].lower() == 'update']
        if not events:
            return

        feature = self.to_feature(no_defaults=True)

        for event in events:
            action = event['action'].lower()
            targetid = event['target']
            if targetid == widget.id:
                utils.log("Can't connect events to the same widget. ID {}".format(targetid))
                continue

            widget = self.get_widget_from_id(targetid)

            if not widget:
                utils.log("Can't find widget for id {} in form".format(targetid))
                continue

            condition = event['condition']
            expression = event['value']

            context = QgsExpressionContext()
            scope = QgsExpressionContextScope()
            scope.setVariable("value", value)
            scope.setVariable("field", widget.field)
            context.setFeature(feature)
            context.appendScope(scope)

            conditionexp = QgsExpression(condition)
            exp = QgsExpression(expression)

            if action.lower() == "show":
                widget.hidden = not conditionexp.evaluate(context)
            if action.lower() == "hide":
                widget.hidden = conditionexp.evaluate(context)
            if action == 'widget expression':
                if conditionexp.evaluate(context):
                    newvalue = self.widget_default(field, feature=feature)
                    widget.setvalue(newvalue)
            if action == 'set value':
                if conditionexp.evaluate(context):
                    newvalue = exp.evaluate(context)
                    widget.setvalue(newvalue)
Beispiel #15
0
    def disconnectGPS(self):
        if self.isConnected:
            self.gpsConn.stateChanged.disconnect(self.gpsStateChanged)
            self.gpsConn.close()

        self.marker.hide()
        log("GPS disconnect")
        self.isConnected = False
        self.setIcon(QIcon(":/icons/gps"))
        self.setIconText("Enable GPS")
        self.setEnabled(True)
Beispiel #16
0
    def getPanels(self):
        raise NotImplementedError("Panel support not migrated in Roam 3")

        for module in glob.iglob(os.path.join(self.folder, "_panels", '*.py')):
            modulename = os.path.splitext(os.path.basename(module))[0]
            try:
                panelmod = self.module.load_source(modulename, module)
                yield panelmod.createPanel()
            except ImportError as err:
                log("Panel import error {}".format(err))
            except AttributeError:
                log("No createPanel defined on module {}".format(module))
Beispiel #17
0
    def disconnectGPS(self):
        if self.isConnected:
            self.gpsConn.stateChanged.disconnect(self.gpsStateChanged)
            self.gpsConn.close()

        self.marker.hide()
        log("GPS disconnect")
        self.isConnected = False
        self.setIcon(QIcon(":/icons/gps"))
        self.setIconText("Enable GPS")
        self.setEnabled(True)
        self._position = None
        QgsGPSConnectionRegistry.instance().unregisterConnection(gpsConnection)
Beispiel #18
0
 def onProjectLoad(self):
     """
         Call the projects onProjectLoad method defined in projects __init__ module.
         Returns True if the user is able to load the project, else False
     """
     try:
         if hasattr(self.module, "onProjectLoad"):
             return self.module.onProjectLoad()
         else:
             return True, None
     except ImportError as err:
         log(err)
         return True, None
Beispiel #19
0
    def connectGPS(self, portname):
        if not self.isConnected:
            self.currentport = portname
            if portname == 'scan' or portname == '':
                log("Auto scanning for GPS port")
                portname = ''

            self.detector = QgsGPSDetector(portname)
            log("Connecting to:{}".format(portname or 'scan'))
            self.detector.detected.connect(self._gpsfound)
            self.detector.detectionFailed.connect(self.gpsfailed)
            self.isConnectFailed = False
            self.detector.advance()
Beispiel #20
0
    def connectGPS(self, portname):
        if not self.isConnected:
            self._currentport = portname
            if portname == 'scan' or portname == '':
                log("Auto scanning for GPS port")
                portname = ''

            self.detector = QgsGPSDetector(portname)
            log("Connecting to:{}".format(portname or 'scan'))
            self.detector.detected.connect(self._gpsfound)
            self.detector.detectionFailed.connect(self.gpsfailed)
            self.isConnectFailed = False
            self.detector.advance()
Beispiel #21
0
    def __WndProc(self, hWnd, msg, wParam, lParam):
        if msg == win32con.WM_POWERBROADCAST:
            if wParam == win32con.PBT_APMSUSPEND:
                log("Power off")
                self.poweroff.emit()
            elif wParam == win32con.PBT_APMRESUMESUSPEND:
                log("Power ON")
                self.poweron.emit()
        else:
            win32api.SetWindowLong(self.widget.winId(),
                                    win32con.GWL_WNDPROC,
                                    self.__oldProc)

        return win32gui.CallWindowProc(self.__oldProc, hWnd, msg, wParam, lParam)
Beispiel #22
0
    def parse_data(self, datastring):
        try:
            data = pynmea2.parse(datastring)
        except AttributeError as er:
            log(er.message)
            return
        except pynmea2.SentenceTypeError as er:
            log(er.message)
            return
        except pynmea2.ParseError as er:
            log(er.message)
            return
        except pynmea2.ChecksumError as er:
            log(er.message)
            return

        mappings = {
            "RMC": self.extract_rmc,
            "GGA": self.extract_gga,
            "GSV": self.extract_gsv,
            "VTG": self.extract_vtg,
            "GSA": self.extract_gsa
        }
        try:
            mappings[data.sentence_type](data)
            self.gpsStateChanged(self.info)
        except KeyError:
            return
        except AttributeError:
            return
Beispiel #23
0
    def parse_data(self, datastring):
        self.log_gps(datastring)
        try:
            data = pynmea2.parse(datastring)
        except AttributeError as er:
            log(er.message)
            return
        except pynmea2.SentenceTypeError as er:
            log(er.message)
            return
        except pynmea2.ParseError as er:
            log(er.message)
            return
        except pynmea2.ChecksumError as er:
            log(er.message)
            return

        mappings = {"RMC": self.extract_rmc,
                    "GGA": self.extract_gga,
                    "GSV": self.extract_gsv,
                    "VTG": self.extract_vtg,
                    "GSA": self.extract_gsa}
        try:
            mappings[data.sentence_type](data)
            self.gpsStateChanged(self.info)
        except KeyError:
            return
        except AttributeError:
            return
Beispiel #24
0
    def __WndProc(self, hWnd, msg, wParam, lParam):
        if msg == win32con.WM_POWERBROADCAST:
            if wParam == win32con.PBT_APMSUSPEND:
                log("Power off")
                self.poweroff.emit()
            elif wParam == win32con.PBT_APMRESUMESUSPEND:
                log("Power ON")
                self.poweron.emit()
        else:
            win32api.SetWindowLong(self.widget.winId(), win32con.GWL_WNDPROC,
                                   self.__oldProc)

        return win32gui.CallWindowProc(self.__oldProc, hWnd, msg, wParam,
                                       lParam)
Beispiel #25
0
 def parse_data(self, datastring):
     try:
         data = pynmea2.parse(datastring)
     except AttributeError as er:
         log(er.message)
         return
     
     mappings = {"RMC": self.extract_rmc,
                 "GGA": self.extract_gga,
                 "GSV": self.extract_gsv,
                 "VTG": self.extract_vtg,
                 "GSA": self.extract_gsa}
     try:
         mappings[data.sentence_type](data)
         self.gpsStateChanged(self.info)
     except KeyError:
         info("{} message not currently handled".format(data.sentence_type))
         pass
Beispiel #26
0
    def gpsStateChanged(self, gpsInfo: QgsGpsInformation):
        # TODO This can also be removed after checking the new QGIS 3 API
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)

        self.elevation = gpsInfo.elevation - roam.config.settings.get(
            'gps_antenna_height', 0.0)
        map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude, self.elevation)
        self.latlong_position = map_pos

        if self.crs:
            coordTransform = QgsCoordinateTransform(self.wgs84CRS, self.crs,
                                                    QgsProject.instance())
            try:
                map_pos.transform(coordTransform)
            except QgsCsException:
                log("Transform exception")
                return

            if self.position is None:
                self.firstfix.emit(map_pos, gpsInfo)

            if (datetime.now() - self._gpsupdate_last
                ).total_seconds() > self._gpsupdate_frequency:
                self.gpsposition.emit(map_pos, gpsInfo)
                self._gpsupdate_last = datetime.now()
                # --- averaging -----------------------------------------------
                # if turned on
                if roam.config.settings.get('gps_averaging', True):
                    # if currently happening
                    if roam.config.settings.get('gps_averaging_in_action',
                                                True):
                        self.gpspoints.append(map_pos)
                        roam.config.settings[
                            'gps_averaging_measurements'] = len(self.gpspoints)
                        roam.config.save()
                    else:
                        if self.gpspoints: self.gpspoints = []
                # -------------------------------------------------------------
            self._position = map_pos.clone()
Beispiel #27
0
 def onProjectLoad(self):
     """
         Call the projects onProjectLoad method defined in projects __init__ module.
         Returns True if the user is able to load the project, else False
     """
     try:
         rootfolder = os.path.abspath(os.path.join(self.folder, '..'))
         name = os.path.basename(self.folder)
         module = imp.find_module(name, [rootfolder])
         module = imp.load_module(name, *module)
         return module.onProjectLoad()
     except ImportError as err:
         log(err)
         print err
         return True, None
     except AttributeError as err:
         log("No onProjectLoad attribute found")
         print "No onProjectLoad attribute found"
         return True, None
Beispiel #28
0
    def onProjectLoad(self):
        """
            Call the projects onProjectLoad method defined in projects __init__ module.
            Returns True if the user is able to load the project, else False
        """
        try:
            name = os.path.basename(self.folder)
            module = importlib.import_module("{}".format(name))
        except ImportError as err:
            log(err)
            print err
            return True, None

        try:
            return module.onProjectLoad()
        except AttributeError as err:
            log("Not onProjectLoad attribute found")
            print "No onProjectLoad attribute found"
            return True, None
Beispiel #29
0
 def onProjectLoad(self):
     """
         Call the projects onProjectLoad method defined in projects __init__ module.
         Returns True if the user is able to load the project, else False
     """
     try:
         name = os.path.basename(self.folder)
         module = importlib.import_module("{}".format(name))
     except ImportError as err:
         log(err)
         print err
         return True, None
         
     try:
         return module.onProjectLoad()
     except AttributeError as err:
         log("Not onProjectLoad attribute found")
         print "No onProjectLoad attribute found"
         return True, None
Beispiel #30
0
 def onProjectLoad(self):
     """
         Call the projects onProjectLoad method defined in projects __init__ module.
         Returns True if the user is able to load the project, else False
     """
     try:
         rootfolder = os.path.abspath(os.path.join(self.folder, '..'))
         name = os.path.basename(self.folder)
         module = imp.find_module(name, [rootfolder])
         module = imp.load_module(name, *module)
         return module.onProjectLoad()
     except ImportError as err:
         log(err)
         print err
         return True, None
     except AttributeError as err:
         log("No onProjectLoad attribute found")
         print "No onProjectLoad attribute found"
         return True, None
Beispiel #31
0
    def connectGPS(self):
        if not self.isConnected:
            #Enable GPS
            self.setIcon(QIcon(":/icons/gps"))
            self.setIconText("Connecting")
            self.setEnabled(False)

            portname = self.settings.settings.get("gpsport", '')
            if portname == 'scan':
                utils.log("Auto scanning for GPS port")
                portname = ''

            self.detector = QgsGPSDetector(portname)
            utils.log("Connecting to:{}".format(portname))
            self.detector.detected.connect(self.connected)
            self.detector.detectionFailed.connect(self.failed)
            self.isConnectFailed = False
            self.detector.advance()
        else:
            self.disconnectGPS()
Beispiel #32
0
def getdefaults(widgets, feature, layer, canvas):
    defaults = {}
    for field, config in widgets:
        default = config.get("default", None)
        if default is None:
            continue
        if isinstance(default, dict):
            defaultconfig = default
            try:
                defaulttype = defaultconfig['type']
                defaultprovider = defaultproviders[defaulttype]
                value = defaultprovider(feature, layer, field, defaultconfig, canvas)
            except KeyError as ex:
                log(ex)
                continue
            except DefaultError as ex:
                log(ex)
                value = None
        else:
            # Pass it though a series of filters to get the default value
            if '[%' in default and '%]' in default:
                # TODO Use regex
                default = QgsExpression.replaceExpressionText(default, feature, layer )
            value = os.path.expandvars(default)

        log("Default value: {}".format(value))
        defaults[field] = value

    defaults.update(featureform.loadsavedvalues(layer))
    return defaults
Beispiel #33
0
    def setTime(self, time):
        """
        Set just the time part of the picker
        """
        hour = time.hour()
        if hour > 12:
            hour = hour - 12
        if hour == 0:
            hour = hour + 12

        minute = time.minute()
        minute = int(round(minute / 5.0) * 5.0)
        amap = time.toString("AP")
        utils.log("Hour %s Minute %s" % (hour, minute))
        try:
            houritems = self.hourpicker.findItems(str(hour),
                                                  Qt.MatchFixedString)
            self.hourpicker.setCurrentItem(houritems[0])
        except IndexError:
            utils.log("Can't find hour")

        try:
            minuteitems = self.minutepicker.findItems(str(minute),
                                                      Qt.MatchFixedString)
            self.minutepicker.setCurrentItem(minuteitems[0])
        except IndexError:
            utils.log("Can't find minute")

        if amap == "PM":
            self.pmbutton.toggle()
Beispiel #34
0
def getdefaults(widgets, feature, layer, canvas):
    defaults = {}
    for field, config in widgets:
        default = config.get("default", None)
        if default is None:
            continue
        if isinstance(default, dict):
            defaultconfig = default
            try:
                defaulttype = defaultconfig['type']
                defaultprovider = defaultproviders[defaulttype]
                value = defaultprovider(feature, layer, field, defaultconfig, canvas)
            except KeyError as ex:
                log(ex)
                continue
            except DefaultError as ex:
                log(ex)
                value = None
        else:
            # Pass it though a series of filters to get the default value
            if '[%' in default and '%]' in default:
                # TODO Use regex
                default = QgsExpression.replaceExpressionText(default, feature, layer )
            value = os.path.expandvars(default)

        log("Default value: {}".format(value))
        defaults[field] = value

    defaults.update(featureform.loadsavedvalues(layer))
    return defaults
    def setTime(self, time):
        """
        Set just the time part of the picker
        """
        hour = time.hour()
        if hour > 12:
            hour = hour - 12
        if hour == 0:
            hour = hour + 12

        minute = time.minute()
        minute = int(round(minute / 5.0) * 5.0)
        amap = time.toString("AP")
        utils.log("Hour %s Minute %s" % (hour, minute))
        try:
            houritems = self.hourpicker.findItems(str(hour), Qt.MatchFixedString)
            self.hourpicker.setCurrentItem(houritems[0])
        except IndexError:
            utils.log("Can't find hour")

        try:
            minuteitems = self.minutepicker.findItems(str(minute), Qt.MatchFixedString)
            self.minutepicker.setCurrentItem(minuteitems[0])
        except IndexError:
            utils.log("Can't find minute")

        if amap == "PM":
            self.pmbutton.toggle()
Beispiel #36
0
def loadsavedvalues(form):
    attr = {}
    savedvaluesfile = os.path.join(values_file, "{}.json".format(form.savekey))
    try:
        utils.log(savedvaluesfile)
        with open(savedvaluesfile, 'r') as f:
            attr = json.loads(f.read())
    except IOError:
        utils.log('No saved values found for %s' % id)
    except ValueError:
        utils.log('No saved values found for %s' % id)
    return attr
Beispiel #37
0
def loadsavedvalues(form):
    attr = {}
    savedvaluesfile = os.path.join(values_file, "{}.json".format(form.savekey))
    try:
        utils.log(savedvaluesfile)
        with open(savedvaluesfile, 'r') as f:
            attr = json.loads(f.read())
    except IOError:
        utils.log('No saved values found for %s' % id)
    except ValueError:
        utils.log('No saved values found for %s' % id)
    return attr
def loadsavedvalues(layer):
    attr = {}
    id = str(layer.id())
    savedvaluesfile = os.path.join(values_file, "%s.json" % id)
    try:
        utils.log(savedvaluesfile)
        with open(savedvaluesfile, 'r') as f:
            attr = json.loads(f.read())
    except IOError:
        utils.log('No saved values found for %s' % id)
    except ValueError:
        utils.log('No saved values found for %s' % id)
    return attr
Beispiel #39
0
def loadsavedvalues(layer):
    attr = {}
    id = str(layer.id())
    savedvaluesfile = os.path.join(values_file, "%s.json" % id)
    try:
        utils.log(savedvaluesfile)
        with open(savedvaluesfile, 'r') as f:
            attr = json.loads(f.read())
    except IOError:
        utils.log('No saved values found for %s' % id)
    except ValueError:
        utils.log('No saved values found for %s' % id)
    return attr
Beispiel #40
0
    def connectGPS(self, portname):
        if not self.isConnected:
            self._currentport = portname
            if portname == 'scan' or portname == '':
                portname = ''
                self.detector = QgsGpsDetector(portname)
                self.detector.detected.connect(self._gpsfound)
                self.detector.detectionFailed.connect(self.gpsfailed)
                self.isConnectFailed = False
                self.detector.advance()
            elif portname.startswith("COM"):
                self.device = QSerialPort(portname)
                baudrates = [
                    QSerialPort.Baud4800, QSerialPort.Baud9600,
                    QSerialPort.Baud38400, QSerialPort.Baud57600,
                    QSerialPort.Baud115200
                ]
                flow = config.get("gps", {}).get("flow_control", None)
                rate = config.get("gps", {}).get("rate", None)
                if rate:
                    baudrates = [rate]

                for rate in baudrates:
                    self.device.setBaudRate(rate)
                    if flow == "hardware":
                        log("using hardware flow control for GPS")
                        self.device.setFlowControl(QSerialPort.HardwareControl)
                    elif flow == "software":
                        log("using software flow control for GPS")
                        self.device.setFlowControl(QSerialPort.SoftwareControl)
                    else:
                        self.device.setFlowControl(QSerialPort.NoFlowControl)
                    self.device.setParity(QSerialPort.NoParity)
                    self.device.setDataBits(QSerialPort.Data8)
                    self.device.setStopBits(QSerialPort.OneStop)
                    if self.device.open(QIODevice.ReadWrite):
                        log("Connection opened with {0}".format(
                            self.device.baudRate()))
                        self.gpsConn = QgsNmeaConnection(self.device)
                        self._gpsfound(self.gpsConn)
                        break
                    else:
                        del self.device
                        continue
                else:
                    # If we can't connect to any GPS just error out
                    self.gpsfailed.emit()
Beispiel #41
0
def loadsavedvalues(form) -> dict:
    """
    Load the last values that have been saved for the form.
    :param form: The form the find the saved values for.
    :return: A dict with fieldname and value of the saved values.
    """
    attr = {}
    savedvaluesfile = os.path.join(values_file, "{}.json".format(form.savekey))
    try:
        utils.log(savedvaluesfile)
        with open(savedvaluesfile, 'r') as f:
            attr = json.loads(f.read())
    except IOError:
        utils.log('No saved values found for %s' % id)
    except ValueError:
        utils.log('No saved values found for %s' % id)
    return attr
Beispiel #42
0
    def connectGPS(self, portname):
        if not self.connected:
            self._currentport = portname
            if config.get("gps", {}).get("exp1", False):
                log("Using QgsSettings override for flow control")
                if portname == 'scan' or portname == '':
                    portname = ''

                flow = config.get("gps", {}).get("flow_control", None)
                log(f"GPS flow control is: {flow}")
                settings = QgsSettings()

                if flow:
                    if flow == "hardware":
                        settings.setValue("gps/flow_control", QSerialPort.HardwareControl, QgsSettings.Core)
                    elif flow == "software":
                        settings.setValue("gps/flow_control", QSerialPort.SoftwareControl, QgsSettings.Core)

                self.detector = QgsGpsDetector(portname)
                self.detector.detected.connect(self.gpsfound_handler)
                self.detector.detectionFailed.connect(self.gpsfailed)
                self.detector.advance()
            else:
                log("Using default code for GPS connection")
                if portname == 'scan' or portname == '':
                    portname = ''
                    self.detector = QgsGpsDetector(portname)
                    self.detector.detected.connect(self.gpsfound_handler)
                    self.detector.detectionFailed.connect(self.gpsfailed)
                    self.detector.advance()
                elif portname.startswith("COM"):
                    flow = config.get("gps", {}).get("flow_control", None)
                    rate = config.get("gps", {}).get("rate", None)
                    if rate:
                        baudrates = [rate]
                    else:
                        baudrates = [QSerialPort.Baud4800,
                                     QSerialPort.Baud9600,
                                     QSerialPort.Baud38400,
                                     QSerialPort.Baud57600,
                                     QSerialPort.Baud115200]

                    for rate in baudrates:
                        device = QSerialPort(portname)
                        device.setBaudRate(rate)
                        if flow == "hardware":
                            log("Using hardware flow control")
                            device.setFlowControl(QSerialPort.HardwareControl)
                        elif flow == "software":
                            log("Using software flow control")
                            device.setFlowControl(QSerialPort.SoftwareControl)
                        else:
                            device.setFlowControl(QSerialPort.NoFlowControl)
                        device.setParity(QSerialPort.NoParity)
                        device.setDataBits(QSerialPort.Data8)
                        device.setStopBits(QSerialPort.OneStop)
                        if device.open(QIODevice.ReadWrite):
                            gpsConn = QgsNmeaConnection(device)
                            self.gpsfound_handler(gpsConn)
                            break
                        else:
                            continue
                    else:
                        # If we can't connect to any GPS just error out
                        self.gpsfailed.emit()
Beispiel #43
0
 def fullScreenCheck_stateChanged(self, checked):
     utils.log("fullscreen changed")
     self.settings["fullscreen"] = checked
     self.notifysettingsupdate()
Beispiel #44
0
    def setupui(self):
        """
        Setup the widget in the form
        """
        self.geomwidget = self.findcontrol("__geomwidget")

        widgetsconfig = copy.deepcopy(self.formconfig['widgets'])

        try:
            widgetsconfig = self.get_widgets(widgetsconfig)
        except AttributeError:
            pass

        layer = self.form.QGISLayer
        # Crash in QGIS if you lookup a field that isn't found.
        # We just make a dict with all fields lower because QgsFields is case sensitive.
        fields = {field.name().lower():field for field in layer.pendingFields().toList()}

        # Build a lookup for events
        self.events = collections.defaultdict(list)
        for event in self.form.events:
            self.events[event['source']].append(event)

        widgetsconfig = copy.deepcopy(widgetsconfig)
        self.sectionwidgets = {}

        currentsection = None
        for config in widgetsconfig:
            widgettype = config['widget']
            if widgettype == "Section":
                name = config['name']
                currentsection = name
                self.sectionwidgets[name] = []
                continue

            field = config['field']
            if not field:
                utils.info("Skipping widget. No field defined")
                continue

            field = field.lower()

            if field in self.boundwidgets:
                utils.warning("Can't bind the same field ({}) twice.".format(field))
                continue

            widget = self.findcontrol(field)
            if widget is None:
                widget = roam.editorwidgets.core.createwidget(widgettype)
                config['hidden'] = True
                utils.info("No widget named {} found so we have made one.".format(field))

            label = self.findcontrol("{}_label".format(field))
            if label is None:
                utils.debug("No label found for {}".format(field))

            widgetconfig = config.get('config', {})
            widgetconfig['formwidget'] = self
            try:
                qgsfield = fields[field]
            except KeyError:
                utils.log("No field for ({}) found".format(field))

            context = dict(project=self.form.project,
                           form=self.form,
                           featureform=self)
            try:
                widgetwrapper = roam.editorwidgets.core.widgetwrapper(widgettype=widgettype,
                                                                      layer=self.form.QGISLayer,
                                                                      field=qgsfield,
                                                                      widget=widget,
                                                                      label=label,
                                                                      config=widgetconfig,
                                                                      context=context)
            except EditorWidgetException as ex:
                utils.exception(ex)
                continue

            widgetwrapper.default_events = config.get('default_events', ['capture'])
            readonlyrules = config.get('read-only-rules', [])

            if self.editingmode and 'editing' in readonlyrules:
                widgetwrapper.readonly = True
            elif 'insert' in readonlyrules or 'always' in readonlyrules:
                widgetwrapper.readonly = True

            widgetwrapper.hidden = config.get('hidden', False)

            widgetwrapper.newstyleform = self.formconfig.get("newstyle", False)
            widgetwrapper.required = config.get('required', False)
            widgetwrapper.id = config.get('_id', '')

            # Only connect widgets that have events
            if widgetwrapper.id in self.events:
                widgetwrapper.valuechanged.connect(partial(self.check_for_update_events, widgetwrapper))

            widgetwrapper.valuechanged.connect(self.updaterequired)

            try:
                changedslot = getattr(self, "widget_{}_changed".format(field))
                widgetwrapper.valuechanged.connect(changedslot)
            except AttributeError:
                pass

            widgetwrapper.largewidgetrequest.connect(RoamEvents.show_widget.emit)

            self._bindsavebutton(field)
            self.boundwidgets[field] = widgetwrapper
            try:
                self.widgetidlookup[config['_id']] = widgetwrapper
            except KeyError:
                pass

            if currentsection:
                self.sectionwidgets[currentsection].append(widgetwrapper)
Beispiel #45
0
 def _gpsfound(self, gpsConnection):
     log("GPS found")
     self.gpsConn = gpsConnection
     self.gpsConn.stateChanged.connect(self.gpsStateChanged)
     self.isConnected = True
     QgsGPSConnectionRegistry.instance().registerConnection(self.gpsConn)
Beispiel #46
0
 def failed(self):
     self.setEnabled(True)
     log("GPS Failed to connect")
     self.setIcon(QIcon(':/icons/gps_failed'))
     self.setIconText("GPS Failed. Click to retry")
Beispiel #47
0
 def failed(self):
     self.setEnabled(True)
     log("GPS Failed to connect")
     self.setIcon(QIcon(':/icons/gps_failed'))
     self.setIconText("GPS Failed. Click to retry")
Beispiel #48
0
    def setupui(self):
        """
        Setup the widget in the form
        """
        self.geomwidget = self.findcontrol("__geomwidget")

        widgetsconfig = copy.deepcopy(self.formconfig['widgets'])

        try:
            widgetsconfig = self.get_widgets(widgetsconfig)
        except AttributeError:
            pass

        layer = self.form.QGISLayer
        # Crash in QGIS if you lookup a field that isn't found.
        # We just make a dict with all fields lower because QgsFields is case sensitive.
        fields = {
            field.name().lower(): field
            for field in layer.fields().toList()
        }

        # Build a lookup for events
        self.events = collections.defaultdict(list)
        for event in self.form.events:
            self.events[event['source']].append(event)

        widgetsconfig = copy.deepcopy(widgetsconfig)
        self.sectionwidgets = {}

        currentsection = None
        for config in widgetsconfig:
            widgettype = config['widget']
            if widgettype == "Section":
                name = config['name']
                currentsection = name
                self.sectionwidgets[name] = []
                continue

            field = config['field']
            if not field:
                utils.info("Skipping widget. No field defined")
                continue

            field = field.lower()

            if field in self.boundwidgets:
                utils.warning(
                    "Can't bind the same field ({}) twice.".format(field))
                continue

            widget = self.findcontrol(field)
            if widget is None:
                widget = roam.editorwidgets.core.createwidget(widgettype)
                config['hidden'] = True
                utils.info(
                    "No widget named {} found so we have made one.".format(
                        field))

            label = self.findcontrol("{}_label".format(field))
            if label is None:
                utils.debug("No label found for {}".format(field))

            widgetconfig = config.get('config', {})
            widgetconfig['formwidget'] = self
            try:
                qgsfield = fields[field]
            except KeyError:
                utils.log("No field for ({}) found".format(field))
                continue

            context = dict(project=self.form.project,
                           form=self.form,
                           featureform=self)
            try:
                widgetwrapper = roam.editorwidgets.core.widgetwrapper(
                    widgettype=widgettype,
                    layer=self.form.QGISLayer,
                    field=qgsfield,
                    widget=widget,
                    label=label,
                    config=widgetconfig,
                    context=context,
                    main_config=config)
            except EditorWidgetException as ex:
                utils.exception(ex)
                continue

            widgetwrapper.default_events = config.get('default_events',
                                                      ['capture'])
            readonlyrules = config.get('read-only-rules', [])

            if self.editingmode and 'editing' in readonlyrules:
                widgetwrapper.readonly = True
            elif 'insert' in readonlyrules or 'always' in readonlyrules:
                widgetwrapper.readonly = True

            widgetwrapper.hidden = config.get('hidden', False)

            widgetwrapper.newstyleform = self.formconfig.get("newstyle", False)
            widgetwrapper.required = config.get('required', False)

            # Only connect widgets that have events
            if widgetwrapper.id in self.events:
                widgetwrapper.valuechanged.connect(
                    partial(self.check_for_update_events, widgetwrapper))

            widgetwrapper.valuechanged.connect(self.updaterequired)

            try:
                changedslot = getattr(self, "widget_{}_changed".format(field))
                widgetwrapper.valuechanged.connect(changedslot)
            except AttributeError:
                pass

            widgetwrapper.largewidgetrequest.connect(
                RoamEvents.show_widget.emit)

            self._bindsavebutton(field)
            self.boundwidgets[field] = widgetwrapper
            try:
                self.widgetidlookup[config['_id']] = widgetwrapper
            except KeyError:
                pass

            if currentsection:
                self.sectionwidgets[currentsection].append(widgetwrapper)
Beispiel #49
0
 def _gpsfound(self, gpsConnection):
     log("GPS found")
     self.gpsConn = gpsConnection
     self.gpsConn.stateChanged.connect(self.gpsStateChanged)
     self.isConnected = True
     QgsGPSConnectionRegistry.instance().registerConnection(self.gpsConn)
Beispiel #50
0
 def fullScreenCheck_stateChanged(self, checked):
     utils.log("fullscreen changed")
     self.settings["fullscreen"] = checked
     self.notifysettingsupdate()