def weatherSense(startDateTime, hostIP, BASE_PORT, streaming=True, logging=True): global agiType global agiIndx global agiStatus i2c = BME280Init(0x77, 2) calib = BME280Calib(i2c) server_address = (hostIP, BASE_PORT) startTimeDT = rNTPTime.stripDateTime(startDateTime) weatherFileName = BASE_PATH+"Relay_Station{0}/Weather/Weather{1}.txt".format(BASE_PORT, startTimeDT) weatherMessage = [] with open(weatherFileName, "w") as weatherFile: weatherFile.write(startDateTime+"\n") weatherFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) weatherFile.write("Timestamp,Temperature,Pressure,Humidity\n") weatherFile.close() startTime = datetime.datetime.now() iterations = -1 sumHum = 0 sumPres = 0 sumTemp = 0 dummyvar = 0 while True: if iterations >= FILE_LENGTH: # update BS and get current time sumHum = sumHum/dummyvar sumPres = sumPres/dummyvar sumTemp = sumTemp/dummyvar weatherMessage = [] weatherMessage.append("Weather") weatherMessage.append(str("{0:.3f}".format(sumHum))) weatherMessage.append(str("{0:.3f}".format(sumPres))) weatherMessage.append(str("{0:.3f}".format(sumTemp))) startDateTime = rNTPTime.sendUpdate(server_address, weatherMessage, 5) #agiIndx = update[0] #agiType = update[1] #if agiType!=0: # agiStatus = True #else: # agiStatus = False #startDateTime = update[2] #startDateTime = rNTPTime.sendUpdate(server_address, iterations, sensorMessage, sumHum, sumPres, sumTemp, 0, 5) iterations = -1 sumHum = 0 sumPres = 0 sumTemp = 0 dummyvar = 0 if startDateTime != None: startTimeDT = rNTPTime.stripDateTime(startDateTime) #startTimeDT = datetime.datetime.now() weatherFileName = BASE_PATH+"Relay_Station{0}/Weather/Weather{1}.txt".format(BASE_PORT, startTimeDT) with open(weatherFileName, "w") as weatherFile: weatherFile.write(startDateTime+"\n") weatherFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) weatherFile.write("Timestamp,Temperature,Pressure,Humidity\n") startTime = datetime.datetime.now() # every UPDATE_LENGTH send update to BS elif (iterations % UPDATE_LENGTH) == (UPDATE_LENGTH - 2): sumHum = sumHum/UPDATE_LENGTH sumPres = sumPres/UPDATE_LENGTH sumTemp = sumTemp/UPDATE_LENGTH weatherMessage = [] weatherMessage.append("Weather") weatherMessage.append(str("{0:.3f}".format(sumHum))) weatherMessage.append(str("{0:.3f}".format(sumPres))) weatherMessage.append(str("{0:.3f}".format(sumTemp))) # weatherMessage.append(str(sumHum)) # weatherMessage.append(str(sumPres)) # weatherMessage.append(str(sumTemp)) startDateTime = rNTPTime.sendUpdate(server_address, weatherMessage, 5) #agiIndx = update[0] #agiType = update[1] #if agiType!=0: # agiStatus = True #else: # agiStatus = False #startDateTime = update[2] #rNTPTime.sendUpdate(server_address, iterations, sensorMessage, sumHum, sumPres, sumTemp, 0, 5) sumHum = 0 sumPres = 0 sumTemp = 0 dummyvar = 0 iterations += 1 dummyvar += 1 # calculate time since start currTime = datetime.datetime.now() currTimeDelta = (currTime - startTime).days * 86400 + (currTime - startTime).seconds + (currTime - startTime).microseconds / 1000000.0 # read sensor data over I2C (temp,t_fine) = readTemp(i2c, calib) pressure = readPressure(i2c, calib, t_fine) humidity = readHumidity(i2c, calib, t_fine) with open(weatherFileName, "a") as weatherFile: weatherFile.write("{0:.2f},{1:.2f},{2:.2f},{3:.2f},\n".format(currTimeDelta, temp, pressure, humidity)) sumHum = sumHum + humidity sumPres = sumPres + pressure sumTemp = sumTemp + temp time.sleep(LOOP_DELAY * UPDATE_DELAY)
def audioFeatureExt(startDateTime, hostIP, BASE_PORT): time.sleep((LOOP_DELAY * UPDATE_DELAY)) #Heartbeat stuff server_address = (hostIP, BASE_PORT) audioMessage = [] sumAudio = 0 sumAudioFeat = 0 iterations = 0 startLine = 3 #from rawADC - line0 = header, line1 = time, line2 = description aSamplingFreq = 10000 winSize = 0.250 #sec winStep = 0.125 #sec audioBuffer = ["0"] startTimeDT = rNTPTime.stripDateTime(startDateTime) audioFeatureFileName = BASE_PATH + "Relay_Station{0}/AudioF/AudioF{1}.txt".format( BASE_PORT, startTimeDT) with open(audioFeatureFileName, "w") as audioFeatureFile: audioFeatureFile.write(startDateTime + "\n") audioFeatureFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) audioFeatureFile.write( "Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, , ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n" ) #audioFeatureFile.write("Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, , ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n") audioFeatureFile.close() currLine = startLine #current line to read/write from while True: startTimeDT = rNTPTime.stripDateTime(startDateTime) rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/rawADC{1}.txt".format( BASE_PORT, startTimeDT) rawlineCount = 0 for line in open(rawADCFileName).xreadlines(): rawlineCount += 1 # close(rawADCFileName) # print "2017-08-07 %d%d:%d%d:%d%d.000" %(1,1,1,1,1,1) # if startTimeDT != rawADC_Time: # print "FileChanged!!!! # print "rawADC Size = ", rawlineCount, ", AudioFeature Size = ",currLine, ", rawADCTime = ", rawADC.rawADC_Time, ", AudioFileTime = ", startTimeDT if rawlineCount > currLine: with open(rawADCFileName, "r") as rawADCFile: rawADC_string = rawADCFile.readlines()[currLine] # rawADCFile.close() rawADC_Data = rawADC_string.split(',') timeDelta = float(rawADC_Data[0]) # audioData = rawADC_Data[1:10001] # doorData1 = rawADC_Data[10001:10011] # doorData2 = rawADC_Data[10011:10021] # tempF = float(rawADC_Data[-1]) if len(rawADC_Data[1:10001]) == 10000: # audioFeatureExtraction.stFeatureExtraction(data, Fs, window, step) # F = audioFeatureExtraction.stFeatureExtraction(rawADC_Data[1:10001], aSamplingFreq, # winSize*aSamplingFreq, winStep*aSamplingFreq) if len(audioBuffer) >= 1250: # F = audioFeatureExtraction.stFeatureExtraction( audioBuffer + rawADC_Data[1:10001], aSamplingFreq, winSize * aSamplingFreq, winStep * aSamplingFreq) timeDelta = timeDelta - 0.125 else: #no audio buffer - first run - just create a new file F = audioFeatureExtraction.stFeatureExtraction( rawADC_Data[1:10001], aSamplingFreq, winSize * aSamplingFreq, winStep * aSamplingFreq) audioBuffer = rawADC_Data[8751:10001] with open(audioFeatureFileName, "a") as audioFeatureFile: for i in range(0, 7): timeStepDelta = winStep * i audioFeatureFile.write("%0.4f," % (timeDelta + timeStepDelta)) audioFeatureFile.write("%f," % (F[0, i])) audioFeatureFile.write("%f," % (F[1, i])) audioFeatureFile.write("%f," % (F[2, i])) audioFeatureFile.write("%f," % (F[3, i])) audioFeatureFile.write("%f," % (F[4, i])) audioFeatureFile.write("%f," % (F[5, i])) audioFeatureFile.write("%f," % (F[6, i])) audioFeatureFile.write("%f," % (F[7, i])) audioFeatureFile.write( "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f," % (F[8, i], F[9, i], F[10, i], F[11, i], F[12, i], F[13, i], F[14, i], F[15, i], F[16, i], F[17, i], F[18, i], F[19, i], F[20, i])) audioFeatureFile.write( "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f," % (F[21, i], F[22, i], F[23, i], F[24, i], F[25, i], F[26, i], F[27, i], F[28, i], F[29, i], F[30, i], F[31, i], F[32, i])) audioFeatureFile.write("%f\n" % (F[33, i])) sumAudio += float(F[2, i]) #data for HEART BEAT sumAudioFeat += float(F[3, i]) audioFeatureFile.close() sumAudio = sumAudio / 7 # there's 7 windows in 1 sec sumAudioFeat = sumAudioFeat / 7 iterations += 1 currLine = currLine + 1 #move to the next Audio line #if finish audioFeature Ext + rawADC creates a new file elif rawADC.rawADC_Time != startTimeDT: rawlineCount = 0 for line in open(rawADCFileName).xreadlines(): rawlineCount += 1 if rawlineCount == currLine: startDateTime = rawADC.rawADC_startDateTime startTimeDT = str(rawADC.rawADC_Time) audioFeatureFileName = BASE_PATH + "Relay_Station{0}/AudioF/AudioF{1}.txt".format( BASE_PORT, startTimeDT) # create new audioFeatureFile with open(audioFeatureFileName, "w") as audioFeatureFile: audioFeatureFile.write(startDateTime + "\n") audioFeatureFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) audioFeatureFile.write( "Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, , ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n" ) audioFeatureFile.close() currLine = startLine # print "new File Created" #update new rawADC filename to open rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/rawADC{1}.txt".format( BASE_PORT, startTimeDT) if iterations >= UPDATE_LENGTH: sumAudio = sumAudio / iterations iterations = 0 audioMessage = [] audioMessage.append("Audio") audioMessage.append(str("{0:.3f}".format(sumAudio))) #Energy audioMessage.append(str("{0:.3f}".format(sumAudioFeat))) #Teager tempDateTime = rNTPTime.sendUpdate( server_address, audioMessage, 5) #Audio uses startDateTime from rawADC sumAudio = 0 sumAudioFeat = 0
def message_log(self,data): global agiType global agiStatus global server_address global batteryStatus global meminifilename #global filename #print("markerCount = {}, responseCount = {}".format(self.markerCount,self.responseCount)) dataTypes = [] buttonIds = [] clickTypes = [] timeStamps = [] batteryStatuses = [] if self.markerCount>0: markerIds = [] #markerTimes = [] for k in range(self.markerCount): dataTypes.append( "MARKER" ) batteryStatuses.append(batteryStatus) if (KEY_MARKER_ID_TO_PHONE+k) in data: markerId = data[KEY_MARKER_ID_TO_PHONE+k] markerIds.append(markerId) buttonId,clickType = decode_click_id(markerId) #print("click:{},{}".format(buttonId,clickType)) buttonIds.append(buttonId) clickTypes.append(clickType) if (KEY_MARKER_TIME_TO_PHONE+k) in data: timeStamps.append(data[KEY_MARKER_TIME_TO_PHONE+k]) #print("timestamps:{}".format(timeStamps)) #mementoMessage = [] #mementoMessage.append("Memento") #mementoMessage.append(datetime.datetime.fromtimestamp(timeStamps[-1]).strftime("%Y-%m-%d %H:%M:%S")) #if not batteryStatuses: # mementoMessage.append(str(000)) #else: # mementoMessage.append(str(batteryStatuses[-1])) #print mementoMessage[1] #startDateTime = rNTPTime.sendUpdate(server_address, mementoMessage, 5) if self.responseCount>0: responseIds = [] for k in range(self.responseCount): dataTypes.append( "RESPONSE" ) batteryStatuses.append(batteryStatus) if (KEY_RESPONSE_ID_TO_PHONE+k) in data: responseId = data[KEY_RESPONSE_ID_TO_PHONE+k] responseIds.append(responseId) buttonId,clickType = decode_click_id(responseId) buttonIds.append(buttonId) clickTypes.append(clickType) if (KEY_RESPONSE_TIME_TO_PHONE+k) in data: timeStamps.append(data[KEY_RESPONSE_TIME_TO_PHONE+k]) agiType = 0 agiMessage = [] agiMessage.append("Agitation") agiMessage.append(str(agiType)) agiMessage.append(str(0)) startDateTime = rNTPTime.sendUpdate(server_address, agiMessage, 5) #print("timestamps:{}".format(timeStamps)) if self.batteryCharge>=0: dataTypes.append( "BATTERY" ) batteryStatus = self.batteryCharge batteryStatuses.append(batteryStatus) buttonIds.append("-") clickTypes.append("-") timeStamps.append(data[BATTERY_TIME_TO_PHONE]) if self.markerCount>0: mementoMessage = [] mementoMessage.append("Memento") mementoMessage.append(str(timeStamps[-1])) #(datetime.datetime.fromtimestamp(timeStamps[-1]).strftime("%Y-%m-%d %H:%M:%S")) if not batteryStatuses: mementoMessage.append(str(000)) else: mementoMessage.append(str(batteryStatuses[-1])) print mementoMessage[1] startDateTime = rNTPTime.sendUpdate(server_address, mementoMessage, 5) try: #print(dataTypes) #print(timeStamps) #print(buttonIds) #print(clickTypes) #print(batteryStatuses) with open(meminifilename,'a') as dataFile: for k in range(len(dataTypes)): dataFile.write("{0},{1},{2},{3},{4}\n" \ .format(dataTypes[k],timeStamps[k],buttonIds[k],clickTypes[k],batteryStatuses[k])) if dataTypes[k] == "RESPONSE": pebbleMessage = [] pebbleMessage.append("pebbleResp") #update btn response to basestaion if buttonIds[k] == "Back": pebbleMessage.append("NO") else: pebbleMessage.append("YES") temp = rNTPTime.checkNoti(server_address[0], pebbleMessage, 5) elif dataTypes[k] == "MARKER": pebbleMessage = [] pebbleMessage.append("eventMark") #update btn response to basestaion temp = rNTPTime.checkNoti(server_address[0], pebbleMessage, 5) return True except: print("Error in writing!") return False
def motionFeatExt(startDateTime, hostIP, BASE_PORT, pebbleFolder): x = [] y = [] z = [] max_x_values = [] min_x_values = [] mean_x_values = [] max_y_values = [] min_y_values = [] mean_y_values = [] max_z_values = [] min_z_values = [] mean_z_values = [] iterations = 0 HB_Pixie_Value = 0 server_address = (hostIP, BASE_PORT) #Fs = 50.0; # sampling rate #Ts = 1.0/Fs; # sampling interval #t = numpy.arange(0,1,Ts) # time vector while True: # f = open('C:\Users\jah4yq\Downloads\pebble_data_1504247643122.csv',"r") #f = open('C:\Users\jah4yq\Downloads\pebble_data_1504251277808.csv',"r") #f = open('/media/card/r101.csv',"r") # Get file name to open files = os.walk(BASE_PATH + pebbleFolder + "/").next()[2] #BASE_PATH = /media/card/ files.sort() #previous file first if ( len(files) >= 2 ): #need more than 2 files -> previous one is finished recording pebble data print "reading Motion from " + files[0] f = open(BASE_PATH + pebbleFolder + "/" + files[0], "r") #f = open('/media/card/pebble_data_XXXXXX.csv',"r") rawlineCount = 0 for numLines in f.xreadlines(): rawlineCount += 1 # read #of lines f.close() f = open(BASE_PATH + pebbleFolder + "/" + files[0], "r") line = f.readline( ) #line pointer at the first line: "z,y,x,offset,timestamp" for q in range(rawlineCount): line = f.readline() # line pointer at the first DATA line count = 1 #print line num = line.split(',') # print num # print num[0] if len(num) >= 5: z.append(int(num[0])) y.append(int(num[1])) x.append(int(num[2])) # for i in line.split(','): # #print i, # try: # num = int(i) # if count==1: # z.append(num) # elif count==2: # y.append(num) # elif count==3: # x.append(num) # count += 1 # except: # print "err converting num = int(i)" f.close() #finished reading all lines x.append(0) y.append(0) z.append(0) #Generate destination file #Convert Epoch time -> readable Time dstFileTime = files[0].split('_') dstFileTime = dstFileTime[2].split('.') dstFileTime = datetime.datetime.fromtimestamp( int(dstFileTime[0]) / 1000).strftime('%y-%m-%d_%H-%M-%S') PebbleFeatureFileName = BASE_PATH + "Relay_Station{0}/PebbleFeature/PebbleFeature{1}.txt".format( BASE_PORT, dstFileTime) with open(PebbleFeatureFileName, "w") as PebbleFeatureFile: PebbleFeatureFile.write(dstFileTime + "\n") PebbleFeatureFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format( BASE_PORT)) PebbleFeatureFile.write( "x_max,x_min,x_mean,x_std,x_fft_mean,x_fft_0_1_max,x_fft_1_3_max,x_fft_3_10_max,x_teager_mean,x_teager_max,y_max,y_min,y_mean,y_std,y_fft_mean,y_fft_0_1_max,y_fft_1_3_max,y_fft_3_10_max,y_teager_mean,y_teager_max,z_max,z_min,z_mean,z_std,z_fft_mean,z_fft_0_1_max,z_fft_1_3_max,z_fft_3_10_max,z_teager_mean,z_teager_max\n " ) # PebbleFeatureFile.close() # f = open('C:\Users\jah4yq\Downloads\pebble_data_accel_features.csv',"w") # f.write(str("x_max") + ", " +str("x_min") + ", " + str("x_mean") + ", " + str("x_std") + ", " + str("x_fft_mean") + ", " + str("x_fft_0_1_max") + ", " + str("x_fft_1_3_max") + ", " + str("x_fft_3_10_max") + ", " + str("x_teager_mean") + ", " + str("x_teager_max") + ", " + str("y_max") + ", " +str("y_min") + ", " + str("y_mean") + ", " + str("y_std") + ", " + str("y_fft_mean") + ", " + str("y_fft_0_1_max") + ", " + str("y_fft_1_3_max") + ", " + str("y_fft_3_10_max") + ", " + str("y_teager_mean") + ", " + str("y_teager_max") + ", " + str("z_max") + ", " + str("z_min") + ", " + str("z_mean") + ", " + str("z_std") + ", " + str("z_fft_mean") + ", " + str("z_fft_0_1_max") + ", " + str("z_fft_1_3_max") + ", " + str("z_fft_3_10_max") + ", " + str("z_teager_mean") + ", " + str("z_teager_max") + "\n ") for m in range(rawlineCount / 1500 - 1): lower_lim = 1500 * m upper_lim = 1500 * m + 2999 x_max = max(x[lower_lim:upper_lim]) x_min = min(x[lower_lim:upper_lim]) x_mean = numpy.mean(x[lower_lim:upper_lim]) x_std = numpy.std(x[lower_lim:upper_lim], ddof=1) Fs = 50.0 # sampling rate Ts = 1.0 / Fs # sampling interval t = numpy.arange(0, 1, Ts) # time vector n = 3000 # length of the signal k = numpy.arange(n) T = n / Fs frq = k / T # two sides frequency range frq = frq[range(n / 2)] # one side frequency range X = numpy.fft.fft(x[lower_lim:upper_lim] ) / n # fft computing and normalization X = X[range(n / 2)] X = numpy.absolute(X) X = list(X) i1 = X.index( max(numpy.absolute(X[1:60])) ) #finds the index of the max fft magnitude between 0&1 Hz i2 = X.index( max(numpy.absolute(X[61:180])) ) #finds the index of the max fft magnitude between 1&3 Hz i3 = X.index( max(numpy.absolute(X[181:600])) ) #finds the index of the max fft magnitude between 3&10 Hz x_fft_0_1_max = frq[i1] x_fft_1_3_max = frq[i2] x_fft_3_10_max = frq[i3] X_sum = sum(X) X_mag = sum(numpy.multiply(X, frq)) x_fft_mean = X_sum / X_mag y_max = max(y[lower_lim:upper_lim]) y_min = min(y[lower_lim:upper_lim]) y_mean = numpy.mean(y[lower_lim:upper_lim]) y_std = numpy.std(y[lower_lim:upper_lim], ddof=1) Y = numpy.fft.fft(y[lower_lim:upper_lim] ) / n # fft computing and normalization Y = Y[range(n / 2)] Y = numpy.absolute(Y) Y = list(Y) i1 = Y.index( max(numpy.absolute(Y[1:60])) ) #finds the index of the max fft magnitude between 0&1 Hz i2 = Y.index( max(numpy.absolute(Y[61:180])) ) #finds the index of the max fft magnitude between 1&3 Hz i3 = Y.index( max(numpy.absolute(Y[181:600])) ) #finds the index of the max fft magnitude between 3&10 Hz y_fft_0_1_max = frq[i1] y_fft_1_3_max = frq[i2] y_fft_3_10_max = frq[i3] Y_sum = sum(Y) Y_mag = sum(numpy.multiply(Y, frq)) y_fft_mean = Y_sum / Y_mag z_max = max(z[lower_lim:upper_lim]) z_min = min(z[lower_lim:upper_lim]) z_mean = numpy.mean(z[lower_lim:upper_lim]) z_std = numpy.std(z[lower_lim:upper_lim], ddof=1) Z = numpy.fft.fft(z[lower_lim:upper_lim] ) / n # fft computing and normalization Z = Z[range(n / 2)] Z = numpy.absolute(Z) Z = list(Z) i1 = Z.index( max(numpy.absolute(Z[1:60])) ) #finds the index of the max fft magnitude between 0&1 Hz i2 = Z.index( max(numpy.absolute(Z[61:180])) ) #finds the index of the max fft magnitude between 1&3 Hz i3 = Z.index( max(numpy.absolute(Z[181:600])) ) #finds the index of the max fft magnitude between 3&10 Hz z_fft_0_1_max = frq[i1] z_fft_1_3_max = frq[i2] z_fft_3_10_max = frq[i3] Z_sum = sum(Z) Z_mag = sum(numpy.multiply(Z, frq)) z_fft_mean = Z_sum / Z_mag x_teager = [] y_teager = [] z_teager = [] for g in range(3000): if g == 0: xx = (x[g + lower_lim]) ^ 2 yy = (y[g + lower_lim]) ^ 2 zz = (z[g + lower_lim]) ^ 2 elif g != 0: xx = ( x[g + lower_lim] ) ^ 2 - (x[g + lower_lim - 1]) * (x[g + lower_lim + 1]) yy = ( y[g + lower_lim] ) ^ 2 - (y[g + lower_lim - 1]) * (y[g + lower_lim + 1]) zz = ( z[g + lower_lim] ) ^ 2 - (z[g + lower_lim - 1]) * (z[g + lower_lim + 1]) #xx=(x[g+lower_lim])^2 #yy=(y[g+lower_lim])^2 #zz=(z[g+lower_lim])^2 x_teager.append(xx) y_teager.append(yy) z_teager.append(zz) x_teager_max = max(x_teager) x_teager_mean = numpy.mean(x_teager) y_teager_max = max(y_teager) y_teager_mean = numpy.mean(y_teager) z_teager_max = max(z_teager) z_teager_mean = numpy.mean(z_teager) HB_Pixie_Value = x_max # f.write(str(x_max) + ", " +str(x_min) + ", " + str(x_mean) + ", " + str(x_std) + ", " + str(x_fft_mean) + ", " + str(x_fft_0_1_max) + ", " + str(x_fft_1_3_max) + ", " + str(x_fft_3_10_max) + ", " + str(x_teager_mean) + ", " + str(x_teager_max) + ", " + str(y_max) + ", " +str(y_min) + ", " + str(y_mean) + ", " + str(y_std) + ", " + str(y_fft_mean) + ", " + str(y_fft_0_1_max) + ", " + str(y_fft_1_3_max) + ", " + str(y_fft_3_10_max) + ", " + str(y_teager_mean) + ", " + str(y_teager_max) + ", " + str(z_max) + ", " + str(z_min) + ", " + str(z_mean) + ", " + str(z_std) + ", " + str(z_fft_mean) + ", " + str(z_fft_0_1_max) + ", " + str(z_fft_1_3_max) + ", " + str(z_fft_3_10_max) + ", " + str(z_teager_mean) + ", " + str(z_teager_max) + "\n ") with open(PebbleFeatureFileName, "a") as PebbleFeatureFile: PebbleFeatureFile.write( str(x_max) + ", " + str(x_min) + ", " + str(x_mean) + ", " + str(x_std) + ", " + str(x_fft_mean) + ", " + str(x_fft_0_1_max) + ", " + str(x_fft_1_3_max) + ", " + str(x_fft_3_10_max) + ", " + str(x_teager_mean) + ", " + str(x_teager_max) + ", " + str(y_max) + ", " + str(y_min) + ", " + str(y_mean) + ", " + str(y_std) + ", " + str(y_fft_mean) + ", " + str(y_fft_0_1_max) + ", " + str(y_fft_1_3_max) + ", " + str(y_fft_3_10_max) + ", " + str(y_teager_mean) + ", " + str(y_teager_max) + ", " + str(z_max) + ", " + str(z_min) + ", " + str(z_mean) + ", " + str(z_std) + ", " + str(z_fft_mean) + ", " + str(z_fft_0_1_max) + ", " + str(z_fft_1_3_max) + ", " + str(z_fft_3_10_max) + ", " + str(z_teager_mean) + ", " + str(z_teager_max) + "\n ") files = os.walk(BASE_PATH + pebbleFolder + "/").next()[2] #BASE_PATH = /media/card/ files.sort() #previous file first if ( len(files) >= 2 ): #need more than 2 files -> previous one is finished recording pebble data f = open( BASE_PATH + pebbleFolder + "/" + files[0], "r") #f = open('/media/card/pebble_data_XXXXXX.csv',"r") src = BASE_PATH + pebbleFolder + "/" + files[0] dst = BASE_PATH + "Relay_Station" + str( BASE_PORT) + "/rawPebble/" + files[0] # dst = "/media/card/Relay_Station10000/" + "rawPebble/" + files[0] shutil.move(src, dst) pixieMessage = [] pixieMessage.append("Pixie") pixieMessage.append(str("{0:.3f}".format(z_teager_max))) tempDateTime = rNTPTime.sendUpdate(server_address, pixieMessage, 5) else: # no new pebble motion data file time.sleep(5)
def audioFeatureExt(): # def audioFeatureExt(startDateTime, hostIP, BASE_PORT): debugMode = True time.sleep((LOOP_DELAY * UPDATE_DELAY)) hostIP, BASE_PORT = readConfigFile() #Heartbeat stuff server_address = (hostIP, BASE_PORT) # startDateTime = rNTPTime.sendUpdate(server_address, "-99", 10) # if startDateTime != None: # # use custom function because datetime.strptime fails in multithreaded applications # startTimeDT = rNTPTime.stripDateTime(startDateTime) # else: # while(startDateTime == None): # startDateTime = rNTPTime.sendUpdate(server_address, "-99", 10) # time.sleep(5) # print "connection to base station timed out" # startTimeDT = rNTPTime.stripDateTime(startDateTime) audioMessage = [] sumAudio = 0 sumAudioFeat = 0 iterations = 0 startLine = 3 #from rawADC - line0 = header, line1 = time, line2 = description aSamplingFreq = 10000 winSize = 0.250 #sec winStep = 0.125 #sec audioBuffer = ["0"] # startTimeDT = rNTPTime.stripDateTime(startDateTime) # audioFeatureFileName = BASE_PATH+"Relay_Station{0}/AudioF/AudioF{1}.txt".format(BASE_PORT, startTimeDT) # with open(audioFeatureFileName, "w") as audioFeatureFile: # audioFeatureFile.write(startDateTime+"\n") # audioFeatureFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) # audioFeatureFile.write("Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n") # #audioFeatureFile.write("Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, , ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n") # audioFeatureFile.close() currLine = startLine #current line to read/write from print "Starting Audio Thread" while True: # startTimeDT = rNTPTime.stripDateTime(startDateTime) rawADCLocation = BASE_PATH + "Relay_Station{0}/rawADC/".format( BASE_PORT) files = os.walk(rawADCLocation).next()[2] #BASE_PATH = /media/card/ files.sort() #previous file first rawlineCount = 0 # print files if (len(files) > 0): #not an empty folder rawADC_timeStamp = files[0][ 6:-4] # read timeStamp on rawADC filename rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/".format( BASE_PORT) + "/" + files[0] #create new audio feature file audioFeatureFileName = BASE_PATH + "Relay_Station{0}/AudioF/AudioF{1}.txt".format( BASE_PORT, rawADC_timeStamp) if not os.path.exists(audioFeatureFileName): with open(audioFeatureFileName, "w") as audioFeatureFile: audioFeatureFile.write(rawADC_timeStamp + "\n") audioFeatureFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) audioFeatureFile.write( "Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n" ) if debugMode: print "reading lines from " + files[0] f = open( BASE_PATH + "Relay_Station{0}/rawADC/".format(BASE_PORT) + "/" + files[0], "r") rawlineCount = 0 for line in f.xreadlines(): rawlineCount += 1 f.close() if debugMode: print "rawlineCount =" + str(rawlineCount) if debugMode: print "currLine =" + str(currLine) # close(rawADCFileName) # print "2017-08-07 %d%d:%d%d:%d%d.000" %(1,1,1,1,1,1) # if startTimeDT != rawADC_Time: # print "FileChanged!!!! # print "rawADC Size = ", rawlineCount, ", AudioFeature Size = ",currLine, ", rawADCTime = ", rawADC.rawADC_Time, ", AudioFileTime = ", startTimeDT # if False: if rawlineCount > currLine: rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/".format( BASE_PORT) + "/" + files[0] with open(rawADCFileName, "r") as rawADCFile: rawADC_string = rawADCFile.readlines()[currLine:rawlineCount] # rawADCFile.close() for j in range(len(rawADC_string)): rawADC_Data = rawADC_string[j].split(',') timeDelta = float(rawADC_Data[0]) # audioData = rawADC_Data[1:10001] # doorData1 = rawADC_Data[10001:10011] # doorData2 = rawADC_Data[10011:10021] # tempF = float(rawADC_Data[-1]) if debugMode: print "len rawADC Data = " + str(len(rawADC_Data[1:10001])) if (len(rawADC_Data[1:10001]) < 10000) and (currLine == ( rawlineCount - 1)): #rawADC file fault - last line bugged rawADCLocation = BASE_PATH + "Relay_Station{0}/rawADC/".format( BASE_PORT) files = os.walk(rawADCLocation).next()[ 2] #BASE_PATH = /media/card/ files.sort() #previous file first if len(files) >= 2: # currLine = currLine + 1 currLine = rawlineCount if debugMode: print "Last line bugged - move to next file" if len(rawADC_Data[1:10001]) == 10000: # audioFeatureExtraction.stFeatureExtraction(data, Fs, window, step) # F = audioFeatureExtraction.stFeatureExtraction(rawADC_Data[1:10001], aSamplingFreq, # winSize*aSamplingFreq, winStep*aSamplingFreq) if len(audioBuffer) >= 1250: # F = audioFeatureExtraction.stFeatureExtraction( audioBuffer + rawADC_Data[1:10001], aSamplingFreq, winSize * aSamplingFreq, winStep * aSamplingFreq) timeDelta = timeDelta - 0.125 else: #no audio buffer - first run - just create a new file F = audioFeatureExtraction.stFeatureExtraction( rawADC_Data[1:10001], aSamplingFreq, winSize * aSamplingFreq, winStep * aSamplingFreq) audioBuffer = rawADC_Data[8751:10001] with open(audioFeatureFileName, "a") as audioFeatureFile: for i in range(0, 7): timeStepDelta = winStep * i audioFeatureFile.write("%0.4f," % (timeDelta + timeStepDelta)) audioFeatureFile.write("%f," % (F[0, i])) audioFeatureFile.write("%f," % (F[1, i])) audioFeatureFile.write("%f," % (F[2, i])) audioFeatureFile.write("%f," % (F[3, i])) audioFeatureFile.write("%f," % (F[4, i])) audioFeatureFile.write("%f," % (F[5, i])) audioFeatureFile.write("%f," % (F[6, i])) audioFeatureFile.write("%f," % (F[7, i])) audioFeatureFile.write( "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f," % (F[8, i], F[9, i], F[10, i], F[11, i], F[12, i], F[13, i], F[14, i], F[15, i], F[16, i], F[17, i], F[18, i], F[19, i], F[20, i])) audioFeatureFile.write( "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f," % (F[21, i], F[22, i], F[23, i], F[24, i], F[25, i], F[26, i], F[27, i], F[28, i], F[29, i], F[30, i], F[31, i], F[32, i])) audioFeatureFile.write("%f\n" % (F[33, i])) sumAudio += float(F[2, i]) #data for HEART BEAT sumAudioFeat += float(F[3, i]) audioFeatureFile.close() sumAudio = sumAudio / 7 # there's 7 windows in 1 sec sumAudioFeat = sumAudioFeat / 7 iterations += 1 # currLine = currLine + 1 #move to the next Audio line currLine = rawlineCount if debugMode: print "AudioFeature Extracted" #if finish audioFeature Ext + rawADC creates a new file elif (len(files) >= 2): #has new rawADC file + rawlineCount == or < currLine # elif rawADC.rawADC_Time != startTimeDT: time.sleep(1) rawlineCount = 0 for line in open(rawADCFileName).xreadlines(): rawlineCount += 1 if rawlineCount <= currLine: if debugMode: print "finished reading " + files[ 0] + ", deleting file now.." os.remove(rawADCFileName) currLine = startLine time.sleep(1) elif (len(files) == 1) and (currLine == rawlineCount): if debugMode: print "waiting for new data..." # if debugMode: print "length of rawX = " + str(len(rawX)) time.sleep(1) # startDateTime = rawADC.rawADC_startDateTime # startTimeDT = str(rawADC.rawADC_Time) # audioFeatureFileName = BASE_PATH+"Relay_Station{0}/AudioF/AudioF{1}.txt".format(BASE_PORT, startTimeDT) # # create new audioFeatureFile # with open(audioFeatureFileName, "w") as audioFeatureFile: # audioFeatureFile.write(startDateTime+"\n") # audioFeatureFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) # audioFeatureFile.write("Timestamp, ZCR, Energy, Energy Entropy, Spectral Centroid, Spectral Spread, Spectral Entropy, Spectral Flux, Spectral Rolloff, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, ChromaVector1, , ChromaVector2, ChromaVector3, ChromaVector4, ChromaVector5, ChromaVector6, ChromaVector7, ChromaVector8, ChromaVector9, ChromaVector10, ChromaVector11, ChromaVector12, ChromaDeviation\n") # audioFeatureFile.close() # currLine = startLine # # print "new File Created" # #update new rawADC filename to open # rawADCFileName = BASE_PATH+"Relay_Station{0}/rawADC/rawADC{1}.txt".format(BASE_PORT, startTimeDT) if iterations >= UPDATE_LENGTH: sumAudio = sumAudio / iterations iterations = 0 audioMessage = [] audioMessage.append("Audio") audioMessage.append(str("{0:.3f}".format(sumAudio))) #Energy audioMessage.append(str("{0:.3f}".format(sumAudioFeat))) #Teager tempDateTime = rNTPTime.sendUpdate( server_address, audioMessage, 5) #Audio uses startDateTime from rawADC sumAudio = 0 sumAudioFeat = 0
def readADC(): streaming = True logging = True #get info from config file hostIP, BASE_PORT = readConfigFile() server_address = (hostIP, BASE_PORT) startDateTime = rNTPTime.sendUpdate(server_address, "-99", 5) if startDateTime != None: # use custom function because datetime.strptime fails in multithreaded applications startTimeDT = rNTPTime.stripDateTime(startDateTime) else: startDateTime = rNTPTime.sendUpdate(server_address, "-99", 5) startTimeDT = rNTPTime.stripDateTime(startDateTime) audioFileName = BASE_PATH + "Relay_Station{0}/Audio/Audio{1}.txt".format( BASE_PORT, startTimeDT) # doorFileName = BASE_PATH+"Relay_Station{0}/Door/Door{1}.txt".format(BASE_PORT, startTimeDT) # tempFileName = BASE_PATH+"Relay_Station{0}/Temperature/Temperature{1}.txt".format(BASE_PORT, startTimeDT) global rawADC_Time global rawADC_startDateTime rawADC_startDateTime = startDateTime sensoMessage = " ADC " rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/rawADC{1}.txt".format( BASE_PORT, startTimeDT) with open(rawADCFileName, "w") as rawADCFile: rawADCFile.write(startDateTime + "\n") rawADCFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) rawADCFile.write("Timestamp,Mic(10kHz samples)\n") # rawADCFile.close() doorFileName = BASE_PATH + "Relay_Station{0}/Door/Door{1}.txt".format( BASE_PORT, startTimeDT) with open(doorFileName, "w") as doorFile: doorFile.write(startDateTime + "\n") doorFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) doorFile.write( "Timestamp,Door Sensor Channel 1, Door Sensor Channel 2\n") # doorFile.close() tempFileName = BASE_PATH + "Relay_Station{0}/Temperature/Temperature{1}.txt".format( BASE_PORT, startTimeDT) with open(tempFileName, "w") as tempFile: tempFile.write(startDateTime + "\n") tempFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) tempFile.write("Timestamp,Degree F\n") # tempFile.close() # get starting time according to the BBB. This is only used for time deltas startTime = datetime.datetime.now() iterationsAudio = 0 iterations = 0 dummyvar = 0 test_count = 0 sumAudio = 0 sumDoor1 = 0 sumDoor2 = 0 sumTemp = 0 while True: rawADC_Time = startTimeDT if iterationsAudio >= AUDIO_LENGTH: iterationsAudio = 0 test_count += 1 # startDateTime = "2017-11-15 %d%d:%d%d:%d%d.000" %(test_count,test_count,test_count,test_count,test_count,test_count) #get current time from basestation startDateTime = rNTPTime.sendUpdate(server_address, "-99", 5) # if startDateTime updates sucessfully -> create a new file # if startDateTime == None (update fails) -> keep writing the current file if startDateTime != None: startTimeDT = rNTPTime.stripDateTime(startDateTime) rawADC_Time = startTimeDT rawADC_startDateTime = startDateTime rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/rawADC{1}.txt".format( BASE_PORT, startTimeDT) with open(rawADCFileName, "w") as rawADCFile: rawADCFile.write(startDateTime + "\n") rawADCFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) rawADCFile.write("Timestamp,Mic(10kHz samples)\n") rawADCFile.close() # get new local start time startTime = datetime.datetime.now() iterationsAudio += 1 if iterations >= FILE_LENGTH: iterations = 0 # test_count += 1 # startDateTime = "2017-11-15 %d%d:%d%d:%d%d.000" %(test_count,test_count,test_count,test_count,test_count,test_count) #get current time from basestation startDateTime = rNTPTime.sendUpdate(server_address, "-99", 5) # if startDateTime updates sucessfully -> create a new file # if startDateTime == None (update fails) -> keep writing the current file if startDateTime != None: startTimeDT = rNTPTime.stripDateTime(startDateTime) doorFileName = BASE_PATH + "Relay_Station{0}/Door/Door{1}.txt".format( BASE_PORT, startTimeDT) with open(doorFileName, "w") as doorFile: doorFile.write(startDateTime + "\n") doorFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) doorFile.write( "Timestamp,Door Sensor Channel 1, Door Sensor Channel 2\n" ) # doorFile.close() tempFileName = BASE_PATH + "Relay_Station{0}/Temperature/Temperature{1}.txt".format( BASE_PORT, startTimeDT) with open(tempFileName, "w") as tempFile: tempFile.write(startDateTime + "\n") tempFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) tempFile.write("Timestamp,Degree F\n") # tempFile.close() # get new local start time startTime = datetime.datetime.now() iterations += 1 dummyvar += 1 # calculate the time since the start of the data collection currTime = datetime.datetime.now() currTimeDelta = (currTime - startTime).days * 86400 + ( currTime - startTime ).seconds + (currTime - startTime).microseconds / 1000000.0 # run the c code to get one second of data from the ADC proc = subprocess.Popen( ["./root/besi-relay-station/BESI_LOGGING_R/ADC1"], stdout=subprocess.PIPE, ) # proc = subprocess.Popen(["./ADC1"], stdout=subprocess.PIPE,) # anything printed in ADC.c is captured in output output = proc.communicate()[0] split_output = output.split(',') # try: # proc = subprocess.Popen(["./ADC1"], stdout=subprocess.PIPE,) # # anything printed in ADC.c is captured in output # output = proc.communicate()[0] # split_output = output.split(',') # except : # print "Thread: ADCThread, ERROR: subprocess.Popen[./ADC1]" # split_output = [0]*10021 # split_output = ",".join(map(str, split_output)) # split_output = split_output.split(',') # print newTimeDelta, (float(split_output[-5]) + currTimeDelta - testTime), len(split_output) # data is in <timestamp>,<value> format # 100 samples/second from the mic and 1 sample/sec from the temperature sensor i = 0 ka = 0 sumA = 0 kd = 0 (tempC, tempF) = calc_temp(float(split_output[-1]) * 1000) buffer_size = 2048 with open(rawADCFileName, "a", buffer_size) as rawADCFile: rawADCFile.write("%0.4f," % (currTimeDelta)) rawADCFile.write(",".join(split_output[0:10000]) + ",") rawADCFile.write("\n") # rawADCFile.write(",".join(split_output[10000:10010]) + ",") # rawADCFile.write(",".join(split_output[10010:10020]) + ",") # rawADCFile.write("%03.2f" %(tempF)) # rawADCFile.close() doorData = map(float, split_output[10000:10020]) sumDoor1 = sumDoor1 + sum(doorData[0:10]) sumDoor2 = sumDoor2 + sum(doorData[10:20]) with open(doorFileName, "a") as doorFile: for i in range(0, 10): doorFile.write("%0.2f," % (currTimeDelta + (0.1 * i))) doorFile.write("%0.4f," % (doorData[i])) doorFile.write("%0.4f\n" % (doorData[i + 10])) # doorFile.close() with open(tempFileName, "a") as tempFile: tempFile.write("%0.2f," % (currTimeDelta)) tempFile.write("%03.2f\n" % (tempF)) # tempFile.close() # newTime = datetime.datetime.now() # newTimeDelta = (newTime - currTime).days * 86400 + (newTime - currTime).seconds + (newTime - currTime).microseconds / 1000000.0 # testTime = float(split_output[-5]) + currTimeDelta if (iterations % UPDATE_LENGTH) == (UPDATE_LENGTH - 2): # iterations = 0 doorMessage = [] doorMessage.append("Door") doorMessage.append(str("{0:.3f}".format(sumDoor1))) #channel1 doorMessage.append(str("{0:.3f}".format(sumDoor2))) #channel2 tempDateTime = rNTPTime.sendUpdate( server_address, doorMessage, 5) #Audio uses startDateTime from rawADC sumDoor1 = 0 sumDoor2 = 0 tempMessage = [] tempMessage.append("Temperature") tempMessage.append(str("{0:.3f}".format(tempF))) #tempF tempDateTime = rNTPTime.sendUpdate( server_address, tempMessage, 5) #Audio uses startDateTime from rawADC
def soundSense(startDateTime, hostIP, BASE_PORT, streaming=True, logging=True): server_address = (hostIP, BASE_PORT) # use custom function because datetime.strptime fails in multithreaded applications startTimeDT = rNTPTime.stripDateTime(startDateTime) audioFileName = BASE_PATH + "Relay_Station{0}/Audio/Audio{1}.txt".format( BASE_PORT, startTimeDT) doorFileName = BASE_PATH + "Relay_Station{0}/Door/Door{1}.txt".format( BASE_PORT, startTimeDT) tempFileName = BASE_PATH + "Relay_Station{0}/Temperature/Temperature{1}.txt".format( BASE_PORT, startTimeDT) sensorMessage = " ADC " # write header information with open(audioFileName, "w") as audioFile: audioFile.write(startDateTime + "\n") audioFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) audioFile.write("Timestamp,Ambient Noise Level\n") audioFile.close() with open(doorFileName, "w") as doorFile: doorFile.write(startDateTime + "\n") doorFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) doorFile.write( "Timestamp,Door Sensor Channel 1, Door Sensor Channel 2\n") doorFile.close() with open(tempFileName, "w") as tempFile: tempFile.write(startDateTime + "\n") tempFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) tempFile.write("Timestamp,Degree F\n") tempFile.close() # get starting time according to the BBB. This is only used for time deltas startTime = datetime.datetime.now() iterations = -1 dummyvar = 0 sumAudio = 0 sumDoor1 = 0 sumDoor2 = 0 sumTemp = 0 while True: if iterations >= FILE_LENGTH: # update BS and get current time every FILE_LENGTH iterations sumAudio = sumAudio / dummyvar sumDoor1 = sumDoor1 / dummyvar sumDoor2 = sumDoor2 / dummyvar sumTemp = sumTemp / dummyvar startDateTime = rNTPTime.sendUpdate(server_address, iterations, sensorMessage, sumAudio, sumDoor1, sumDoor2, sumTemp, 5) iterations = -1 sumAudio = 0 sumDoor1 = 0 sumDoor2 = 0 sumTemp = 0 dummyvar = 0 # if startDateTime == None, the update failed, so we keep writing to the old file if startDateTime != None: startTimeDT = rNTPTime.stripDateTime(startDateTime) audioFile.close() doorFile.close() tempFile.close() audioFileName = BASE_PATH + "Relay_Station{0}/Audio/Audio{1}.txt".format( BASE_PORT, startTimeDT) doorFileName = BASE_PATH + "Relay_Station{0}/Door/Door{1}.txt".format( BASE_PORT, startTimeDT) tempFileName = BASE_PATH + "Relay_Station{0}/Temperature/Temperature{1}.txt".format( BASE_PORT, startTimeDT) with open(audioFileName, "w") as audioFile: audioFile.write(startDateTime + "\n") audioFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) audioFile.write("Timestamp,Ambient Noise Level\n") audioFile.close() with open(doorFileName, "w") as doorFile: doorFile.write(startDateTime + "\n") doorFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) doorFile.write( "Timestamp,Door Sensor Channel 1, Door Sensor Channel 2\n" ) doorFile.close() with open(tempFileName, "w") as tempFile: tempFile.write(startDateTime + "\n") tempFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) tempFile.write("Timestamp,Degree F\n") tempFile.close() # get new local start time startTime = datetime.datetime.now() # update BS every UPDATE_LENGTH iterations elif (iterations % UPDATE_LENGTH) == (UPDATE_LENGTH - 2): sumAudio = sumAudio / UPDATE_LENGTH sumDoor1 = sumDoor1 / UPDATE_LENGTH sumDoor2 = sumDoor2 / UPDATE_LENGTH sumTemp = sumTemp / UPDATE_LENGTH rNTPTime.sendUpdate(server_address, iterations, sensorMessage, sumAudio, sumDoor1, sumDoor2, sumTemp, 5) sumAudio = 0 sumDoor1 = 0 sumDoor2 = 0 sumTemp = 0 dummyvar = 0 iterations += 1 dummyvar += 1 # calculate the time since the start of the data collection currTime = datetime.datetime.now() currTimeDelta = (currTime - startTime).days * 86400 + ( currTime - startTime ).seconds + (currTime - startTime).microseconds / 1000000.0 # run the c code to get one second of data from the ADC proc = subprocess.Popen( ["./root/besi-relay-station/BESI_LOGGING_R/ADC1"], stdout=subprocess.PIPE, ) # anything printed in ADC.c is captured in output output = proc.communicate()[0] split_output = output.split(',') # data is in <timestamp>,<value> format # 100 samples/second from the mic and 1 sample/sec from the temperature sensor i = 0 ka = 0 sumA = 0 kd = 0 sumD1 = 0 sumD2 = 0 while (i < (len(split_output) / 2 - 1)): # every 11th sample is from the door sensor if (((i + 1) % 12) == 11): #doorFile.write(struct.pack("fff", float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1]),float(split_output[2 * i + 3])) + "~~") with open(doorFileName, "a") as doorFile: doorFile.write("{0:.2f},{1:.2f},{2:.2f}\n".format( float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1]), float(split_output[2 * i + 3]))) doorFile.close() sumD1 = sumD1 + float(split_output[2 * i + 1]) sumD2 = sumD2 + float(split_output[2 * i + 3]) kd = kd + 1 i = i + 2 else: #audioFile.write(struct.pack("ff", float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1])) + "~~") with open(audioFileName, "a") as audioFile: audioFile.write("{0:.2f},{1:.2f}\n".format( float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1]))) audioFile.close() sumA = sumA + float(split_output[2 * i + 1]) ka = ka + 1 i = i + 1 # send 1 semple from the temperature sensor try: (tempC, tempF) = calc_temp(float(split_output[-1]) * 1000) except: sys.exit() with open(tempFileName, "a") as tempFile: tempFile.write("{0:0.4f},{1:03.2f},\n".format( float(split_output[-2]) + currTimeDelta, tempF)) tempFile.close() sumAudio = sumAudio + (sumA / ka) sumDoor1 = sumDoor1 + (sumD1 / kd) sumDoor2 = sumDoor2 + (sumD2 / kd) sumTemp = sumTemp + tempF
def doorSensor(startDateTime, hostIP, BASE_PORT): time.sleep((LOOP_DELAY * UPDATE_DELAY)) #Heartbeat stuff server_address = (hostIP, BASE_PORT) doorMessage = [] tempMessage = [] sumDoor1 = 0 sumDoor2 = 0 sumTemp = 0 iterations = 0 startLine = 3 # 3 lines description in the beginning currLine = startLine #current line to read/write from startTimeDT = rNTPTime.stripDateTime(startDateTime) doorFileName = BASE_PATH+"Relay_Station{0}/Door/Door{1}.txt".format(BASE_PORT, startTimeDT) with open(doorFileName, "w") as doorFile: doorFile.write(startDateTime+"\n") doorFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) doorFile.write("Timestamp,Door Sensor Channel 1, Door Sensor Channel 2\n") doorFile.close() tempFileName = BASE_PATH+"Relay_Station{0}/Temperature/Temperature{1}.txt".format(BASE_PORT, startTimeDT) with open(tempFileName, "w") as tempFile: tempFile.write(startDateTime+"\n") tempFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) tempFile.write("Timestamp,Degree F\n") tempFile.close() # for testing doorway crossing event directionFileName = BASE_PATH+"Relay_Station{0}/Direction/Direction{1}.txt".format(BASE_PORT, startTimeDT) with open(directionFileName, "w") as directionFile: directionFile.write(startDateTime+"\n") directionFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) directionFile.write("Timestamp,Direction\n") directionFile.close() while True: startTimeDT = rNTPTime.stripDateTime(startDateTime) rawADCFileName = BASE_PATH+"Relay_Station{0}/rawADC/rawADC{1}.txt".format(BASE_PORT, startTimeDT) # doorFileName = BASE_PATH+"Relay_Station{0}/Door/Door{1}.txt".format(BASE_PORT, startTimeDT) rawlineCount = 0 for line in open(rawADCFileName).xreadlines( ): rawlineCount += 1 if rawlineCount > currLine: with open(rawADCFileName, "r") as rawADCFile: rawADC_string = rawADCFile.readlines()[currLine] rawADC_Data = rawADC_string.split(',') timeDelta = float(rawADC_Data[0]) # print float(rawADC_Data[-1]), " length=", len(rawADC_Data[10000:10021]) # if len(rawADC_Data[-1]) == 1: # with open(tempFileName, "a") as tempFile: # tempFile.write("%0.2f," %( timeDelta )) # tempFile.write("%03.2f\n" %( float(rawADC_Data[-1]))) if len(rawADC_Data[10001:10022]) == 21: #20(Doors) + 1(Temp) #Door sensor data processing rawDoorData = map(float,rawADC_Data[10001:10021]) rawDoorData = numpy.array(rawDoorData) doorData = doorProcessing(timeDelta, rawDoorData) #END Door sensor data processing with open(doorFileName, "a") as doorFile: for i in range(0,10): doorFile.write("%0.2f," %( timeDelta + (0.1*i) )) doorFile.write("%d," %( doorData[i])) doorFile.write("%d\n" %( doorData[i+10])) doorFile.close() with open(tempFileName, "a") as tempFile: tempFile.write("%0.2f," %( timeDelta )) tempFile.write("%03.2f\n" %( float(rawADC_Data[-1]))) tempFile.close() #value for heartbeat sumDoor1 += numpy.mean(doorData[0:10]) sumDoor1 += numpy.mean(doorData[10:20]) sumTemp += float(rawADC_Data[-1]) iterations += 1 currLine = currLine + 1 #move to the next Audio line #if finish audioFeature Ext + rawADC creates a new file elif rawADC.rawADC_Time != startTimeDT: rawlineCount = 0 for line in open(rawADCFileName).xreadlines( ): rawlineCount += 1 if rawlineCount==currLine: #delete the previous rawADCFile try: os.remove(rawADCFileName) except OSError: pass startDateTime = rawADC.rawADC_startDateTime startTimeDT = str(rawADC.rawADC_Time) doorFileName = BASE_PATH+"Relay_Station{0}/Door/Door{1}.txt".format(BASE_PORT, startTimeDT) # create new door file with open(doorFileName, "w") as doorFile: doorFile.write(startDateTime+"\n") doorFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) doorFile.write("Timestamp,Door Sensor Channel 1, Door Sensor Channel 2\n") doorFile.close() currLine = startLine # print "new File Created" tempFileName = BASE_PATH+"Relay_Station{0}/Temperature/Temperature{1}.txt".format(BASE_PORT, startTimeDT) with open(tempFileName, "w") as tempFile: tempFile.write(startDateTime+"\n") tempFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) tempFile.write("Timestamp,Degree F\n") tempFile.close() directionFileName = BASE_PATH+"Relay_Station{0}/Direction/Direction{1}.txt".format(BASE_PORT, startTimeDT) with open(directionFileName, "w") as directionFile: directionFile.write(startDateTime+"\n") directionFile.write("Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) directionFile.write("Timestamp,Direction\n") directionFile.close() #update new rawADC filename to open rawADCFileName = BASE_PATH+"Relay_Station{0}/rawADC/rawADC{1}.txt".format(BASE_PORT, startTimeDT) if iterations>=UPDATE_LENGTH: #HEARTBEAT sumDoor1 = sumDoor1/iterations sumDoor2 = sumDoor2/iterations sumTemp = sumTemp/iterations iterations = 0 doorMessage = [] doorMessage.append("Door") doorMessage.append(str("{0:.3f}".format(sumDoor1))) doorMessage.append(str("{0:.3f}".format(sumDoor2))) tempDateTime = rNTPTime.sendUpdate(server_address, doorMessage, 5) #Audio uses startDateTime from rawADC sumAudio = 0 tempMessage = [] tempMessage.append("Temperature") tempMessage.append(str("{0:.3f}".format(sumTemp))) tempDateTime = rNTPTime.sendUpdate(server_address, tempMessage, 5) #uses startDateTime from rawADC sumTemp = 0
def readADC(startDateTime, hostIP, BASE_PORT, streaming=True, logging=True): server_address = (hostIP, BASE_PORT) # use custom function because datetime.strptime fails in multithreaded applications startTimeDT = rNTPTime.stripDateTime(startDateTime) audioFileName = BASE_PATH + "Relay_Station{0}/Audio/Audio{1}.txt".format( BASE_PORT, startTimeDT) doorFileName = BASE_PATH + "Relay_Station{0}/Door/Door{1}.txt".format( BASE_PORT, startTimeDT) tempFileName = BASE_PATH + "Relay_Station{0}/Temperature/Temperature{1}.txt".format( BASE_PORT, startTimeDT) rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/rawADC{1}.txt".format( BASE_PORT, startTimeDT) global rawADC_Time global rawADC_startDateTime rawADC_startDateTime = startDateTime sensoMessage = " ADC " with open(rawADCFileName, "w") as rawADCFile: rawADCFile.write(startDateTime + "\n") rawADCFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) rawADCFile.write( "Timestamp,Mic(10kHz samples),Door1(10 samples),Door2(10 samples),Temp(Degree F)\n" ) rawADCFile.close() # get starting time according to the BBB. This is only used for time deltas startTime = datetime.datetime.now() iterations = 0 dummyvar = 0 test_count = 0 sumAudio = 0 sumDoor1 = 0 sumDoor2 = 0 sumTemp = 0 while True: rawADC_Time = startTimeDT if iterations >= ADC_LENGTH: iterations = 0 test_count += 1 # startDateTime = "2017-11-15 %d%d:%d%d:%d%d.000" %(test_count,test_count,test_count,test_count,test_count,test_count) #get current time from basestation startDateTime = rNTPTime.sendUpdate(server_address, "-99", 5) # if startDateTime updates sucessfully -> create a new file # if startDateTime == None (update fails) -> keep writing the current file if startDateTime != None: startTimeDT = rNTPTime.stripDateTime(startDateTime) rawADC_Time = startTimeDT rawADC_startDateTime = startDateTime rawADCFileName = BASE_PATH + "Relay_Station{0}/rawADC/rawADC{1}.txt".format( BASE_PORT, startTimeDT) with open(rawADCFileName, "w") as rawADCFile: rawADCFile.write(startDateTime + "\n") rawADCFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) rawADCFile.write( "Timestamp,Mic(10kHz samples),Door1(10 samples),Door2(10 samples),Temp(Degree F)\n" ) rawADCFile.close() # get new local start time startTime = datetime.datetime.now() iterations += 1 dummyvar += 1 # calculate the time since the start of the data collection currTime = datetime.datetime.now() currTimeDelta = (currTime - startTime).days * 86400 + ( currTime - startTime ).seconds + (currTime - startTime).microseconds / 1000000.0 # run the c code to get one second of data from the ADC proc = subprocess.Popen( ["./root/besi-relay-station/BESI_LOGGING_R/ADC1"], stdout=subprocess.PIPE, ) # anything printed in ADC.c is captured in output output = proc.communicate()[0] split_output = output.split(',') # try: # proc = subprocess.Popen(["./ADC1"], stdout=subprocess.PIPE,) # # anything printed in ADC.c is captured in output # output = proc.communicate()[0] # split_output = output.split(',') # except : # print "Thread: ADCThread, ERROR: subprocess.Popen[./ADC1]" # split_output = [0]*10021 # split_output = ",".join(map(str, split_output)) # split_output = split_output.split(',') # print newTimeDelta, (float(split_output[-5]) + currTimeDelta - testTime), len(split_output) # data is in <timestamp>,<value> format # 100 samples/second from the mic and 1 sample/sec from the temperature sensor i = 0 ka = 0 sumA = 0 kd = 0 sumD1 = 0 sumD2 = 0 (tempC, tempF) = calc_temp(float(split_output[-1]) * 1000) with open(rawADCFileName, "a") as rawADCFile: rawADCFile.write("%0.4f," % (currTimeDelta)) rawADCFile.write(",".join(split_output[0:10000]) + ",") rawADCFile.write(",".join(split_output[10000:10010]) + ",") rawADCFile.write(",".join(split_output[10010:10020]) + ",") rawADCFile.write("%03.2f" % (tempF)) rawADCFile.write("\n") rawADCFile.close() newTime = datetime.datetime.now() newTimeDelta = (newTime - currTime).days * 86400 + ( newTime - currTime).seconds + (newTime - currTime).microseconds / 1000000.0 # print newTimeDelta, currTimeDelta, len(split_output) # print "rMic" # print len(timeData), len(audioData), len(doorData1), len(doorData2), tempData # while (i < (len(split_output) / 2 - 1)): # # every 1000th sample is from the door sensor # if (((i + 1) % 1001) == 1000): # with open(doorFileName, "a") as doorFile: # doorFile.write("{0:.2f},{1:.2f},{2:.2f}\n".format( float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 2]),float(split_output[2 * i + 3]))) # doorFile.close() # sumD1 = sumD1 + float(split_output[2 * i + 1]) # sumD2 = sumD2 + float(split_output[2 * i + 3]) # kd = kd + 1 # # with open(audioFileName, "a") as audioFile: # # audioFile.write("{0:.4f},{1:.2f}\n".format(float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1]))) # # audioFile.close() # # sumA = sumA + float(split_output[2 * i + 1]) # # ka = ka + 1 # i = i + 2 # else: # # with open(audioFileName, "a") as audioFile: # # audioFile.write("{0:.4f},{1:.2f}\n".format(float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1]))) # # audioFile.close() # ###### # # if ((i%100)==0): # # with open(audioFileName, "a") as audioFile: # # audioFile.write("{0:.4f},{1:.2f}\n".format(float(split_output[2 * i]) + currTimeDelta, float(split_output[2 * i + 1]))) # # audioFile.close() # sumA = sumA + float(split_output[2 * i + 1]) # ka = ka + 1 # i = i + 1 # send 1 semple from the temperature sensor # try: # (tempC, tempF) = calc_temp(float(split_output[-1]) * 1000) # except: # sys.exit() # with open(tempFileName, "a") as tempFile: # tempFile.write("{0:0.4f},{1:03.2f},{2:0.4f}\n".format(float(split_output[-5]) + currTimeDelta, tempF, float(split_output[-5]) + currTimeDelta - testTime)) # #tempFile.write("{0:0.4f},{1:03.2f},\n".format(float(split_output[-2]) + currTimeDelta, tempF)) # tempFile.close() # sumAudio = sumAudio + (sumA/ka) # sumDoor1 = sumDoor1 + (sumD1/kd) # sumDoor2 = sumDoor2 + (sumD2/kd) # sumTemp = sumTemp + tempF testTime = float(split_output[-5]) + currTimeDelta
def pixieLog(): global agiStatus global agiType global agiIndx #get info from config file hostIP, BASE_PORT, pebbleFolder = readConfigFile() server_address = (hostIP, BASE_PORT) # startTimeDT = rNTPTime.stripDateTime(startDateTime) # pixieFileName = BASE_PATH+"Relay_Station{0}/Pixie/Pixie{1}.txt".format(BASE_PORT, startTimeDT) context = zmq.Context() # Socket to receive messages on receiver = context.socket(zmq.PULL) receiver.bind("tcp://127.0.0.1:5000") # file_path = "/media/card/rtest/" #os.environ.get('PEBBLE_DATA_LOC') file_path = "/media/card/" + pebbleFolder + "/" if file_path is None: print("DID NOT FIND PEBBLE_DATA_LOC") print(os.environ) exit(1) if not os.path.exists(file_path): os.mkdir(file_path) newFile = True iterFile = 0 fileSize_min = 60 #min fileSize = fileSize_min*60*50 #min * seconds * sampling_rate merr = 0 # print("merr = {}".format(merr)) # xagi = [] # yagi = [] # zagi = [] magi = [] tgr = [] iterations = 0 epochSecs = 10 while True: try: data = msgpack.unpackb(receiver.recv()) packet_count = int(len(data)/208) #print("got {} packets".format(packet_count)) if iterFile>=(fileSize): newFile = True if (packet_count>0 & packet_count<10): timestamp = unpack_from('Q',data,208*0) if newFile==True: #datafile.close() filename = str(file_path) + "pebble_data_"+ str(timestamp[0]) + ".csv" # print("file name: {}".format(filename)) #newFile = False #iterFile = 0 try: with open(filename,'w') as datafile: datafile.write("z,y,x,timestamp\n") # print("Opened file: {}".format(filename)) newFile = False iterFile = 0 #datafile.close() except: merr = 1 print("Error opening new file!") #break #datafile.close() # print("keep moving!") for k in range(packet_count): timestamp = unpack_from('Q',data,208*k) acc_data = [] for i in range(25): acc_data.append(unpack_from('hhhH',data,(208*k)+(i+1)*8)) # print("timestamp:{}".format(timestamp[0])) # print("data:{}".format(acc_data)) for data_t in acc_data: ## DATA FOR AGITATION DETECTION #print("calculate m") zvalue,yvalue,xvalue,offset = data_t mvalue = math.sqrt(xvalue**2 + yvalue**2 + zvalue**2) #zagi.append(zvalue) #yagi.append(yvalue) #xagi.append(xvalue) magi.append(mvalue/100) #print("{},{},{},{}".format(xvalue,yvalue,zvalue,mvalue)) # write to a file iterFile = iterFile + 1 try: with open(filename,'a') as datafile: datafile.write("{0},{1},{2},{3}\n".format(data_t[0],data_t[1],data_t[2],data_t[3]+timestamp[0])) #print("Wrote to file: {}".format(filename)) #datafile.close() except: merr = 1 #datafile.close() print("Error in writing data!") #receiver.close() print("Going out!") #exit(0) # print("Wrote all to file: {}".format(filename)) else: print("Size Error!") ## PROCESSING FOR AGITATION DETECTION #print "PROCESSING" if len(magi)>=(50*3): magiValues = magi[-50*3:] # print("magi = {}".format(magiValues)) try: # print str(reduce(lambda x,y:x+y,magiValues)) teagerValue = calcTeagerPerEpoch(magiValues,3) if teagerValue>10: tgr.append(teagerValue) # print("teagerValue = {}".format(teagerValue)) magi = [] except: print("Function Error!") #print("teagerValue = {}".format(teagerValue)) if iterations==10: pixieMessage = [] pixieMessage.append("Pixie") if len(tgr)>=2: pixieValue = reduce(lambda x,y:x+y,tgr) else: pixieValue = teagerValue # print pixieValue pixieMessage.append(str("{0:.3f}".format(pixieValue))) startDateTime = rNTPTime.sendUpdate(server_address, pixieMessage, 5) iterations = 0 if pixieValue>50: agiType = 1 agiStatus = True print "Agitation Type: " + str(agiType) agiMessage = [] agiMessage.append("Agitation") agiMessage.append(str(agiType)) agiMessage.append(str("{0:.3f}".format(pixieValue))) # startDateTime = rNTPTime.sendUpdate(server_address, agiMessage, 5) tgr = [] pixieValue = 0 else: del tgr[:int((len(tgr)/2)+1)] else: iterations +=1 except: print "Error!", sys.exc_info()[0] print("Exit!") receiver.close() print("merr={}".format(merr)) if merr==1: merr = 0 sys.exit() print("merr={}".format(merr))
def lightSense(startDateTime, hostIP, BASE_PORT, streaming=True, logging=True): global agiType global agiIndx global agiStatus server_address = (hostIP, BASE_PORT) startTimeDT = rNTPTime.stripDateTime(startDateTime) lightFileName = BASE_PATH + "Relay_Station{0}/Light/Light{1}.txt".format( BASE_PORT, startTimeDT) lightMessage = [] light_i2c = i2c_light_init(LIGHT_ADDR) with open(lightFileName, "w") as lightFile: lightFile.write(startDateTime + "\n") lightFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n".format(BASE_PORT)) lightFile.write("Timestamp,Lux\n") startTime = datetime.datetime.now() iterations = -1 sumLux = 0 dummyvar = 0 while True: if iterations >= FILE_LENGTH: sumLux = sumLux / dummyvar lightMessage = [] lightMessage.append("Light") lightMessage.append(str("{0:.3f}".format(sumLux))) startDateTime = rNTPTime.sendUpdate(server_address, lightMessage, 5) #agiIndx = update[0] #agiType = update[1] #if agiType!=0: # agiStatus = True #else: # agiStatus = False #startDateTime = update[2] #startDateTime = rNTPTime.sendUpdate(server_address, iterations, sensorMessage, sumLux, 0, 0, 0, 5) # " light samples" iterations = -1 sumLux = 0 dummyvar = 0 if startDateTime != None: startTimeDT = rNTPTime.stripDateTime(startDateTime) #startTimeDT = datetime.datetime.now() lightFileName = BASE_PATH + "Relay_Station{0}/Light/Light{1}.txt".format( BASE_PORT, startTimeDT) with open(lightFileName, "w") as lightFile: lightFile.write(startDateTime + "\n") lightFile.write( "Deployment ID: Unknown, Relay Station ID: {}\n". format(BASE_PORT)) lightFile.write("Timestamp,Lux\n") startTime = datetime.datetime.now() elif (iterations % UPDATE_LENGTH) == (UPDATE_LENGTH - 2): sumLux = sumLux / UPDATE_LENGTH lightMessage = [] lightMessage.append("Light") lightMessage.append(str("{0:.3f}".format(sumLux))) startDateTime = rNTPTime.sendUpdate(server_address, lightMessage, 5) #agiIndx = update[0] #agiType = update[1] #if agiType!=0: # agiStatus = True #else: # agiStatus = False #startDateTime = update[2] #rNTPTime.sendUpdate(server_address, iterations, sensorMessage, sumLux, 0,0,0, 5) # " light samples" sumLux = 0 dummyvar = 0 iterations += 1 dummyvar += 1 # calculate time since start currTime = datetime.datetime.now() currTimeDelta = (currTime - startTime).days * 86400 + ( currTime - startTime ).seconds + (currTime - startTime).microseconds / 1000000.0 # read light sensor # error reading i2c bus. Try to reinitialize sensor lightLevel = lux_calc(light_i2c.readU16(LIGHT_REG_LOW), light_i2c.readU16(LIGHT_REG_HIGH)) if lightLevel == -1: light_i2c = i2c_light_init(LIGHT_ADDR) #if logging: #lightWriter.writerow(("{0:.2f}".format(currTimeDelta), "{0:.2f}".format(lightLevel))) with open(lightFileName, "a") as lightFile: lightFile.write("{0:.2f},{1:.2f},\n".format( currTimeDelta, lightLevel)) sumLux = sumLux + lightLevel time.sleep(LOOP_DELAY * UPDATE_DELAY)
def check_charging(address): message = [] message.append("Charging") message.append(str("-1")) temp = rNTPTime.sendUpdate(address, message, 5) return