示例#1
0
def getActiveFlights(vehicle=None):
    ACTIVE_FLIGHTS_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_ACTIVE_FLIGHT_MODEL)

    if not vehicle:
        return ACTIVE_FLIGHTS_MODEL.get().objects.all()
    else:
        # filter by vehicle
        return ACTIVE_FLIGHTS_MODEL.get().objects.filter(flight__vehicle=vehicle)
示例#2
0
 def initializeVehicleChoices(self):
     CHOICES = []
     VEHICLE_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_VEHICLE_MODEL)
     if (VEHICLE_MODEL.get().objects.count() > 0):
         for vehicle in VEHICLE_MODEL.get().objects.all().order_by('name'):
             CHOICES.append((vehicle.name, vehicle.name))
 
     if len(CHOICES) == 1:
         initial = [c[0] for c in CHOICES]
     else:
         initial = None
     result = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple(attrs={"checked":""}), required=False, initial=initial)
     return result
示例#3
0
 def initializeLetter(self, dateprefix):
     GROUP_FLIGHT_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_GROUP_FLIGHT_MODEL)
     try:
         last = GROUP_FLIGHT_MODEL.get().objects.filter(name__startswith=dateprefix).order_by('name').last()
         self.fields['prefix'].initial = chr(ord(last.name[-1]) + 1)
     except:
         self.fields['prefix'].initial = 'A'
示例#4
0
def planImportXPJson(request):
    PLAN_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
    try:
        form = UploadXPJsonForm(request.POST, request.FILES)
        if form.is_valid():
            planUuid = form.cleaned_data['planUuid']
            try:
                plan = PLAN_MODEL.get().objects.get(uuid=planUuid)
            except:
                return HttpResponse(json.dumps({'Success':"False", 'responseText': 'Wrong UUID, plan not found'}), content_type='application/json', status=406)
            incoming = request.FILES['file']
            newJson = handle_uploading_xpjson(incoming)
            if (len(newJson) > 0):
                newJsonObj = json.loads(newJson, 'UTF-8')
                foundUuid = newJsonObj['uuid']
                if (foundUuid != planUuid):
                    return HttpResponse(json.dumps({'Success':"False", 'responseText': 'Loaded JSON is for a different plan; UUID of plans do not match.'}), content_type='application/json', status=406)
                isValid = validateJson(newJsonObj)
                if isValid == True:
                    updateJson(plan, newJsonObj)
                    return HttpResponse(json.dumps({'Success':"True"}))
                else:
                    return HttpResponse(json.dumps({'Success':"False", 'responseText': isValid}), content_type='application/json', status=406)
            else:
                return HttpResponse(json.dumps({'Success':"False", 'responseText': 'JSON Empty'}), content_type='application/json', status=406)
    except Exception:
        traceback.print_exc()
        exc_type, exc_value, exc_traceback = sys.exc_info()
        return HttpResponse(json.dumps({'Success':"False", 'responseText': exc_value['message']}), content_type='application/json', status=406)
示例#5
0
def planImportXPJson(request):
    PLAN_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
    try:
        form = UploadXPJsonForm(request.POST, request.FILES)
        if form.is_valid():
            planUuid = form.cleaned_data['planUuid']
            try:
                plan = PLAN_MODEL.get().objects.get(uuid=planUuid)
            except:
                return HttpResponse(json.dumps({'Success':"False", 'responseText': 'Wrong UUID, plan not found'}), content_type='application/json', status=406)
            incoming = request.FILES['file']
            newJson = handle_uploading_xpjson(incoming)
            if (len(newJson) > 0):
                newJsonObj = json.loads(newJson, 'UTF-8')
                foundUuid = newJsonObj['uuid']
                if (foundUuid != planUuid):
                    return HttpResponse(json.dumps({'Success':"False", 'responseText': 'Loaded JSON is for a different plan; UUID of plans do not match.'}), content_type='application/json', status=406)
                isValid = validateJson(newJsonObj)
                if isValid == True:
                    updateJson(plan, newJsonObj)
                    return HttpResponse(json.dumps({'Success':"True"}))
                else:
                    return HttpResponse(json.dumps({'Success':"False", 'responseText': isValid}), content_type='application/json', status=406)
            else:
                return HttpResponse(json.dumps({'Success':"False", 'responseText': 'JSON Empty'}), content_type='application/json', status=406)
    except Exception:
        traceback.print_exc()
        exc_type, exc_value, exc_traceback = sys.exc_info()
        return HttpResponse(json.dumps({'Success':"False", 'responseText': exc_value['message']}), content_type='application/json', status=406)
示例#6
0
def callPextantAjax(request, planId, clear=0):
    """ Call Pextant over Ajax and either return the modified plan with success message,
    or return error message.
    """
    PLAN_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
    response = {}
    try:
        plan = PLAN_MODEL.get().objects.get(pk=planId)
        plan = pextantHarness.clearSegmentGeometry(plan)
        response["plan"] = plan.jsonPlan
        if clear:
            response["msg"] = "Sextant route cleared."
            response["status"] = True
            status = 200
        else:
            optimize = str(request.POST['optimize'])

            maxSlope = float(request.POST['slope'])
            post_extent = request.POST['extent']
            if post_extent:
                extent = [float(val) for val in (str(post_extent).split(','))]
            plan = pextantHarness.callPextant(request, plan, optimize,
                                              maxSlope, extent)
            response["plan"] = plan.jsonPlan
            response["msg"] = "Sextant has calculated a new route."
            response["status"] = True
            status = 200
    except Exception, e:
        traceback.print_exc()
        response["msg"] = str(e)
        response["status"] = False
        status = 406
示例#7
0
    def startTracking(self):
        resource = self.getResource()

        #Create the track if it does not exist
        if not self.track:
            TRACK_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_TRACK_MODEL)
            try:
                track = TRACK_MODEL.get().objects.get(name=self.name)
            except ObjectDoesNotExist:
                timezone = settings.TIME_ZONE
                if self.plans:
                    timezone = str(self.plans[0].plan.jsonPlan.site.
                                   alternateCrs.properties.timezone)
                    self.timezone = timezone
                track = TRACK_MODEL.get()(
                    name=self.name,
                    resource=resource,
                    timezone=timezone,
                    iconStyle=geocamTrackModels.IconStyle.objects.get(
                        uuid=resource.name),
                    lineStyle=geocamTrackModels.LineStyle.objects.get(
                        uuid=resource.name),
                    dataType=DataType.objects.get(name="RawGPSLocation"))
                track.save()
                self.track = track

                # this is for archival purposes; make sure remoteDelay is set for the other server's delay.
                delayConstant = Constant.objects.get(name="remoteDelay")
                self.delaySeconds = int(delayConstant.value)
                self.save()

        if settings.PYRAPTORD_SERVICE is True:
            pyraptord = getPyraptordClient()
            serviceName = self.vehicle.name + "TrackListener"
            ipAddress = Constant.objects.get(name=resource.name +
                                             "_TRACKING_IP")
            protocol = Constant.objects.get(name=resource.name +
                                            "_TRACKING_PROTO")
            scriptPath = os.path.join(settings.PROJ_ROOT, 'apps', 'basaltApp',
                                      'scripts', 'evaTrackListener.py')
            command = "%s -o %s -p %d -n %s --proto=%s -t %s" % (
                scriptPath, ipAddress.value, resource.port,
                self.vehicle.name[-1:], protocol.value, self.name)
            stopPyraptordServiceIfRunning(pyraptord, serviceName)
            time.sleep(2)
            pyraptord.updateServiceConfig(serviceName, {'command': command})
            pyraptord.startService(serviceName)
示例#8
0
def getInstrumentDataCsvResponse(request, productModel, productPk):
    INSTRUMENT_DATA_PRODUCT_MODEL = LazyGetModelByName(productModel)
    dataProduct = get_object_or_404(INSTRUMENT_DATA_PRODUCT_MODEL.get(), pk=productPk)
    filename, dataframe = dataProduct.getInstrumentDataCsv()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=' + filename
    dataframe.to_csv(response, index=False)
    return response
示例#9
0
def saveUpdatedInstrumentData(request, instrument_name, pk):
    """
    Updates instrument data on save.
    """

    if request.method == 'POST':
        mapDict = settings.XGDS_MAP_SERVER_JS_MAP[instrument_name]
        INSTRUMENT_MODEL = LazyGetModelByName(mapDict['model'])
        dataProduct = INSTRUMENT_MODEL.get().objects.get(pk=pk)

        # get existing data.
        if 'edit_form_class' in mapDict:
            form = getFormByName(mapDict['edit_form_class'])(request.POST,
                                                             request.FILES)
        else:
            form = BasaltInstrumentDataForm(request.POST, request.FILES)

        try:
            form.is_valid()
        except:
            pass

        for key in form.changed_data:
            value = form.cleaned_data[key]
            if not hasattr(value, 'read'):
                if not isinstance(value, datetime.datetime):
                    setattr(dataProduct, key, value)
            else:
                form.handleFileUpdate(dataProduct, key)
        # save the update info into the model.


#         postDict = request.POST.dict()
#         dataProduct.name = postDict['name']
#         dataProduct.description = postDict['description']
#         dataProduct.minerals = postDict['minerals']
#         resourceId = postDict['resource']
#         if resourceId:
#             resource = BasaltResource.objects.get(id=resourceId)
#             dataProduct.resource = resource

        dataProduct.acquisition_time = form.cleaned_data['dataCollectionTime']

        if (('lat' in form.cleaned_data) and
            ('lon' in form.cleaned_data)) or ('alt' in form.cleaned_data):
            editInstrumentDataPosition(dataProduct, form.cleaned_data['lat'],
                                       form.cleaned_data['lon'],
                                       form.cleaned_data['alt'])
        dataProduct.save()

        messages.success(request, 'Instrument data successfully saved!')

        return HttpResponseRedirect(
            reverse('search_map_single_object',
                    kwargs={
                        'modelPK': pk,
                        'modelName': instrument_name
                    }))
示例#10
0
    def initializeVehicleChoices(self):
        CHOICES = []
        VEHICLE_MODEL = LazyGetModelByName(
            settings.XGDS_PLANNER2_VEHICLE_MODEL)
        if (VEHICLE_MODEL.get().objects.count() > 0):
            for vehicle in VEHICLE_MODEL.get().objects.all().order_by('name'):
                CHOICES.append((vehicle.name, vehicle.name))

        if len(CHOICES) == 1:
            initial = [c[0] for c in CHOICES]
        else:
            initial = None
        result = forms.MultipleChoiceField(
            choices=CHOICES,
            widget=forms.CheckboxSelectMultiple(attrs={"checked": ""}),
            required=False,
            initial=initial)
        return result
示例#11
0
 def initializeLetter(self, dateprefix):
     GROUP_FLIGHT_MODEL = LazyGetModelByName(
         settings.XGDS_PLANNER2_GROUP_FLIGHT_MODEL)
     try:
         last = GROUP_FLIGHT_MODEL.get().objects.filter(
             name__startswith=dateprefix).order_by('name').last()
         self.fields['prefix'].initial = chr(ord(last.name[-1]) + 1)
     except:
         self.fields['prefix'].initial = 'A'
示例#12
0
def mapJsonPosition(request, id):
    POSITION_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_POSITION_MODEL)
    try:
        position = POSITION_MODEL.get().objects.get(pk=id)
        json_data = json.dumps([position.toMapDict()], cls=DatetimeJsonEncoder)
        return HttpResponse(content=json_data,
                            content_type="application/json")
    except:
        return HttpResponse(content={},
                            content_type="application/json")
示例#13
0
def mapJsonPlan(request, uuid):
    PLAN_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
    try:
        plan = PLAN_MODEL.get().objects.get(uuid=uuid)
        json_data = json.dumps([plan.toMapDict()], indent=4)
        return HttpResponse(content=json_data,
                            content_type="application/json")
    except:
        return HttpResponse(content={},
                            content_type="application/json")
示例#14
0
def mapJsonPlan(request, uuid):
    PLAN_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
    try:
        plan = PLAN_MODEL.get().objects.get(uuid=uuid)
        json_data = json.dumps([plan.toMapDict()], indent=4)
        return HttpResponse(content=json_data,
                            content_type="application/json")
    except:
        return HttpResponse(content={},
                            content_type="application/json")
示例#15
0
def mapJsonTrack(request, uuid, downsample=False):
    TRACK_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_TRACK_MODEL)
    try:
        track = TRACK_MODEL.get().objects.get(uuid=uuid)
        json_data = json.dumps([track.toMapDict(downsample)], cls=DatetimeJsonEncoder)
        return HttpResponse(content=json_data,
                            content_type="application/json")
    except:
        traceback.print_exc()
        return HttpResponse(content={},
                            content_type="application/json")
示例#16
0
def editInstrumentData(request, instrument_name, pk):
    """
    Renders instrument data edit page -- if data exists, displays the existing data.
    """
    mapDict = settings.XGDS_MAP_SERVER_JS_MAP[instrument_name]
    INSTRUMENT_MODEL = LazyGetModelByName(mapDict['model'])
    dataProduct = INSTRUMENT_MODEL.get().objects.get(pk=pk)
    jsonDict = dataProduct.toMapDict()

    # get existing data.
    if 'edit_form_class' in mapDict:
        form = getFormByName(mapDict['edit_form_class'])(initial=jsonDict)
    else:
        form = BasaltInstrumentDataForm(initial=jsonDict)

    form.editingSetup(dataProduct)

    # convert to local time.
    utcTime = dataProduct.acquisition_time
    timezone = dataProduct.acquisition_timezone
    acquisitionTime = utcToTimeZone(utcTime, timezone)
    acquisitionTime = acquisitionTime.strftime('%m/%d/%Y %H:%M')

    form.fields['dataCollectionTime'].initial = acquisitionTime
    form.fields['timezone'].initial = timezone

    # hide the two file fields
    #     form.fields['portableDataFile'].widget = forms.HiddenInput()
    #     form.fields['manufacturerDataFile'].widget = forms.HiddenInput()
    #
    updateInstrumentDataUrl = reverse('instrument_data_update',
                                      kwargs={
                                          'instrument_name': instrument_name,
                                          'pk': pk
                                      })
    return render(
        request,
        'xgds_instrument/editInstrumentData.html',
        {
            'form': form,
            'instrument_name': instrument_name,
            'dataProductJson': json.dumps(jsonDict, cls=DatetimeJsonEncoder),
            'updateInstrumentDataUrl': updateInstrumentDataUrl,
            'manufacturer_data_file_url':
            dataProduct.manufacturer_data_file_url,
            'portable_data_file_url': dataProduct.portable_data_file_url
        },
    )
示例#17
0
    def save(self, commit=True):
        instance = super(ImportInstrumentDataForm, self).save(commit=False)
        if (('lat' in self.changed_data) and ('lon' in self.changed_data)) or ('alt' in self.changed_data):
            if instance.user_position is None:
                LOCATION_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_PAST_POSITION_MODEL)
                instance.user_position = LOCATION_MODEL.get().objects.create(serverTimestamp = datetime.datetime.now(pytz.utc),
                                                                             timestamp = instance.acquisition_time,
                                                                             latitude = self.cleaned_data['lat'],
                                                                             longitude = self.cleaned_data['lon'], 
                                                                             altitude = self.cleaned_data['alt'])
            else:
                instance.user_position.latitude = self.cleaned_data['lat']
                instance.user_position.longitude = self.cleaned_data['lon']
                instance.user_position.altitude = self.cleaned_data['alt']
                instance.user_position.save()

        if commit:
            instance.save()
        return instance
示例#18
0
def editInstrumentDataPosition(dataProduct, newLatitude, newLongitude, newAltitude):
    cleanLatitude = cleanValue(newLatitude)
    cleanLongitude = cleanValue(newLongitude)
    cleanAltitude = cleanValue(newAltitude)
    if not newLatitude or not newLongitude:
        return
    
    
    ''' create or update the user position for an instrument data reading '''
    if cleanLatitude != dataProduct.lat or cleanLongitude != dataProduct.lon or cleanAltitude != dataProduct.alt:
        if dataProduct.user_position is None:
            LOCATION_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_PAST_POSITION_MODEL)
            dataProduct.user_position = LOCATION_MODEL.get().objects.create(serverTimestamp = datetime.datetime.now(pytz.utc),
                                                                            timestamp = dataProduct.acquisition_time,
                                                                            latitude = cleanLatitude,
                                                                            longitude = cleanLongitude, 
                                                                            altitude = cleanAltitude)
        else:
            dataProduct.user_position.latitude = cleanLatitude
            dataProduct.user_position.longitude = cleanLongitude
            dataProduct.user_position.altitude = cleanAltitude
            dataProduct.user_position.save()
        dataProduct.save()
示例#19
0
    def startTracking(self):
        vehicle = self.getVehicle()

        protocol = None
        try:
            protocol = Constant.objects.get(name=vehicle.name +
                                            "_TRACKING_PROTO")
        except:
            # if there is no protocol, there should be no track.
            return

        #Create the track if it does not exist
        if not getattr(self, 'track'):
            TRACK_MODEL = LazyGetModelByName(settings.GEOCAM_TRACK_TRACK_MODEL)
            try:
                track = TRACK_MODEL.get().objects.get(name=self.name)
            except ObjectDoesNotExist:
                timezone = settings.TIME_ZONE
                if self.plans:
                    timezone = str(self.plans[0].plan.jsonPlan.site.
                                   alternateCrs.properties.timezone)
                    self.timezone = timezone
                track = TRACK_MODEL.get()(
                    name=self.name,
                    vehicle=vehicle,
                    timezone=timezone,
                    iconStyle=geocamTrackModels.IconStyle.objects.get(
                        uuid=vehicle.name),
                    lineStyle=geocamTrackModels.LineStyle.objects.get(
                        uuid=vehicle.name),
                    dataType=DataType.objects.get(name="RawGPSLocation"))
                track.save()
                self.track = track

                # this is for archival purposes; make sure remoteDelay is set for the other server's delay.
                delayConstant = Constant.objects.get(name="remoteDelay")
                self.delaySeconds = int(delayConstant.value)
                self.save()

        if settings.PYRAPTORD_SERVICE is True and protocol:
            pyraptord = getPyraptordClient()
            serviceName = self.vehicle.name + "TrackListener"
            ipAddress = Constant.objects.get(name=vehicle.name +
                                             "_TRACKING_IP")
            scriptPath = os.path.join(settings.PROJ_ROOT, 'apps', 'basaltApp',
                                      'scripts', 'evaTrackListener.py')
            command = "%s -o %s -p %d -n %s --proto=%s -t %s" % (
                scriptPath, ipAddress.value, vehicle.port,
                self.vehicle.name[-1:], protocol.value, self.name)
            stopPyraptordServiceIfRunning(pyraptord, serviceName)
            time.sleep(2)
            pyraptord.updateServiceConfig(serviceName, {'command': command})
            pyraptord.startService(serviceName)

            if self.vehicle.name in settings.COMPASS_EQUIPPED_VEHICLES:
                serviceName = self.vehicle.name + "CompassListener"
                port = Constant.objects.get(name="%s_COMPASS_PORT" %
                                            self.vehicle.name).value
                scriptPath = os.path.join(settings.PROJ_ROOT, 'apps',
                                          'basaltApp', 'scripts',
                                          'evaTrackListener.py')
                command = "%s -p %s -n %s -d compass --proto=%s -t %s" % (
                    scriptPath, port, self.vehicle.name[-1:], 'UDP', self.name)
                print "COMPASS: %s" % command
                stopPyraptordServiceIfRunning(pyraptord, serviceName)
                time.sleep(2)
                pyraptord.updateServiceConfig(serviceName,
                                              {'command': command})
                pyraptord.startService(serviceName)
示例#20
0
def getActiveFlights():
    ACTIVE_FLIGHTS_MODEL = LazyGetModelByName(settings.XGDS_PLANNER2_ACTIVE_FLIGHT_MODEL)
    return ACTIVE_FLIGHTS_MODEL.get().objects.all()
示例#21
0
def getInstrumentDataJson(request, productModel, productPk):
    INSTRUMENT_DATA_PRODUCT_MODEL = LazyGetModelByName(productModel)
    dataProduct = get_object_or_404(INSTRUMENT_DATA_PRODUCT_MODEL.get(), pk=productPk)
    sampleList = dataProduct.samples
    return HttpResponse(json.dumps(sampleList), content_type='application/json')
示例#22
0
XGDS_CORE_VEHICLE_MODEL = LazyGetModelByName(settings.XGDS_CORE_VEHICLE_MODEL)

XGDS_IMAGE_TEMPLATE_LIST = list(settings.XGDS_MAP_SERVER_HANDLEBARS_DIRS)
XGDS_IMAGE_TEMPLATE_LIST = XGDS_IMAGE_TEMPLATE_LIST + settings.XGDS_CORE_TEMPLATE_DIRS[
    settings.XGDS_IMAGE_IMAGE_SET_MODEL]

ARROW_ANNOTATION_MODEL = LazyGetModelByName(
    settings.XGDS_IMAGE_ARROW_ANNOTATION_MODEL)
ELLIPSE_ANNOTATION_MODEL = LazyGetModelByName(
    settings.XGDS_IMAGE_ELLIPSE_ANNOTATION_MODEL)
RECTANGLE_ANNOTATION_MODEL = LazyGetModelByName(
    settings.XGDS_IMAGE_RECTANGLE_ANNOTATION_MODEL)
TEXT_ANNOTATION_MODEL = LazyGetModelByName(
    settings.XGDS_IMAGE_TEXT_ANNOTATION_MODEL)
ANNOTATION_MANAGER = ModelCollectionManager(AbstractAnnotation, [
    ARROW_ANNOTATION_MODEL.get(),
    ELLIPSE_ANNOTATION_MODEL.get(),
    RECTANGLE_ANNOTATION_MODEL.get(),
    TEXT_ANNOTATION_MODEL.get()
])
CAMERA_MODEL = LazyGetModelByName(settings.XGDS_IMAGE_CAMERA_MODEL)

import couchdb


def getImageImportPage(request):
    # map plus image templates for now
    templates = get_handlebars_templates(XGDS_IMAGE_TEMPLATE_LIST,
                                         'XGDS_IMAGE_TEMPLATE_LIST')
    data = {
        'imageSetsJson': [],