示例#1
0
def meminiSense(startDateTime,hostIP,BASE_PORT,streaming=True,logging=True):
	global meminifilename
	
	global agiType
	global agiIndx
	global agiStatus

	global server_address
	
	server_address = (hostIP, BASE_PORT)
	startTimeDT = rNTPTime.stripDateTime(startDateTime)

	#logging.basicConfig(level=logging.INFO)
	#file_path = "/media/card/memini/"
	#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) 
	#
	#filename = str(file_path) + "memini_data.csv"
	running = True
	#pebble = PebbleConnection(SerialTransport("/dev/rfcomm0"))
	#pebble.connect()
	
	while True:
		try:
			pebble = PebbleConnection(SerialTransport("/dev/rfcomm0"))
			pebble.connect()
			pebble.pump_reader()
			#print "connection try 0!"
			appUUID = APP_UUID[:]

			print "initializing Pebble connection.."
			# print pebble.send_and_read(AppRunState(data=AppRunStateRequest()), AppRunState).data.uuid

			while running:
				try:
					print "Attempt to Connect"
					#logging.info("Attempting to connect to pebble")
					pebble.run_async()
					print "Connection Success"
					#logging.info("Pebble connection success")
					break
				except libpebble2.exceptions.TimeoutError:
					print "Pebble timeouted, retrying.."
					continue

			while pebble.connected:
				try:
					print "Pebble Connected.."
					restart_app_on_watch(pebble,appUUID)
					with open(meminifilename,'a') as dataFile:
						dataFile.write("message,timestamp,button_id,click_type,battery_charge\n")
					
					# Register service for app messages
					print "initializing Services..."
					mainMsgService = AppMessageService(pebble)
					mainCommHandler = CommunicationKeeper(appUUID, mainMsgService)
					mainMsgService.register_handler("nack", mainCommHandler.nack_received)
					mainMsgService.register_handler("ack", mainCommHandler.ack_received)
					mainMsgHandler = AppMsgHandler(appUUID)
					mainMsgService.register_handler("appmessage", mainMsgHandler.message_received_event)

					break
				except Exception as err:
					print err
					print "Error Initializing Services, retrying.."
					pebble.run_async()
					continue

			while pebble.connected:
				# time.sleep(10) 
				is_app_on(pebble,appUUID)
				pebbleMessage = []
				pebbleMessage.append("checkNoti") #check for notiFlag from basestation
				pebbleMessage.append(str(BASE_PORT))
				temp = rNTPTime.checkNoti(hostIP, pebbleMessage, 5) 
				# if True: #for testing
				if int(rNTPTime.notiFlag) == 1:
					memini_main(mainMsgService,mainCommHandler,mainMsgHandler)
					# print("sending Message")
				else:
					#print "NO NOTIFICATION"
					time.sleep(NOTI_CHECK_DELAY)
		except SerialException:
			print("Pebble Disconnected!")
			time.sleep(30)
			continue

		except Exception as err:
			print err
			pass
示例#2
0
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)	
示例#3
0
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
示例#4
0
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
示例#5
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
示例#6
0
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
示例#7
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
示例#8
0
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)
示例#9
0
def pixieLog(startDateTime,hostIP,BASE_PORT):
    
    global agiStatus
    global agiType
    global agiIndx

    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')
    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
    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>=(50*60*60): 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))