def get_data2(request): #if request.method != 'POST' or not request.is_secure(): # return HttpResponseBadRequest("Request must be a HTTPS post!") #else: #if 'data' in request.POST: jsonObj = request.POST['Data'] jsonObj = jsonParse.cleanJSON(jsonObj) # Test Key Authentication try: userProf = UserProfile.objects.get(privAPIKey__exact = jsonObj['APIKey']) except ObjectDoesNotExist: return HttpResponseBadRequest("Bad Key! Your key is = \n%s" % jsonObj['APIKey']) retData = privacy.process_privacy(userProf.userID, jsonObj) #Get all Data for sensorID #Modify data based on name's access privleges #Find sensorID.owner's XML file and find rule for name and sensorID #Modify data of SensorID data = -1 return HttpResponse(retData)
def upload_rules(request): if request.method != 'POST' or not request.is_secure(): return HttpResponseBadRequest("Request must be a HTTPS post!") else: try: jsonObj = request.POST['Data'] except KeyError: return HttpResponseBadRequest("Your POST object didn't contain an item with a key = 'Data'") try: jsonObj = jsonParse.cleanJSON(jsonObj) except KeyError: return HttpResponseBadRequest("Your POST object didn't contain an item with a key = 'APIKey'") # Test Key Authentication try: userProf = UserProfile.objects.get(privAPIKey__exact = jsonObj['APIKey']) except ObjectDoesNotExist: return HttpResponseBadRequest("Bad Key! Your key is = \n%s" % jsonObj['APIKey']) # Add/Update these rules in database retVal = privacy_rules(jsonObj, userProf.userID) if retVal == 0: return HttpResponse("Rule Upload Succesful") else: return retVal
def upload_data(request): if request.method != 'POST' or not request.is_secure(): return HttpResponseBadRequest("Request must be a HTTPS post!") else: try: jsonObj = request.POST['Data'] except KeyError: HttResponseBadRequest("Your POST object didn't contain an item with a key = 'Data'") try: jsonObj = jsonParse.cleanJSON(jsonObj) except KeyError: HttResponseBadRequest("Your POST object didn't contain an item with a key = 'APIKey'") # Test Key Authentication try: userProf = UserProfile.objects.get(privAPIKey__exact = jsonObj['APIKey']) except ObjectDoesNotExist: return HttpResponseBadRequest("Bad Key! Your key is = \n%s" % jsonObj['APIKey']) # Make sure this user owns this SensorNode try: currSN = SensorNode.objects.get(id__exact = jsonObj['SensorNode']) if userProf.userID != currSN.owner: return HttpResponseBadRequest("You do not own this sensor and therefore cannot add data to it") except ObjectDoesNotExist: return HttpResponseBadRequest("Wave Seg Series must be created in web UI before adding data to it!") # Try to get the WSS by name instead of ID as above except ValueError: try: currSN = SensorNode.objects.filter(owner__exact = userProf.userID).get(name__exact = jsonObj['SensorNode']) if userProf.userID != currSN.owner: return HttpResponseBadRequest("You do not own this sensor and therefore cannot add data to it") except ObjectDoesNotExist: return HttpResponseBadRequest("Wave Seg Series must be created in web UI before adding data to it!") for seg in jsonObj['WaveSeg']: ws = WaveSeg() ws.sensorNode_id = currSN.id try: ws.valuesFormat = '''%s''' % json.dumps(seg['ValueBlobFormat']) currNodeChan = SensorChannel.objects.filter(sensorNode__exact = currSN).values_list('name', flat=True) for chan in seg['ValueBlobFormat']: if chan not in currNodeChan: return HttpResponseBadRequest("%s is not a known channel for sensor %s" % (chan, currSN)) except KeyError: return HttpResponseBadRequest("Could not find necessary ValueBlobFormat key") try: ws.values = '''%s''' % json.dumps(seg['ValueBlob']) except KeyError: return HttpResponseBadRequest("Could not find necessary ValueBlob key") try: if seg['SamplingInterval'] != None: ws.sampleInterval = float(seg['SamplingInterval']) isPeriodic = True else: isPeriodic = False except KeyError: isPeriodic = False try: wsST = float(seg['StartTime']) ws.startTime = epochToDjangoTime(wsST) except (KeyError, TypeError): try: timeVar = seg['ValueBlobFormat'].index('Time') except ValueError: timeVar = len(seg['ValuesBlobFormat']) wsST = float(seg['ValueBlob'][0][timeVar]) ws.startTime = epochToDjangoTime(wsST) try: ws.endTime = epochToDjangoTime(float(seg['EndTime'])) except (KeyError, TypeError): # Pull from the last value in Values or Calculate from start time and sample interval # Throw an error if you can't do one of the above two things if isPeriodic: ws.endTime = epochToDjangoTime(wsST + float(ws.sampleInterval) * len(seg['ValueBlob'])) else: try: timeVar = seg['ValueBlobFormat'].index('Time') except ValueError: timeVar = len(seg['ValueBlobFormat']) ws.endTime = epochToDjangoTime(float(seg['ValueBlob'][len(seg['ValueBlob']) - 1][timeVar])) try: if seg['StaticLocation'] != None: ws.staticLocationX = float(seg['StaticLocation']['X']) except KeyError: pass try: if seg['StaticLocation'] != None: ws.staticLocationY = float(seg['StaticLocation']['Y']) except KeyError: pass try: if seg['StaticLocation'] != None: ws.staticLocationH = float(seg['StaticLocation']['Z']) except KeyError: pass ws.save() # Add statistic calculations! # Check how many channels should be in each value set snChannels = SensorChannel.objects.order_by('id').filter(sensorNode__exact = currSN) #Set up list for statistics stats = [] nonNumericChanName = [] nonNumericChan = [] for chan in range(len(snChannels)): stats.append([]) if snChannels[chan].isNonNumeric: nonNumericChanName.append(snChannels[chan].name) nonNumericChan.append(snChannels[chan]) # For each value set check how many channels there are # If any value == NULL drop it numValues = len(seg['ValueBlobFormat']) idx = 0 for valSet in seg['ValueBlob']: if len(valSet) < numValues or len(valSet) > numValues + 4: return HttpResponseBadRequest("JSON Object not properly formatted") for chan in range(numValues): if valSet[chan] != 'NULL' and valSet[chan] != None: try: stats[chan].append(float(valSet[chan])) except ValueError: if seg['valueBlobFormat'][idx] not in nonNumericChanName: return HttpResponseBadRequest('All Values Must Be Numerical!!!') else: nameIDX = nonNumericChanName.index(seg['valueBlobFormat'][idx]) currEnum = json.loads(nonNumericChan[nameIDX].nonNumericEnum) if valSet[chan] not in currEnum: valSet[chan] = 'Null' else: enumIDX = currEnum.index(valSet[chan]) valSet[chan] = enumIDX stats[chan] = enumIDX except IndexError: return HttpResponseBadRequest('Too Many Channels for this Wave Segment Series') # There can be up to 4 extra channels that correspond to Time, X, Y, Z # If location changes there must at least be a NULL place holder for time if len(valSet) > numValues: for chan in range(numValues, len(valSet)): if valSet[chan] != 'NULL' and valSet[chan] != None: try: stats[chan].append(float(valSet[chan])) except ValueError: if seg['valueBlobFormat'][idx] not in nonNumericChanName: return HttpResponseBadRequest('All Values Must Be Numerical!!!') else: nameIDX = nonNumericChanName.index(seg['valueBlobFormat'][idx]) currEnum = json.loads(nonNumericChan[nameIDX].nonNumericEnum) if valSet[chan] not in currEnum: valSet[chan] = 'Null' else: enumIDX = currEnum.index(valSet[chan]) valSet[chan] = enumIDX stats[chan] = enumIDX except IndexError: return HttpResponseBadRequest('Too Many Channels for this Wave Segment Series') idx += 1 # This is for when the previous for-loop updates ValueBlob ws.values = '''%s''' % json.dumps(seg['ValueBlob']) ws.save() # Calc Stats for each channel for chan in range(len(stats)): currSN = snChannels[0].sensorNode if chan < numValues: chanID = SensorChannel.objects.order_by('id').filter(sensorNode__exact = currSN).get(name__exact = seg['ValueBlobFormat'][chan]) else: over = chan - len(snChannels) if over == 0: chanID = SensorChannel.objects.order_by('id').filter(sensorNode__exact = currSN).get(name__exact = 'Time') elif over == 1: chanID = SensorChannel.objects.order_by('id').filter(sensorNode__exact = currSN).get(name__exact = 'X') elif over == 2: chanID = SensorChannel.objects.order_by('id').filter(sensorNode__exact = currSN).get(name__exact = 'Y') elif over == 3: chanID = SensorChannel.objects.order_by('id').filter(sensorNode__exact = currSN).get(name__exact = 'Z') newStat = Statistics() newStat.waveSegID = ws newStat.channelID = chanID if newStat.channelID.isNonNumeric: data = {} for i in range(len(stats[chan])): if stats[chan][i] in data: data[stats[chan][i]] += 1 else: data[stats[chan][i]] = 1 sortData = sorted(data.iteritems(), key=lambda (k,v): (v,k)) newStatNN = StatisticsNonNumeric() newStatNN.waveSegID = ws newStatNN.channelID = chanID newStatNN.sortedData = sortData newStatNN.save() else: chanStats = numpy.array(stats[chan]) if chanStats.size > 0: newStat.min = chanStats.min() newStat.max = chanStats.max() newStat.mean = chanStats.mean() newStat.median = numpy.median(chanStats) newStat.std = chanStats.std() newStat.save() return HttpResponse("Data Upload Succesful")