Beispiel #1
0
def turnButton(pin):
    if (aqC.state == 'commute'):
        if (pin == leftTurn):
            # begin turn
            utility.printAndLog('beginning left turn')
            aqC.turningLeft = True
            while (aqC.turningLeft):
                # blink and check for the signal to stop
                illuminator.blinkLeft()
                if (GPIO.input(endTurn)):
                    print('ending turn')
                    aqC.turningLeft = False
                    doLights()
                    return
        else:
            # begin turn
            utility.printAndLog('beginning right turn')
            aqC.turningRight = True
            while (aqC.turningRight):
                # blink and check for the signal to stop
                illuminator.blinkRight()
                if (GPIO.input(endTurn)):
                    print('ending turn')
                    aqC.turningRight = False
                    doLights()
                    return
Beispiel #2
0
def lurk():
    utility.printAndLog('lurking for %d seconds' % lurkDowntime)
    time.sleep(lurkDowntime)
    if (aqC.state == 'nap'):
        pass
    elif (aqC.state == 'commute'):
        aqC.monitorSensors()
Beispiel #3
0
def isDark():
    # query the full and IR-only light values
    full, ir = aquaTSL2591.get_full_luminosity()
    # convert to lux
    lux = aquaTSL2591.calculate_lux(full, ir)
    # compare against threshold
    if (lux < darknessThreshold):
        utility.printAndLog("it's dark!")
        return True
    else:
        utility.printAndLog("it's light!")
        return False
Beispiel #4
0
 def monitorSensors(self):
     utility.printAndLog('monitoring sensors')
     # check darkness and adjust LEDs appropriately
     if (darknessSensor.isDark()):
         illuminator.lightsOn()
     else:
         illuminator.lightsOff()
     # location check
     # get GPS coordinates
     if aquaGPS.checkForFix():
         (self.lat, self.lon) = aquaGPS.getCoord()
         # check if we are home - if not, begin ride
         if not (aquaGPS.homeZone(self.lat, self.lon)):
             self.there()
Beispiel #5
0
def getCoord():
    # Start the serial connection
    ser = serial.Serial('/dev/serial0',
                        115200,
                        bytesize=serial.EIGHTBITS,
                        parity=serial.PARITY_NONE,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=1)
    ser.write(gpsCheck.encode())
    while True:
        response = str(ser.readline())
        if ("+CGNSINF: 1," in response):
            # Split the reading by commas and return the parts referencing lat and long
            array = response.split(",")
            lat = array[3]
            utility.printAndLog("Latitude: %s" % lat)
            lon = array[4]
            utility.printAndLog("Longitude: %s\n" % lon)
            # turn GPS off
            ser.write(gpsPowerOff.encode())
            return (lat, lon)
Beispiel #6
0
def checkForFix():
    utility.printAndLog("checking for fix")
    # Start the serial connection
    ser = serial.Serial('/dev/serial0',
                        115200,
                        bytesize=serial.EIGHTBITS,
                        parity=serial.PARITY_NONE,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=1)
    # Turn on the GPS
    ser.write(gpsPowerOn.encode())
    ser.write(gpsPowerCheck.encode())
    while True:
        response = str(ser.readline())
        if (" 1" in response):
            break
    # Ask for the navigation info parsed from NMEA sentences
    ser.write(gpsCheck.encode())
    while True:
        response = str(ser.readline())
        # Check if a fix was found
        if ("+CGNSINF: 1,1," in response):
            utility.printAndLog("fix found")
            return True
        # If a fix wasn't found, wait and try again
        if ("+CGNSINF: 1,0," in response):
            sleep(5)
            ser.write(gpsCheck.encode())
            utility.printAndLog("still looking for fix")
            # turn the GPS off to save power
            ser.write(gpsPowerOff.encode())
            return False
        else:
            # still waiting for response
            ser.write(gpsCheck.encode())
Beispiel #7
0
def uploadData(controllerInstance):
    gpsFileName = controllerInstance.gpsFileName
    accelFileName = controllerInstance.accelFileName
    fd = controllerInstance.freshData
    # if there is new data to log (i.e. we came back from a ride)
    if fd:
        # get the file contents and split into rows
        gpsFile = open(gpsFileName, 'r')
        gpsContents = gpsFile.read()
        gpsRows = gpsContents.split('\n')

        accelFile = open(accelFileName, 'r')
        accelContents = accelFile.read()
        accelRows = accelContents.split('\n')
        while fd:
            try:
                for row in gpsRows:
                    # split each row by data point
                    rowEntries = row.split('\t')
                    # make sure there are the correct number of entries
                    if (len(rowEntries) == 3):
                        # log the data
                        gpsData = {
                            'sheet': sheetName + ':GPS',
                            'Data Time': rowEntries[0],
                            'Latitude': rowEntries[1],
                            'Longitude': rowEntries[2]
                        }
                        requests.get(publicURL, params=gpsData)
                for row in accelRows:
                    rowEntries = row.split('\t')
                    if (len(rowEntries) == 4):
                        accelData = {
                            'sheet': sheetName + ':Accel',
                            'Data Time': rowEntries[0],
                            'X': rowEntries[1],
                            'Y': rowEntries[2],
                            'Z': rowEntries[3]
                        }
                        requests.get(publicURL, params=accelData)
                # no more fresh data
                fd = False
                controllerInstance.freshData = False
                utility.printAndLog('data logged succesfully')
                return True
            # if no wifi, try again later
            except requests.exceptions.ConnectionError:
                utility.printAndLog('no WiFi right now')
                time.sleep(wifiCheckTime)
    else:
        utility.printAndLog('no data to log!')
Beispiel #8
0
 def __init__(self):
     utility.printAndLog('setting up accelerometer SPI')
     # set up SPI
     self.spi = spidev.SpiDev()
     self.spi.open(0, 0)
     # CPHA = CPOL = 0
     self.spi.mode = 0b00
     # recommended speeds 1MHz - 8MHz
     self.spi.max_speed_hz = 1000000
     # soft reset
     utility.printAndLog('accel soft reset')
     self.spiWrite(REG_SOFT_RESET, [VAL_SOFT_RESET])
     time.sleep(0.5)
     # setup interrupts and mode
     utility.printAndLog('setting up accel interrupts')
     self.setupInterrupts()
Beispiel #9
0
 def collectData(self):
     utility.printAndLog('riding')
     # check darkness and adjust LEDs appropriately
     if (darknessSensor.isDark()):
         illuminator.lightsOn()
     else:
         illuminator.lightsOff()
     # check previous state - if commute, make new data file
     if (self.previous == 'commute'):
         utility.printAndLog('creating new data files')
         self.accelFileName = dataLogger.makeFileName('accel')
         self.gpsFileName = dataLogger.makeFileName('gps')
         self.freshData = True
         # so that we don't accidentally create new files again
         self.previous = 'ride'
     # otherwise, use the one that already exists
     else:
         utility.printAndLog('using existing data files')
         dataLogger.writeToFile(self.accelFileName, self.accelDataBuffer)
         self.accelDataBuffer = ''
     # main data collection: accelerometer
     for reading in range(BicycleController.accelReadsBetweenGPS):
         # get accelerometer data and store in file
         #(x,y,z,temp) = accel.read_xyz()
         (x, y, z) = self.accel.readXYZ()
         t = dataLogger.makeTimeStamp()
         accelData = '%s\t%s\t%s\t%s\n' % (t, x, y, z)
         dataLogger.writeToFile(self.accelFileName, accelData)
         # sleep
         time.sleep(BicycleController.timeBetweenAccelReads)
     # location check
     # get GPS coordinates
     # if we can't get a fix, it will use the last one
     if aquaGPS.checkForFix():
         (self.lat, self.lon) = aquaGPS.getCoord()
         t = dataLogger.makeTimeStamp()
         # log GPS data
         gpsData = '%s\t%s\t%s\n' % (t, self.lat, self.lon)
         dataLogger.writeToFile(self.gpsFileName, gpsData)
     # check if we are home - if so, transition to commute
     if (aquaGPS.homeZone(self.lat, self.lon)):
         self.back_again()
     # if not, continue to log data
     else:
         self.collectData()
Beispiel #10
0
 def housekeep(self):
     utility.printAndLog('housekeeping')
     illuminator.sign()
     dataLogger.uploadData(self)
Beispiel #11
0
def inactDetected(pin):
    utility.printAndLog('inactivity detected!')
    if (aqC.state == 'commute'):
        aqC.slumber()
Beispiel #12
0
def actDetected(pin):
    utility.printAndLog('activity detected!')
    if (aqC.state == 'nap'):
        aqC.awaken()
Beispiel #13
0
                    print('ending turn')
                    aqC.turningLeft = False
                    doLights()
                    return
        else:
            # begin turn
            utility.printAndLog('beginning right turn')
            aqC.turningRight = True
            while (aqC.turningRight):
                # blink and check for the signal to stop
                illuminator.blinkRight()
                if (GPIO.input(endTurn)):
                    print('ending turn')
                    aqC.turningRight = False
                    doLights()
                    return


GPIO.add_event_detect(actPin, GPIO.RISING, actDetected)
GPIO.add_event_detect(inactPin, GPIO.RISING, inactDetected)
GPIO.add_event_detect(leftTurn, GPIO.RISING, turnButton, bouncetime=5000)
GPIO.add_event_detect(rightTurn, GPIO.RISING, turnButton, bouncetime=5000)
utility.printAndLog('GPIO interrupts ready')
time.sleep(5)
utility.printAndLog('clearing accel status register')
adxl.clearInterrupts()

# lurk patiently in the background, forever....
while True:
    lurk()