<commit_before>#!/usr/bin/python
# @Author: Eddie Ruano
# @Date:   2017-05-01 05:14:54
# @Last Modified by:   Eddie Ruano
# @Last Modified time: 2017-06-13 20:20:19
#
"""
    MissionControl.py is a debugging tool for DESI_Sentinel
"""
################################## IMPORTS ###################################
import sys
import os.path
import signal
import time
#
import collections
import pyaudio
import wave
from math import floor
# Customs Mods #
import RPi.GPIO as GPIO
import Sentinel as Sentinel
# Local Modules #
################################### PATHS #####################################
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import drivers.VoyagerHCSR04 as VoyagerHCSR04
import DESIConfig as DESIConfig
import drivers.MPR121 as MPR121
#import trigger.snowboydetect as snowboydetect
############################ INITIALIZE CLASSES ###############################
DESI = DESIConfig.DESI()
Voyager1 = VoyagerHCSR04.Voyager("Voyager1", DESI.PROX1_TRIG, DESI.PROX1_ECHO)
Voyager2 = VoyagerHCSR04.Voyager("Voyager2", DESI.PROX2_TRIG, DESI.PROX2_ECHO)
TouchSense = MPR121.MPR121()
Sentinel = Sentinel.Sentinel()
################################## PATHS ######################################
def main():
    # Variables/Flags
    flagRailWarning = False
    flagSelectorWarning = False
    flagProximityWarning = False
    flagRedux = False
    flagStartSet = False
    # Initialize DESI States
    DESI.initDESI()
    # Initialize Voyager Proximity Sensors
    DESI.initProximity(Voyager1, Voyager2)
    try:
        if not TouchSense.begin():  # Init TouchSense Capacitive Sensor Array
            print("TSense Error")
            sys.exit(1)
    except OSError as e:
        print(e)
        print("Sensor Error.")
        sys.exit(1)
    Sentinel.getStateKnob(DESI)
    Sentinel.setStateKnob()
    time.sleep(1)
    Sentinel.getStateKnob(DESI)
    Sentinel.setStateKnob()
    Sentinel.updateActiveLock(TouchSense)
    # Single Start Trigger
    GPIO.add_event_detect(DESI.IN_START, GPIO.FALLING, callback=StartHandler, bouncetime=Sentinel.CONST_BOUNCE)
    try:
        print("Listening")
        #Wait for the Start Command
        while not Sentinel.StartDetect:
            Sentinel.getStateKnob(DESI)
            Sentinel.setStateKnob()
            print("Off")
        #Wait until the correct Knob State Happens
        print("Waiting for knob")
        print(Sentinel.StateKnob)
        while Sentinel.StateKnob != 0.0:
            # if the counter reaches zero issue warning
            if (Sentinel.SpCount == 0):
                DESI.DESISendResponse("audio/wav_sp_sel.wav")
                Sentinel.SpCount = Sentinel.CONST_RESCOUNT
            else:
                # decrement counter
                time.sleep(0.1)
                Sentinel.SpCount-=1
            # we verify here
            Sentinel.getStateKnob(DESI)
            Sentinel.setStateKnob()
        # in correct setting so we wait for speech mutex
        Sentinel.waitMutexSpeech()
        DESI.DESISendResponse("audio/wav_okay_megan.wav")
        # issue start
        Sentinel.waitMutexSpeech()
        DESI.DESISendResponse("audio/wav_lets_start.wav")
        # officially add pause event
        GPIO.add_event_detect(DESI.IN_PAUSE, GPIO.FALLING, callback=PauseHandler, bouncetime=Sentinel.CONST_BOUNCE)
        flagStartSet = True

        while True:
            if Sentinel.flagShut == True:
                continue
            localKnobState = Sentinel.StateKnob
            # Update the ActiveLock
            Sentinel.updateActiveLock(TouchSense)
            # Query the knob states
            Sentinel.getStateKnob(DESI)
            # Set the Knob State according to the recent get
            Sentinel.setStateKnob()
            speed = getSpeed()
            if (Sentinel.StateKnob == 0.0) and (flagStartSet == False):
                GPIO.add_event_detect(DESI.IN_START, GPIO.FALLING, callback=StartHandler, bouncetime=Sentinel.CONST_BOUNCE)
                flagStartSet = True
            elif(flagStartSet == True)
                GPIO.remove_event_detect(DESI.IN_START)
                flagStartSet = False

            # Check if the knob changed position
            if (Sentinel.StateKnob != localKnobState):
                localKnobState = Sentinel.StateKnob
                speed = getSpeed()
                if Sentinel.flagPause == False:
                    DESI.DESISend(speed)
                print("State Indifff")
                print(speed)
            if (Sentinel.CapLock == True):
                continue
            if (Sentinel.ProxLock == True):
                continue
            # Set the Speed if the knob doesn't match up
            #if (Sentinel.StateKnob != Sentinel.ActualSpeed):
            #    DESI.DESISend(Sentinel.StateKnob * 1.0)
            #    Sentinel.ActualSpeed = (speed)
            # Here we check for contact
            """ CAPACITANCE CHECKS """
            # Check for an issue warning
            flagRailWarning = checkRailWarning(flagRailWarning)
            # if we aren't touching
            if not Sentinel.ActiveLock and Sentinel.flagPause == False:
                print("NO CONTACT")
                # If we reach zero on the counter and not in pause
                if ((Sentinel.CapCountdown == 0) and (Sentinel.CapLock == False)):
                    # save current workout state
                    saved_state = Sentinel.StateKnob
                    Sentinel.waitMutexSpeech()
                    DESI.DESISendResponse(DESI.RespondPaused)   #pause
                    DESI.DESISend("Pause")
                    Sentinel.flagPause = True
                    print(DESI.State_Main)
                    # Enable the CapLock
                    Sentinel.CapLock = True
                    print("CapLocked.")
                    # Runs forever until CapLock disabled
                else:
                    # Else we are not making contact but not end of count
                    Sentinel.CapCountdown -= 1
            else:  # we are making contact
                    Sentinel.CapCountdown = Sentinel.CAPCOUNT
                    flagRailWarning = False

            """ START PROXIMITY CHECKS """
            Sentinel.Proximity = queryDistance()
            #print (Sentinel.Proximity)
            if Sentinel.Proximity > 12.0 and Sentinel.flagPause == False:
                flagProximityWarning = True
                # If we reach zero on the counter and not in pause
                if ((Sentinel.ProxCountdown == 0) and (Sentinel.ProxLock == False)):
                    Sentinel.ProximityRetries += 1
                    # reduce speed
                    i = 0.0
                    while i < Sentinel.Redux:
                        #print("Reducing By: " + i)
                        DESI.DESISend("SendDown")
                        i += 1.0
                        flagRedux = True
                        Sentinel.ActualSpeed = Sentinel.ActualSpeed - 0.1
                    # Enable the CapLock
                    if (Sentinel.ProximityRetries > Sentinel.CONST_PROX_RETRIES):
                        Sentinel.ProxLock = True
                        DESI.DESISend("Pause")
                        Sentinel.flagPause = True
                        Sentinel.waitMutexSpeech()
                        DESI.DESISendResponse(DESI.RespondPause)
                        print("ProxLocked.")
                    # Runs forever until CapLock disabled
                else:
                    # Else we are not making contact but not end of count
                    Sentinel.ProxCountdown -= 1
            else:  # we are making contact
                    Sentinel.ProxCountdown = Sentinel.PROXCOUNT
                    flagProximityWarning = False
                    sp = getSpeed()
                    if flagRedux:
                        DESI.DESISend(sp)
                        flagRedux = False
            """"""""""""" END PROXIMITY CHECKS """""""""""""""""""""
            #print(Sentinel.ActualSpeed)
            time.sleep(Sentinel.RunningLoopSpeed)
    except KeyboardInterrupt:
        GPIO.cleanup()
        DESI.DESICleanup()
        print("Shutdown Mission.")
        #Detector.terminate()
### END OF MAIN ###
"""Helper Functions"""
def activateAlexa():
    GPIO.output(DESI.OUT_ALEXA, GPIO.LOW)
    time.sleep(2)
    GPIO.output(DESI.OUT_ALEXA, GPIO.HIGH)
def queryDistance():
    distv1 = Voyager1.get_distance()
    distv2 = Voyager2.get_distance()
    # Sanitize
    distv1 = sanitizeDistance(Voyager1, distv1)
    distv2 = sanitizeDistance(Voyager2, distv2)
    # Subtract 3.5 to get 0
    distv1 = abs(distv1 - 3.5)
    distv2 = abs(distv2 - 3.5)
    if distv1 == -1.0 and distv2 != -1.0:
        print("Check Sensor 1")
        return distv2
    elif distv2 == -1.0 and distv1 != -1.0:
        print("Check Sensor 2")
        return distv1
    else:
        ave = (distv1 + distv2) / 2
    return ave
def sanitizeDistance(voy, inDist):
    tries = 0
    while inDist == -1.0 and tries < Sentinel.ProximityRetries:
        inDist = Voyager1.get_distance()
    return inDist
def StartHandler(channel):
    if (Sentinel.StateKnob == 0.0) and DESI.State_Main == "Pause":
        DESI.DESISend("Shutdown")
        Sentinel.flagShut = True
        GPIO.cleanup()
        print("Shutdown")
        return
    else:
        print("Starting")
        Sentinel.StartDetect = True
        DESI.DESISend("Start")

def getSpeed():
    if Sentinel.StateKnob == 0.0:
        Sentinel.setSpeed(0.0)
        return "Send00"
    elif Sentinel.StateKnob == 1.0:
        Sentinel.setSpeed(2.0)
        return "Send01"
    elif Sentinel.StateKnob == 2.0:
        Sentinel.setSpeed(2.5)
        return "Send02"
    elif Sentinel.StateKnob == 3.0:
        Sentinel.setSpeed(3.0)
        return "Send03"
    elif Sentinel.StateKnob == 4.0:
        Sentinel.setSpeed(3.5)
        return "Send04"
    else:
        return "Send00"
def PauseHandler(channel):
    print("pause")
    DESI.DESISend("Pause")
    Sentinel.flagPause = not Sentinel.flagPause
    if Sentinel.CapLock == True:
        Sentinel.CapLock = False
    elif Sentinel.ProxLock == True:
        Sentinel.ProxLock = False
        Sentinel.ProximityRetries = 0
def checkRailWarning(flag):
    if ((Sentinel.ActiveLock == False) and (flag == False)):
        if (Sentinel.CapCountdown == (Sentinel.CAPCOUNT / 2)):
            DESI.DESISendResponse(DESI.RespondRails)
        return True
    return False

#def signal_handler(signal, frame):
#    global HotwordInterrupt
#    HotwordInterrupt = True
#def interrupt_callback():
#    global HotwordInterrupt
#    return HotwordInterrupt
### MAIN CALL ###
if __name__ == "__main__":
    main()<commit_msg>Script<commit_after>#!/usr/bin/python
# @Author: Eddie Ruano
# @Date:   2017-05-01 05:14:54
# @Last Modified by:   Eddie Ruano
# @Last Modified time: 2017-06-13 20:20:35
#
"""
    MissionControl.py is a debugging tool for DESI_Sentinel
"""
################################## IMPORTS ###################################
import sys
import os.path
import signal
import time
#
import collections
import pyaudio
import wave
from math import floor
# Customs Mods #
import RPi.GPIO as GPIO
import Sentinel as Sentinel
# Local Modules #
################################### PATHS #####################################
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import drivers.VoyagerHCSR04 as VoyagerHCSR04
import DESIConfig as DESIConfig
import drivers.MPR121 as MPR121
#import trigger.snowboydetect as snowboydetect
############################ INITIALIZE CLASSES ###############################
DESI = DESIConfig.DESI()
Voyager1 = VoyagerHCSR04.Voyager("Voyager1", DESI.PROX1_TRIG, DESI.PROX1_ECHO)
Voyager2 = VoyagerHCSR04.Voyager("Voyager2", DESI.PROX2_TRIG, DESI.PROX2_ECHO)
TouchSense = MPR121.MPR121()
Sentinel = Sentinel.Sentinel()
################################## PATHS ######################################
def main():
    # Variables/Flags
    flagRailWarning = False
    flagSelectorWarning = False
    flagProximityWarning = False
    flagRedux = False
    flagStartSet = False
    # Initialize DESI States
    DESI.initDESI()
    # Initialize Voyager Proximity Sensors
    DESI.initProximity(Voyager1, Voyager2)
    try:
        if not TouchSense.begin():  # Init TouchSense Capacitive Sensor Array
            print("TSense Error")
            sys.exit(1)
    except OSError as e:
        print(e)
        print("Sensor Error.")
        sys.exit(1)
    Sentinel.getStateKnob(DESI)
    Sentinel.setStateKnob()
    time.sleep(1)
    Sentinel.getStateKnob(DESI)
    Sentinel.setStateKnob()
    Sentinel.updateActiveLock(TouchSense)
    # Single Start Trigger
    GPIO.add_event_detect(DESI.IN_START, GPIO.FALLING, callback=StartHandler, bouncetime=Sentinel.CONST_BOUNCE)
    try:
        print("Listening")
        #Wait for the Start Command
        while not Sentinel.StartDetect:
            Sentinel.getStateKnob(DESI)
            Sentinel.setStateKnob()
            print("Off")
        #Wait until the correct Knob State Happens
        print("Waiting for knob")
        print(Sentinel.StateKnob)
        while Sentinel.StateKnob != 0.0:
            # if the counter reaches zero issue warning
            if (Sentinel.SpCount == 0):
                DESI.DESISendResponse("audio/wav_sp_sel.wav")
                Sentinel.SpCount = Sentinel.CONST_RESCOUNT
            else:
                # decrement counter
                time.sleep(0.1)
                Sentinel.SpCount-=1
            # we verify here
            Sentinel.getStateKnob(DESI)
            Sentinel.setStateKnob()
        # in correct setting so we wait for speech mutex
        Sentinel.waitMutexSpeech()
        DESI.DESISendResponse("audio/wav_okay_megan.wav")
        # issue start
        Sentinel.waitMutexSpeech()
        DESI.DESISendResponse("audio/wav_lets_start.wav")
        # officially add pause event
        GPIO.add_event_detect(DESI.IN_PAUSE, GPIO.FALLING, callback=PauseHandler, bouncetime=Sentinel.CONST_BOUNCE)
        flagStartSet = True

        while True:
            if Sentinel.flagShut == True:
                continue
            localKnobState = Sentinel.StateKnob
            # Update the ActiveLock
            Sentinel.updateActiveLock(TouchSense)
            # Query the knob states
            Sentinel.getStateKnob(DESI)
            # Set the Knob State according to the recent get
            Sentinel.setStateKnob()
            speed = getSpeed()
            if (Sentinel.StateKnob == 0.0) and (flagStartSet == False):
                GPIO.add_event_detect(DESI.IN_START, GPIO.FALLING, callback=StartHandler, bouncetime=Sentinel.CONST_BOUNCE)
                flagStartSet = True
            elif(flagStartSet == True):
                GPIO.remove_event_detect(DESI.IN_START)
                flagStartSet = False

            # Check if the knob changed position
            if (Sentinel.StateKnob != localKnobState):
                localKnobState = Sentinel.StateKnob
                speed = getSpeed()
                if Sentinel.flagPause == False:
                    DESI.DESISend(speed)
                print("State Indifff")
                print(speed)
            if (Sentinel.CapLock == True):
                continue
            if (Sentinel.ProxLock == True):
                continue
            # Set the Speed if the knob doesn't match up
            #if (Sentinel.StateKnob != Sentinel.ActualSpeed):
            #    DESI.DESISend(Sentinel.StateKnob * 1.0)
            #    Sentinel.ActualSpeed = (speed)
            # Here we check for contact
            """ CAPACITANCE CHECKS """
            # Check for an issue warning
            flagRailWarning = checkRailWarning(flagRailWarning)
            # if we aren't touching
            if not Sentinel.ActiveLock and Sentinel.flagPause == False:
                print("NO CONTACT")
                # If we reach zero on the counter and not in pause
                if ((Sentinel.CapCountdown == 0) and (Sentinel.CapLock == False)):
                    # save current workout state
                    saved_state = Sentinel.StateKnob
                    Sentinel.waitMutexSpeech()
                    DESI.DESISendResponse(DESI.RespondPaused)   #pause
                    DESI.DESISend("Pause")
                    Sentinel.flagPause = True
                    print(DESI.State_Main)
                    # Enable the CapLock
                    Sentinel.CapLock = True
                    print("CapLocked.")
                    # Runs forever until CapLock disabled
                else:
                    # Else we are not making contact but not end of count
                    Sentinel.CapCountdown -= 1
            else:  # we are making contact
                    Sentinel.CapCountdown = Sentinel.CAPCOUNT
                    flagRailWarning = False

            """ START PROXIMITY CHECKS """
            Sentinel.Proximity = queryDistance()
            #print (Sentinel.Proximity)
            if Sentinel.Proximity > 12.0 and Sentinel.flagPause == False:
                flagProximityWarning = True
                # If we reach zero on the counter and not in pause
                if ((Sentinel.ProxCountdown == 0) and (Sentinel.ProxLock == False)):
                    Sentinel.ProximityRetries += 1
                    # reduce speed
                    i = 0.0
                    while i < Sentinel.Redux:
                        #print("Reducing By: " + i)
                        DESI.DESISend("SendDown")
                        i += 1.0
                        flagRedux = True
                        Sentinel.ActualSpeed = Sentinel.ActualSpeed - 0.1
                    # Enable the CapLock
                    if (Sentinel.ProximityRetries > Sentinel.CONST_PROX_RETRIES):
                        Sentinel.ProxLock = True
                        DESI.DESISend("Pause")
                        Sentinel.flagPause = True
                        Sentinel.waitMutexSpeech()
                        DESI.DESISendResponse(DESI.RespondPause)
                        print("ProxLocked.")
                    # Runs forever until CapLock disabled
                else:
                    # Else we are not making contact but not end of count
                    Sentinel.ProxCountdown -= 1
            else:  # we are making contact
                    Sentinel.ProxCountdown = Sentinel.PROXCOUNT
                    flagProximityWarning = False
                    sp = getSpeed()
                    if flagRedux:
                        DESI.DESISend(sp)
                        flagRedux = False
            """"""""""""" END PROXIMITY CHECKS """""""""""""""""""""
            #print(Sentinel.ActualSpeed)
            time.sleep(Sentinel.RunningLoopSpeed)
    except KeyboardInterrupt:
        GPIO.cleanup()
        DESI.DESICleanup()
        print("Shutdown Mission.")
        #Detector.terminate()
### END OF MAIN ###
"""Helper Functions"""
def activateAlexa():
    GPIO.output(DESI.OUT_ALEXA, GPIO.LOW)
    time.sleep(2)
    GPIO.output(DESI.OUT_ALEXA, GPIO.HIGH)
def queryDistance():
    distv1 = Voyager1.get_distance()
    distv2 = Voyager2.get_distance()
    # Sanitize
    distv1 = sanitizeDistance(Voyager1, distv1)
    distv2 = sanitizeDistance(Voyager2, distv2)
    # Subtract 3.5 to get 0
    distv1 = abs(distv1 - 3.5)
    distv2 = abs(distv2 - 3.5)
    if distv1 == -1.0 and distv2 != -1.0:
        print("Check Sensor 1")
        return distv2
    elif distv2 == -1.0 and distv1 != -1.0:
        print("Check Sensor 2")
        return distv1
    else:
        ave = (distv1 + distv2) / 2
    return ave
def sanitizeDistance(voy, inDist):
    tries = 0
    while inDist == -1.0 and tries < Sentinel.ProximityRetries:
        inDist = Voyager1.get_distance()
    return inDist
def StartHandler(channel):
    if (Sentinel.StateKnob == 0.0) and DESI.State_Main == "Pause":
        DESI.DESISend("Shutdown")
        Sentinel.flagShut = True
        GPIO.cleanup()
        print("Shutdown")
        return
    else:
        print("Starting")
        Sentinel.StartDetect = True
        DESI.DESISend("Start")

def getSpeed():
    if Sentinel.StateKnob == 0.0:
        Sentinel.setSpeed(0.0)
        return "Send00"
    elif Sentinel.StateKnob == 1.0:
        Sentinel.setSpeed(2.0)
        return "Send01"
    elif Sentinel.StateKnob == 2.0:
        Sentinel.setSpeed(2.5)
        return "Send02"
    elif Sentinel.StateKnob == 3.0:
        Sentinel.setSpeed(3.0)
        return "Send03"
    elif Sentinel.StateKnob == 4.0:
        Sentinel.setSpeed(3.5)
        return "Send04"
    else:
        return "Send00"
def PauseHandler(channel):
    print("pause")
    DESI.DESISend("Pause")
    Sentinel.flagPause = not Sentinel.flagPause
    if Sentinel.CapLock == True:
        Sentinel.CapLock = False
    elif Sentinel.ProxLock == True:
        Sentinel.ProxLock = False
        Sentinel.ProximityRetries = 0
def checkRailWarning(flag):
    if ((Sentinel.ActiveLock == False) and (flag == False)):
        if (Sentinel.CapCountdown == (Sentinel.CAPCOUNT / 2)):
            DESI.DESISendResponse(DESI.RespondRails)
        return True
    return False

#def signal_handler(signal, frame):
#    global HotwordInterrupt
#    HotwordInterrupt = True
#def interrupt_callback():
#    global HotwordInterrupt
#    return HotwordInterrupt
### MAIN CALL ###
if __name__ == "__main__":
    main()<|endoftext|>


<commit_before>#
# Copyright 2012-2014 John Whitlock
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Define Trip model for rows in trips.txt

Google documentation from
https://developers.google.com/transit/gtfs/reference

trips.txt is required

- route_id (required)
The route_id field contains an ID that uniquely identifies a route. This value
is referenced from the routes.txt file.

- service_id (required)
The service_id contains an ID that uniquely identifies a set of dates when
service is available for one or more routes. This value is referenced from the
calendar.txt or calendar_dates.txt file.

- trip_id (required)
The trip_id field contains an ID that identifies a trip. The trip_id is dataset
unique.

- trip_headsign (optional)
The trip_headsign field contains the text that appears on a sign that
identifies the trip's destination to passengers. Use this field to distinguish
between different patterns of service in the same route. If the headsign
changes during a trip, you can override the trip_headsign by specifying values
for the the stop_headsign field in stop_times.txt.

See a Google Maps screenshot highlighting the headsign:
  http://bit.ly/A3ot2j

- trip_short_name (optional)
The trip_short_name field contains the text that appears in schedules and sign
boards to identify the trip to passengers, for example, to identify train
numbers for commuter rail trips. If riders do not commonly rely on trip names,
please leave this field blank.

A trip_short_name value, if provided, should uniquely identify a trip within a
service day; it should not be used for destination names or limited/express
designations.

- direction_id (optional)
The direction_id field contains a binary value that indicates the direction of
travel for a trip. Use this field to distinguish between bi-directional trips
with the same route_id. This field is not used in routing; it provides a way to
separate trips by direction when publishing time tables. You can specify names
for each direction with the trip_headsign field.

    * 0 - travel in one direction (e.g. outbound travel)
    * 1 - travel in the opposite direction (e.g. inbound travel)

For example, you could use the trip_headsign and direction_id fields together
to assign a name to travel in each direction on trip "1234", the trips.txt file
would contain these rows for use in time tables:

    trip_id, ... ,trip_headsign,direction_id
    1234, ... , to Airport,0
    1505, ... , to Downtown,1

- block_id (optional)
The block_id field identifies the block to which the trip belongs. A block
consists of two or more sequential trips made using the same vehicle, where a
passenger can transfer from one trip to the next just by staying in the
vehicle. The block_id must be referenced by two or more trips in trips.txt.

- shape_id (optional)
The shape_id field contains an ID that defines a shape for the trip. This value
is referenced from the shapes.txt file. The shapes.txt file allows you to
define how a line should be drawn on the map to represent a trip.

- wheelchair_accessible (optional)
    * 0 (or empty) - indicates that there is no accessibility information for
        the trip
    * 1 - indicates that the vehicle being used on this particular trip can
        accommodate at least one rider in a wheelchair
    * 2 - indicates that no riders in wheelchairs can be accommodated on this
        trip

- bikes_allowed (optional)
    * 0 (or empty) - indicates that there is no bike information for the trip
    * 1 - indicates that the vehicle being used on this particular trip can
        accommodate at least one bicycle
    * 2 - indicates that no bicycles are allowed on this trip
"""
from __future__ import unicode_literals

from django.contrib.gis.geos import LineString
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField

from multigtfs.models.base import models, Base

@python_2_unicode_compatible
class Trip(Base):
    """A trip along a route"""

    route = models.ForeignKey('Route')
    service = models.ForeignKey('Service', null=True, blank=True)
    trip_id = models.CharField(
        max_length=255, db_index=True,
        help_text="Unique identifier for a trip.")
    headsign = models.CharField(
        max_length=255, blank=True,
        help_text="Destination identification for passengers.")
    short_name = models.CharField(
        max_length=63, blank=True,
        help_text="Short name used in schedules and signboards.")
    direction = models.CharField(
        max_length=1, blank=True,
        choices=(('0', 'Outbound'), ('1', 'Inbound')),
        help_text="Direction for bi-directional routes.")
    block = models.ForeignKey(
        'Block', null=True, blank=True,
        help_text="Block of sequential trips that this trip belongs to.")
    shape = models.ForeignKey(
        'Shape', null=True, blank=True,
        help_text="Shape used for this trip")
    geometry = models.LineStringField(
        null=True, blank=True,
        help_text='Geometry cache of Shape or Stops')
    wheelchair_accessible = models.CharField(
        max_length=1, blank=True,
        choices=(
            ('0', 'No information'),
            ('1', 'Some wheelchair accommodation'),
            ('2', 'No wheelchair accommodation')),
        help_text='Are there accommodations for riders with wheelchair?')
    bikes_allowed = models.CharField(
        max_length=1, blank=True,
        choices=(
            ('0', 'No information'),
            ('1', 'Some bicycle accommodation'),
            ('2', 'No bicycles allowed')),
        help_text='Are bicycles allowed?')
    extra_data = JSONField(default={})

    def update_geometry(self, update_parent=True):
        """Update the geometry from the Shape or Stops"""
        original = self.geometry
        if self.shape:
            self.geometry = self.shape.geometry
        else:
            stoptimes = self.stoptime_set.order_by('stop_sequence')
            if stoptimes.count() > 1:
                self.geometry = LineString(
                    [st.stop.point.coords for st in stoptimes])
        if self.geometry != original:
            self.save()
            if update_parent:
                self.route.update_geometry()

    def __str__(self):
        return "%s-%s" % (self.route, self.trip_id)

    class Meta:
        db_table = 'trip'
        app_label = 'multigtfs'

    _column_map = (
        ('route_id', 'route__route_id'),
        ('service_id', 'service__service_id'),
        ('trip_id', 'trip_id'),
        ('trip_headsign', 'headsign'),
        ('trip_short_name', 'short_name'),
        ('direction_id', 'direction'),
        ('block_id', 'block__block_id'),
        ('shape_id', 'shape__shape_id'),
        ('wheelchair_accessible', 'wheelchair_accessible'),
        ('bikes_allowed', 'bikes_allowed'),
    )
    _filename = 'trips.txt'
    _rel_to_feed = 'route__feed'
    _unique_fields = ('trip_id',)
<commit_msg>On trip, change inbound/outbound to 0/1<commit_after>#
# Copyright 2012-2014 John Whitlock
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Define Trip model for rows in trips.txt

Google documentation from
https://developers.google.com/transit/gtfs/reference

trips.txt is required

- route_id (required)
The route_id field contains an ID that uniquely identifies a route. This value
is referenced from the routes.txt file.

- service_id (required)
The service_id contains an ID that uniquely identifies a set of dates when
service is available for one or more routes. This value is referenced from the
calendar.txt or calendar_dates.txt file.

- trip_id (required)
The trip_id field contains an ID that identifies a trip. The trip_id is dataset
unique.

- trip_headsign (optional)
The trip_headsign field contains the text that appears on a sign that
identifies the trip's destination to passengers. Use this field to distinguish
between different patterns of service in the same route. If the headsign
changes during a trip, you can override the trip_headsign by specifying values
for the the stop_headsign field in stop_times.txt.

See a Google Maps screenshot highlighting the headsign:
  http://bit.ly/A3ot2j

- trip_short_name (optional)
The trip_short_name field contains the text that appears in schedules and sign
boards to identify the trip to passengers, for example, to identify train
numbers for commuter rail trips. If riders do not commonly rely on trip names,
please leave this field blank.

A trip_short_name value, if provided, should uniquely identify a trip within a
service day; it should not be used for destination names or limited/express
designations.

- direction_id (optional)
The direction_id field contains a binary value that indicates the direction of
travel for a trip. Use this field to distinguish between bi-directional trips
with the same route_id. This field is not used in routing; it provides a way to
separate trips by direction when publishing time tables. You can specify names
for each direction with the trip_headsign field.

    * 0 - travel in one direction (e.g. outbound travel)
    * 1 - travel in the opposite direction (e.g. inbound travel)

For example, you could use the trip_headsign and direction_id fields together
to assign a name to travel in each direction on trip "1234", the trips.txt file
would contain these rows for use in time tables:

    trip_id, ... ,trip_headsign,direction_id
    1234, ... , to Airport,0
    1505, ... , to Downtown,1

- block_id (optional)
The block_id field identifies the block to which the trip belongs. A block
consists of two or more sequential trips made using the same vehicle, where a
passenger can transfer from one trip to the next just by staying in the
vehicle. The block_id must be referenced by two or more trips in trips.txt.

- shape_id (optional)
The shape_id field contains an ID that defines a shape for the trip. This value
is referenced from the shapes.txt file. The shapes.txt file allows you to
define how a line should be drawn on the map to represent a trip.

- wheelchair_accessible (optional)
    * 0 (or empty) - indicates that there is no accessibility information for
        the trip
    * 1 - indicates that the vehicle being used on this particular trip can
        accommodate at least one rider in a wheelchair
    * 2 - indicates that no riders in wheelchairs can be accommodated on this
        trip

- bikes_allowed (optional)
    * 0 (or empty) - indicates that there is no bike information for the trip
    * 1 - indicates that the vehicle being used on this particular trip can
        accommodate at least one bicycle
    * 2 - indicates that no bicycles are allowed on this trip
"""
from __future__ import unicode_literals

from django.contrib.gis.geos import LineString
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField

from multigtfs.models.base import models, Base

@python_2_unicode_compatible
class Trip(Base):
    """A trip along a route"""

    route = models.ForeignKey('Route')
    service = models.ForeignKey('Service', null=True, blank=True)
    trip_id = models.CharField(
        max_length=255, db_index=True,
        help_text="Unique identifier for a trip.")
    headsign = models.CharField(
        max_length=255, blank=True,
        help_text="Destination identification for passengers.")
    short_name = models.CharField(
        max_length=63, blank=True,
        help_text="Short name used in schedules and signboards.")
    direction = models.CharField(
        max_length=1, blank=True,
        choices=(('0', '0'), ('1', '1')),
        help_text="Direction for bi-directional routes.")
    block = models.ForeignKey(
        'Block', null=True, blank=True,
        help_text="Block of sequential trips that this trip belongs to.")
    shape = models.ForeignKey(
        'Shape', null=True, blank=True,
        help_text="Shape used for this trip")
    geometry = models.LineStringField(
        null=True, blank=True,
        help_text='Geometry cache of Shape or Stops')
    wheelchair_accessible = models.CharField(
        max_length=1, blank=True,
        choices=(
            ('0', 'No information'),
            ('1', 'Some wheelchair accommodation'),
            ('2', 'No wheelchair accommodation')),
        help_text='Are there accommodations for riders with wheelchair?')
    bikes_allowed = models.CharField(
        max_length=1, blank=True,
        choices=(
            ('0', 'No information'),
            ('1', 'Some bicycle accommodation'),
            ('2', 'No bicycles allowed')),
        help_text='Are bicycles allowed?')
    extra_data = JSONField(default={})

    def update_geometry(self, update_parent=True):
        """Update the geometry from the Shape or Stops"""
        original = self.geometry
        if self.shape:
            self.geometry = self.shape.geometry
        else:
            stoptimes = self.stoptime_set.order_by('stop_sequence')
            if stoptimes.count() > 1:
                self.geometry = LineString(
                    [st.stop.point.coords for st in stoptimes])
        if self.geometry != original:
            self.save()
            if update_parent:
                self.route.update_geometry()

    def __str__(self):
        return "%s-%s" % (self.route, self.trip_id)

    class Meta:
        db_table = 'trip'
        app_label = 'multigtfs'

    _column_map = (
        ('route_id', 'route__route_id'),
        ('service_id', 'service__service_id'),
        ('trip_id', 'trip_id'),
        ('trip_headsign', 'headsign'),
        ('trip_short_name', 'short_name'),
        ('direction_id', 'direction'),
        ('block_id', 'block__block_id'),
        ('shape_id', 'shape__shape_id'),
        ('wheelchair_accessible', 'wheelchair_accessible'),
        ('bikes_allowed', 'bikes_allowed'),
    )
    _filename = 'trips.txt'
    _rel_to_feed = 'route__feed'
    _unique_fields = ('trip_id',)
<|endoftext|>


<commit_before>"""A device to test loading devices. It doesn't do anything."""

###############################################################################
#
# TODO: [ ]
#
###############################################################################

# standard library imports
import logging
import math
import time

# related third party imports
try:
    import pigpio
except ImportError:
    pigpio = None

# application specific imports
# pylint: disable=import-error
from core import subscribe_to
from devices.device import BaseClass
# pylint: enable=import-error

__version__ = "1.1.1"

# Initialize the logger
LOGGER = logging.getLogger(__name__)

if pigpio:
    PI = pigpio.pi("192.168.178.56")
else:
    LOGGER.exception(
        "Could not import pigpio. Please follow the instructions on %s to "
        "install it manually.",
        "https://github.com/joan2937/pigpio/blob/master/README#L103")

if PI.connected:
    RED_PINS = [12, 25]
    GREEN_PINS = [20, 23]
    BLUE_PINS = [21, 18]
else:
    LOGGER.error("Could not connect to the RasPi at 192.168.178.56.")

DEVICE = BaseClass("LED", PI.connected, LOGGER, __file__)

def _set_pins(red=-1, green=-1, blue=-1):
    if 0 <= red <= 255:
        for pin in RED_PINS:
            PI.set_PWM_dutycycle(pin, red)
    if 0 <= green <= 255:
        for pin in GREEN_PINS:
            PI.set_PWM_dutycycle(pin, green)
    if 0 <= blue <= 255:
        for pin in BLUE_PINS:
            PI.set_PWM_dutycycle(pin, blue)

def _spread(steps, length=255, interpolator=None):
    """Spread an amount of 'steps' evenly in a list with 'length' items."""

    if length == 0:
        return []
    if steps == 0:
        return [0] * steps

    # Convert the args to floats
    length = float(length)
    steps = float(steps)

    def linear(x):
        """Linear function. linear(0) = 0, linear(length) = steps."""
        return round(x*(steps/length))

    def squared(x):
        """Squared function. squared(0) = 0, squared(length) = steps."""
        return round(x*x*(steps/(length*length)))

    def root(x):
        """Square root function. root(0) = 0, root(length) = steps."""
        return round((steps*math.sqrt(length)*math.sqrt(x))/length)

    if interpolator == "linear" or (interpolator is None and steps == 0):
        func = linear
    elif interpolator == "squared" or (interpolator is None and steps > 0):
        func = squared
    elif interpolator == "sqrt" or (interpolator is None and steps < 0):
        func = root

    # Create a 'length' long list with evenly distributed items [0 ... 'steps']
    result = [func(x) for x in range(1, int(length)+1)]
    # For each item, set the item to it's rounded difference to the item before
    val = 0.0
    for i, value in enumerate(result):
        result[i], val = int(value - val), value
    return result

def _crossfade(red=-1, green=-1, blue=-1, speed=1.0, interpolator="linear"):
    steps = int(256 * speed)
    if 0 <= red <= 255:
        red_is = PI.get_PWM_dutycycle(RED_PINS[0])
        red_list = _spread((red - red_is), steps, interpolator)
    if 0 <= green <= 255:
        green_is = PI.get_PWM_dutycycle(GREEN_PINS[0])
        green_list = _spread((green - green_is), steps, interpolator)
    if 0 <= blue <= 255:
        blue_is = PI.get_PWM_dutycycle(BLUE_PINS[0])
        blue_list = _spread((blue - blue_is), steps, interpolator)
    for i in range(steps):
        if red_list[i] is not 0:
            red_is += red_list[i]
        if green_list[i] is not 0:
            green_is += green_list[i]
        if blue_list[i] is not 0:
            blue_is += blue_list[i]
        _set_pins(red_is, green_is, blue_is)

@subscribe_to("system.onstart")
def start_func(key, data):
    """Test the 'onstart' event."""
    _set_pins(0, 0, 0)
    _crossfade(red=255, green=0, blue=0, speed=0.2)
    _crossfade(red=0, green=255, blue=0, speed=0.2)
    _crossfade(red=0, green=0, blue=255, speed=0.2)
    _crossfade(red=0, green=0, blue=0, speed=0.2)
    # _crossfade(255, 85, 17)
    return True

@subscribe_to("test.led")
def test_interpolators(key, data):
    """Test the different interpolators."""
    _crossfade(0, 0, 0, 0.2)
    _crossfade(red=255, green=0, blue=0, interpolator="sqrt")
    _set_pins(0, 0, 0)
    time.sleep(0.5)
    _set_pins(255, 0, 0)
    _crossfade(red=0, green=0, blue=0, interpolator="sqrt")
    time.sleep(0.5)
    _crossfade(red=0, green=255, blue=0, interpolator="linear")
    _set_pins(0, 0, 0)
    time.sleep(0.5)
    _set_pins(0, 255, 0)
    _crossfade(red=0, green=0, blue=0, interpolator="linear")
    time.sleep(0.5)
    _crossfade(red=0, green=0, blue=255, interpolator="squared")
    _set_pins(0, 0, 0)
    time.sleep(0.5)
    _set_pins(0, 0, 255)
    _crossfade(red=0, green=0, blue=0, interpolator="squared")
    # _crossfade(255, 85, 17)
    return True

@subscribe_to("turn_on.led")
def turn_on(key, data):
    """Turn on all lights."""
    _crossfade(255, 85, 17, 0.2)
    return True

@subscribe_to(["system.onexit", "turn_off.led"])
def turn_off(key, data):
    """Turn off all lights."""
    _crossfade(0, 0, 0, 0.2)
    return True
<commit_msg>:wrench: a bunch of fixes<commit_after>"""A device to test loading devices. It doesn't do anything."""

###############################################################################
#
# TODO: [ ]
#
###############################################################################

# standard library imports
import logging
import math
import time

# related third party imports
try:
    import pigpio
except ImportError:
    pigpio = None

# application specific imports
# pylint: disable=import-error
from core import subscribe_to
from devices.device import BaseClass
# pylint: enable=import-error

__version__ = "1.1.2"

# Initialize the logger
LOGGER = logging.getLogger(__name__)

if pigpio:
    PI = pigpio.pi("192.168.178.56")
else:
    LOGGER.exception(
        "Could not import pigpio. Please follow the instructions on %s to "
        "install it manually.",
        "https://github.com/joan2937/pigpio/blob/master/README#L103")

if PI.connected:
    RED_PINS = [12, 25]
    GREEN_PINS = [20, 23]
    BLUE_PINS = [21, 18]
else:
    LOGGER.error("Could not connect to the RasPi at 192.168.178.56.")

DEVICE = BaseClass("LED", PI.connected, LOGGER, __file__)

def _set_pins(red=-1, green=-1, blue=-1):
    if 0 <= red <= 255:
        for pin in RED_PINS:
            PI.set_PWM_dutycycle(pin, red)
    if 0 <= green <= 255:
        for pin in GREEN_PINS:
            PI.set_PWM_dutycycle(pin, green)
    if 0 <= blue <= 255:
        for pin in BLUE_PINS:
            PI.set_PWM_dutycycle(pin, blue)

def _spread(steps, length=256, interpolator=None):
    """Spread an amount of 'steps' evenly in a list with 'length' items."""

    if length == 0:
        return []
    if steps == 0:
        return [0] * length

    # Convert the args to floats
    length = float(length)
    steps = float(steps)

    def linear(x):
        """Linear function. linear(0) = 0, linear(length) = steps."""
        return round(x*(steps/length))

    def squared(x):
        """Squared function. squared(0) = 0, squared(length) = steps."""
        return round(x*x*(steps/(length*length)))

    def root(x):
        """Square root function. root(0) = 0, root(length) = steps."""
        return round((steps*math.sqrt(length)*math.sqrt(x))/length)

    if interpolator == "linear" or (interpolator is None and steps == 0):
        func = linear
    elif interpolator == "squared" or (interpolator is None and steps > 0):
        func = squared
    elif interpolator == "sqrt" or (interpolator is None and steps < 0):
        func = root

    # Create a 'length' long list with evenly distributed items [0 ... 'steps']
    result = [func(x) for x in range(1, int(length)+1)]
    # For each item, set the item to it's rounded difference to the item before
    val = 0.0
    for i, value in enumerate(result):
        result[i], val = int(value - val), value
    return result

def _crossfade(red=-1, green=-1, blue=-1, speed=1.0, interpolator=None):
    steps = int(256 * speed)
    if 0 <= red <= 255:
        red_is = PI.get_PWM_dutycycle(RED_PINS[0])
        red_list = _spread((red - red_is), steps, interpolator)
    if 0 <= green <= 255:
        green_is = PI.get_PWM_dutycycle(GREEN_PINS[0])
        green_list = _spread((green - green_is), steps, interpolator)
    if 0 <= blue <= 255:
        blue_is = PI.get_PWM_dutycycle(BLUE_PINS[0])
        blue_list = _spread((blue - blue_is), steps, interpolator)
    for i in range(steps):
        if red_list[i] is not 0:
            red_is += red_list[i]
        if green_list[i] is not 0:
            green_is += green_list[i]
        if blue_list[i] is not 0:
            blue_is += blue_list[i]
        _set_pins(red_is, green_is, blue_is)

@subscribe_to("system.onstart")
def start_func(key, data):
    """Test the 'onstart' event."""
    _set_pins(0, 0, 0)
    _crossfade(red=255, green=0, blue=0, speed=0.2)
    _crossfade(red=0, green=255, blue=0, speed=0.2)
    _crossfade(red=0, green=0, blue=255, speed=0.2)
    _crossfade(red=0, green=0, blue=0, speed=0.2)
    # _crossfade(255, 85, 17)
    return True

@subscribe_to("test.led")
def test_interpolators(key, data):
    """Test the different interpolators."""
    _crossfade(0, 0, 0, 0.2)
    _crossfade(255, 0, 0, interpolator="sqrt")
    _set_pins(0, 0, 0)
    time.sleep(0.5)
    _set_pins(255, 0, 0)
    _crossfade(0, 0, 0, interpolator="sqrt")
    time.sleep(0.5)
    _crossfade(0, 255, 0, interpolator="linear")
    _set_pins(0, 0, 0)
    time.sleep(0.5)
    _set_pins(0, 255, 0)
    _crossfade(0, 0, 0, interpolator="linear")
    time.sleep(0.5)
    _crossfade(0, 0, 255, interpolator="squared")
    _set_pins(0, 0, 0)
    time.sleep(0.5)
    _set_pins(0, 0, 255)
    _crossfade(0, 0, 0, interpolator="squared")
    # _crossfade(255, 85, 17)
    return True

@subscribe_to("turn_on.led")
def turn_on(key, data):
    """Turn on all lights."""
    _crossfade(255, 85, 17, 0.2)
    return True

@subscribe_to(["system.onexit", "turn_off.led"])
def turn_off(key, data):
    """Turn off all lights."""
    _crossfade(0, 0, 0, 0.2)
    return True
<|endoftext|>


<commit_before>'''
Operations are the core of pyinfra. The ``@operation`` wrapper intercepts calls
to the function and instead diff against the remote server, outputting commands
to the deploy state. This is then run later by pyinfra's ``__main__`` or the
:doc:`./pyinfra.api.operations` module.
'''

from __future__ import unicode_literals

from functools import wraps
from types import FunctionType

import six

import pyinfra

from pyinfra import logger, pseudo_host, pseudo_state

from .command import StringCommand
from .exceptions import OperationValueError, PyinfraError
from .host import Host
from .operation_kwargs import get_execution_kwarg_keys, pop_global_op_kwargs
from .state import State
from .util import (
    get_arg_value,
    get_call_location,
    get_operation_order_from_stack,
    make_hash,
    memoize,
    unroll_generators,
)

# List of available operation names
OPERATIONS = []

def get_operation_names():
    '''
    Returns a list of available operations.
    '''

    return OPERATIONS

class OperationMeta(object):
    def __init__(self, hash=None, commands=None):
        # Wrap all the attributes
        commands = commands or []
        self.commands = commands
        self.hash = hash

        # Changed flag = did we do anything?
        self.changed = len(self.commands) > 0

    def __repr__(self):
        '''Return Operation object as a string.'''
        return 'commands:{} changed:{} hash:{}'.format(
            self.commands, self.changed, self.hash)

def add_op(state, op_func, *args, **kwargs):
    '''
    Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.

    Args:
        state (``pyinfra.api.State`` obj): the deploy state to add the operation
        to op_func (function): the operation function from one of the modules,
        ie ``server.user``
        args/kwargs: passed to the operation function
    '''

    allow_cli_mode = kwargs.pop('_allow_cli_mode', False)
    after_host_callback = kwargs.pop('_after_host_callback', lambda host: None)

    if pyinfra.is_cli and not allow_cli_mode:
        raise PyinfraError((
            '`add_op` should not be called when pyinfra is executing in CLI mode! ({0})'
        ).format(get_call_location()))

    # This ensures that every time an operation is added (API mode), it is simply
    # appended to the operation order.
    kwargs['_op_order_number'] = len(state.op_meta)

    kwargs['state'] = state

    hosts = kwargs.pop('host', state.inventory.iter_active_hosts())
    if isinstance(hosts, Host):
        hosts = [hosts]

    results = {}
    for host in hosts:
        kwargs['host'] = host
        results[host] = op_func(*args, **kwargs)
        after_host_callback(host)

    return results

@memoize
def show_set_name_warning(call_location):
    logger.warning((
        '{0}:\n\tUse of a `set` to name operations is deprecated, '
        'please us the `name` keyword argument.'
    ).format(call_location))

@memoize
def show_state_host_arguments_warning(call_location):
    logger.warning((
        '{0}:\n\tPassing `state` and `host` as the first two arguments to operations is '
        'deprecated, please use `state` and `host` keyword arguments.'
    ).format(call_location))

def operation(func=None, pipeline_facts=None):
    '''
    Decorator that takes a simple module function and turn it into the internal
    operation representation that consists of a list of commands + options
    (sudo, (sudo|su)_user, env).
    '''

    # If not decorating, return function with config attached
    if func is None:
        def decorator(f):
            setattr(f, 'pipeline_facts', pipeline_facts)
            return operation(f)

        return decorator

    # Index the operation!
    module_bits = func.__module__.split('.')
    module_name = module_bits[-1]
    op_name = '.'.join((module_name, func.__name__))
    OPERATIONS.append(op_name)

    # Actually decorate!
    @wraps(func)
    def decorated_func(*args, **kwargs):
        # Prepare state/host
        #

        # State & host passed in as kwargs (API, nested op, @deploy op)
        if 'state' in kwargs and 'host' in kwargs:
            state = kwargs['state']
            host = kwargs['host']

        # State & host passed in as first two arguments (LEGACY)
        elif len(args) >= 2 and isinstance(args[0], State) and isinstance(args[1], Host):
            show_state_host_arguments_warning(get_call_location())
            state = kwargs['state'] = args[0]
            host = kwargs['host'] = args[1]
            args_copy = list(args)
            args = args_copy[2:]

        # Finally, still no state+host? Use pseudo if we're CLI mode, or fail
        elif pyinfra.is_cli:
            state = kwargs['state'] = pseudo_state._module
            host = kwargs['host'] = pseudo_host._module

            if state.in_op:
                raise PyinfraError((
                    'Nested operation called without state/host: {0} ({1})'
                ).format(op_name, get_call_location()))

            if state.in_deploy:
                raise PyinfraError((
                    'Nested deploy operation called without state/host: {0} ({1})'
                ).format(op_name, get_call_location()))

        else:
            raise PyinfraError((
                'API operation called without state/host: {0} ({1})'
            ).format(op_name, get_call_location()))

        # Configure operation
        #

        # Get the meta kwargs (globals that apply to all hosts)
        global_kwargs = pop_global_op_kwargs(state, kwargs)

        # If this op is being called inside another, just return here
        # (any unwanted/op-related kwargs removed above).
        if state.in_op:
            return func(*args, **kwargs) or []

        # Name the operation
        name = global_kwargs.get('name')
        add_args = False

        if name:
            names = {name}

        # Look for a set as the first argument
        # TODO: remove this! COMPAT w/<1
        elif len(args) > 0 and isinstance(args[0], set):
            show_set_name_warning(get_call_location())
            names = args[0]
            args_copy = list(args)
            args = args[1:]

        # Generate an operation name if needed (Module/Operation format)
        else:
            add_args = True
            module_bits = func.__module__.split('.')
            module_name = module_bits[-1]
            names = {
                '{0}/{1}'.format(module_name.title(), func.__name__.title()),
            }

        if state.deploy_name:
            names = {
                '{0} | {1}'.format(state.deploy_name, name)
                for name in names
            }

        op_order = get_operation_order_from_stack(state)

        op_order_number = kwargs.pop('_op_order_number', None)
        if op_order_number is not None:
            op_order = [op_order_number]
        # If we're in API mode, op order number must be provided by calling `add_op`
        elif not pyinfra.is_cli:
            raise PyinfraError((
                'Operation order number not provided in API mode - '
                'you must use `add_op` to add operations.'
            ))

        # Make a hash from the call stack lines
        op_hash = make_hash(op_order)

        # Avoid adding duplicates! This happens if an operation is called within
        # a loop - such that the filename/lineno/code _are_ the same, but the
        # arguments might be different. We just append an increasing number to
        # the op hash and also handle below with the op order.
        host_op_hashes = state.meta[host]['op_hashes']
        duplicate_op_count = 0
        while op_hash in host_op_hashes:
            logger.debug('Duplicate hash ({0}) detected!'.format(op_hash))
            op_hash = '{0}-{1}'.format(op_hash, duplicate_op_count)
            duplicate_op_count += 1

        host_op_hashes.add(op_hash)

        if duplicate_op_count:
            op_order.append(duplicate_op_count)

        op_order = tuple(op_order)

        logger.debug('Adding operation, {0}, opOrder={1}, opHash={2}'.format(
            names, op_order, op_hash,
        ))
        state.op_line_numbers_to_hash[op_order] = op_hash

        # Ensure shared (between servers) operation meta
        op_meta = state.op_meta.setdefault(op_hash, {
            'names': set(),
            'args': [],
        })

        for key in get_execution_kwarg_keys():
            global_value = global_kwargs.pop(key)
            op_meta_value = op_meta.get(key)

            if op_meta_value and global_value != op_meta_value:
                raise OperationValueError('Cannot have different values for `{0}`.'.format(key))

            op_meta[key] = global_value

        # Add any meta kwargs (sudo, etc) to the meta - first parse any strings
        # as jinja templates.
        actual_global_kwargs = {
            key: get_arg_value(state, host, a)
            for key, a in six.iteritems(global_kwargs)
        }

        # Add any new names to the set
        op_meta['names'].update(names)

        # Attach normal args, if we're auto-naming this operation
        if add_args:
            for arg in args:
                if isinstance(arg, FunctionType):
                    arg = arg.__name__

                if arg not in op_meta['args']:
                    op_meta['args'].append(arg)

            # Attach keyword args
            for key, value in six.iteritems(kwargs):
                if isinstance(value, FunctionType):
                    value = value.__name__

                if key in ('state', 'host'):
                    continue

                arg = '='.join((str(key), str(value)))
                if arg not in op_meta['args']:
                    op_meta['args'].append(arg)

        # Check if we're actually running the operation on this host
        #

        # Run once and we've already added meta for this op? Stop here.
        if op_meta['run_once']:
            has_run = False
            for ops in six.itervalues(state.ops):
                if op_hash in ops:
                    has_run = True
                    break

            if has_run:
                return OperationMeta(op_hash)

        # "Run" operation
        #

        # Otherwise, flag as in-op and run it to get the commands
        state.in_op = True
        state.current_op_hash = op_hash
        state.current_op_global_kwargs = actual_global_kwargs

        # Generate actual arguments by parsing strings as jinja2 templates. This
        # means you can string format arguments w/o generating multiple
        # operations. Only affects top level operations, as must be run "in_op"
        # so facts are gathered correctly.
        actual_args = [
            get_arg_value(state, host, a)
            for a in args
        ]

        actual_kwargs = {
            key: get_arg_value(state, host, a)
            for key, a in six.iteritems(kwargs)
        }

        # Convert to list as the result may be a generator
        commands = unroll_generators(func(*actual_args, **actual_kwargs))
        commands = [  # convert any strings -> StringCommand's
            StringCommand(command.strip())
            if isinstance(command, six.string_types) else command
            for command in commands
        ]

        state.in_op = False
        state.current_op_hash = None
        state.current_op_global_kwargs = None

        # Add host-specific operation data to state
        #

        # We're doing some commands, meta/ops++
        state.meta[host]['ops'] += 1
        state.meta[host]['commands'] += len(commands)

        # Add the server-relevant commands
        state.ops[host][op_hash] = {
            'commands': commands,
            'global_kwargs': actual_global_kwargs,
        }

        # Return result meta for use in deploy scripts
        return OperationMeta(op_hash, commands)

    decorated_func._pyinfra_op = func
    return decorated_func
<commit_msg>Properly support user-defined operations outside of modules.<commit_after>'''
Operations are the core of pyinfra. The ``@operation`` wrapper intercepts calls
to the function and instead diff against the remote server, outputting commands
to the deploy state. This is then run later by pyinfra's ``__main__`` or the
:doc:`./pyinfra.api.operations` module.
'''

from __future__ import unicode_literals

from functools import wraps
from types import FunctionType

import six

import pyinfra

from pyinfra import logger, pseudo_host, pseudo_state

from .command import StringCommand
from .exceptions import OperationValueError, PyinfraError
from .host import Host
from .operation_kwargs import get_execution_kwarg_keys, pop_global_op_kwargs
from .state import State
from .util import (
    get_arg_value,
    get_call_location,
    get_operation_order_from_stack,
    make_hash,
    memoize,
    unroll_generators,
)

# List of available operation names
OPERATIONS = []

def get_operation_names():
    '''
    Returns a list of available operations.
    '''

    return OPERATIONS

class OperationMeta(object):
    def __init__(self, hash=None, commands=None):
        # Wrap all the attributes
        commands = commands or []
        self.commands = commands
        self.hash = hash

        # Changed flag = did we do anything?
        self.changed = len(self.commands) > 0

    def __repr__(self):
        '''Return Operation object as a string.'''
        return 'commands:{} changed:{} hash:{}'.format(
            self.commands, self.changed, self.hash)

def add_op(state, op_func, *args, **kwargs):
    '''
    Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.

    Args:
        state (``pyinfra.api.State`` obj): the deploy state to add the operation
        to op_func (function): the operation function from one of the modules,
        ie ``server.user``
        args/kwargs: passed to the operation function
    '''

    allow_cli_mode = kwargs.pop('_allow_cli_mode', False)
    after_host_callback = kwargs.pop('_after_host_callback', lambda host: None)

    if pyinfra.is_cli and not allow_cli_mode:
        raise PyinfraError((
            '`add_op` should not be called when pyinfra is executing in CLI mode! ({0})'
        ).format(get_call_location()))

    # This ensures that every time an operation is added (API mode), it is simply
    # appended to the operation order.
    kwargs['_op_order_number'] = len(state.op_meta)

    kwargs['state'] = state

    hosts = kwargs.pop('host', state.inventory.iter_active_hosts())
    if isinstance(hosts, Host):
        hosts = [hosts]

    results = {}
    for host in hosts:
        kwargs['host'] = host
        results[host] = op_func(*args, **kwargs)
        after_host_callback(host)

    return results

@memoize
def show_set_name_warning(call_location):
    logger.warning((
        '{0}:\n\tUse of a `set` to name operations is deprecated, '
        'please us the `name` keyword argument.'
    ).format(call_location))

@memoize
def show_state_host_arguments_warning(call_location):
    logger.warning((
        '{0}:\n\tPassing `state` and `host` as the first two arguments to operations is '
        'deprecated, please use `state` and `host` keyword arguments.'
    ).format(call_location))

def operation(func=None, pipeline_facts=None):
    '''
    Decorator that takes a simple module function and turn it into the internal
    operation representation that consists of a list of commands + options
    (sudo, (sudo|su)_user, env).
    '''

    # If not decorating, return function with config attached
    if func is None:
        def decorator(f):
            setattr(f, 'pipeline_facts', pipeline_facts)
            return operation(f)

        return decorator

    # Index the operation!
    if func.__module__:
        module_bits = func.__module__.split('.')
        module_name = module_bits[-1]
        op_name = '.'.join((module_name, func.__name__))
        OPERATIONS.append(op_name)

    # Actually decorate!
    @wraps(func)
    def decorated_func(*args, **kwargs):
        # Prepare state/host
        #

        # State & host passed in as kwargs (API, nested op, @deploy op)
        if 'state' in kwargs and 'host' in kwargs:
            state = kwargs['state']
            host = kwargs['host']

        # State & host passed in as first two arguments (LEGACY)
        elif len(args) >= 2 and isinstance(args[0], State) and isinstance(args[1], Host):
            show_state_host_arguments_warning(get_call_location())
            state = kwargs['state'] = args[0]
            host = kwargs['host'] = args[1]
            args_copy = list(args)
            args = args_copy[2:]

        # Finally, still no state+host? Use pseudo if we're CLI mode, or fail
        elif pyinfra.is_cli:
            state = kwargs['state'] = pseudo_state._module
            host = kwargs['host'] = pseudo_host._module

            if state.in_op:
                raise PyinfraError((
                    'Nested operation called without state/host: {0} ({1})'
                ).format(op_name, get_call_location()))

            if state.in_deploy:
                raise PyinfraError((
                    'Nested deploy operation called without state/host: {0} ({1})'
                ).format(op_name, get_call_location()))

        else:
            raise PyinfraError((
                'API operation called without state/host: {0} ({1})'
            ).format(op_name, get_call_location()))

        # Configure operation
        #

        # Get the meta kwargs (globals that apply to all hosts)
        global_kwargs = pop_global_op_kwargs(state, kwargs)

        # If this op is being called inside another, just return here
        # (any unwanted/op-related kwargs removed above).
        if state.in_op:
            return func(*args, **kwargs) or []

        # Name the operation
        name = global_kwargs.get('name')
        add_args = False

        if name:
            names = {name}

        # Look for a set as the first argument
        # TODO: remove this! COMPAT w/<1
        elif len(args) > 0 and isinstance(args[0], set):
            show_set_name_warning(get_call_location())
            names = args[0]
            args_copy = list(args)
            args = args[1:]

        # Generate an operation name if needed (Module/Operation format)
        else:
            add_args = True

            if func.__module__:
                module_bits = func.__module__.split('.')
                module_name = module_bits[-1]
                name = '{0}/{1}'.format(module_name.title(), func.__name__.title())
            else:
                name = func.__name__

            names = {name}

        if state.deploy_name:
            names = {
                '{0} | {1}'.format(state.deploy_name, name)
                for name in names
            }

        op_order = get_operation_order_from_stack(state)

        op_order_number = kwargs.pop('_op_order_number', None)
        if op_order_number is not None:
            op_order = [op_order_number]
        # If we're in API mode, op order number must be provided by calling `add_op`
        elif not pyinfra.is_cli:
            raise PyinfraError((
                'Operation order number not provided in API mode - '
                'you must use `add_op` to add operations.'
            ))

        # Make a hash from the call stack lines
        op_hash = make_hash(op_order)

        # Avoid adding duplicates! This happens if an operation is called within
        # a loop - such that the filename/lineno/code _are_ the same, but the
        # arguments might be different. We just append an increasing number to
        # the op hash and also handle below with the op order.
        host_op_hashes = state.meta[host]['op_hashes']
        duplicate_op_count = 0
        while op_hash in host_op_hashes:
            logger.debug('Duplicate hash ({0}) detected!'.format(op_hash))
            op_hash = '{0}-{1}'.format(op_hash, duplicate_op_count)
            duplicate_op_count += 1

        host_op_hashes.add(op_hash)

        if duplicate_op_count:
            op_order.append(duplicate_op_count)

        op_order = tuple(op_order)

        logger.debug('Adding operation, {0}, opOrder={1}, opHash={2}'.format(
            names, op_order, op_hash,
        ))
        state.op_line_numbers_to_hash[op_order] = op_hash

        # Ensure shared (between servers) operation meta
        op_meta = state.op_meta.setdefault(op_hash, {
            'names': set(),
            'args': [],
        })

        for key in get_execution_kwarg_keys():
            global_value = global_kwargs.pop(key)
            op_meta_value = op_meta.get(key)

            if op_meta_value and global_value != op_meta_value:
                raise OperationValueError('Cannot have different values for `{0}`.'.format(key))

            op_meta[key] = global_value

        # Add any meta kwargs (sudo, etc) to the meta - first parse any strings
        # as jinja templates.
        actual_global_kwargs = {
            key: get_arg_value(state, host, a)
            for key, a in six.iteritems(global_kwargs)
        }

        # Add any new names to the set
        op_meta['names'].update(names)

        # Attach normal args, if we're auto-naming this operation
        if add_args:
            for arg in args:
                if isinstance(arg, FunctionType):
                    arg = arg.__name__

                if arg not in op_meta['args']:
                    op_meta['args'].append(arg)

            # Attach keyword args
            for key, value in six.iteritems(kwargs):
                if isinstance(value, FunctionType):
                    value = value.__name__

                if key in ('state', 'host'):
                    continue

                arg = '='.join((str(key), str(value)))
                if arg not in op_meta['args']:
                    op_meta['args'].append(arg)

        # Check if we're actually running the operation on this host
        #

        # Run once and we've already added meta for this op? Stop here.
        if op_meta['run_once']:
            has_run = False
            for ops in six.itervalues(state.ops):
                if op_hash in ops:
                    has_run = True
                    break

            if has_run:
                return OperationMeta(op_hash)

        # "Run" operation
        #

        # Otherwise, flag as in-op and run it to get the commands
        state.in_op = True
        state.current_op_hash = op_hash
        state.current_op_global_kwargs = actual_global_kwargs

        # Generate actual arguments by parsing strings as jinja2 templates. This
        # means you can string format arguments w/o generating multiple
        # operations. Only affects top level operations, as must be run "in_op"
        # so facts are gathered correctly.
        actual_args = [
            get_arg_value(state, host, a)
            for a in args
        ]

        actual_kwargs = {
            key: get_arg_value(state, host, a)
            for key, a in six.iteritems(kwargs)
        }

        # Convert to list as the result may be a generator
        commands = unroll_generators(func(*actual_args, **actual_kwargs))
        commands = [  # convert any strings -> StringCommand's
            StringCommand(command.strip())
            if isinstance(command, six.string_types) else command
            for command in commands
        ]

        state.in_op = False
        state.current_op_hash = None
        state.current_op_global_kwargs = None

        # Add host-specific operation data to state
        #

        # We're doing some commands, meta/ops++
        state.meta[host]['ops'] += 1
        state.meta[host]['commands'] += len(commands)

        # Add the server-relevant commands
        state.ops[host][op_hash] = {
            'commands': commands,
            'global_kwargs': actual_global_kwargs,
        }

        # Return result meta for use in deploy scripts
        return OperationMeta(op_hash, commands)

    decorated_func._pyinfra_op = func
    return decorated_func
<|endoftext|>


<commit_before>#!/usr/bin/python
# @Author: Eddie Ruano
# @Date:   2017-05-01 05:14:54
# @Last Modified by:   Eddie Ruano
# @Last Modified time: 2017-06-04 03:27:48
#
"""
    MissionControl.py is a debugging tool for DESI_Sentinel
"""
### IMPORT MODULES ###
import sys
import os.path
import signal
import collections
import pyaudio
import wave
import time
from math import floor
# Customs Mods #
import Adafruit_MPR121.MPR121 as MPR121
import RPi.GPIO as GPIO
# Local Modules #
### Set path ###
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import drivers.VoyagerHCSR04 as VoyagerHCSR04
import drivers.DESIConfig as DESIConfig
TOP_DIR = os.path.dirname(os.path.abspath(__file__))
DING = os.path.join(TOP_DIR, "resources/ding.wav")
### Global Variables ###
DESI = DESIConfig.DESI()
Voyager1 = VoyagerHCSR04.Voyager("Voyager1", DESI.PROX1_TRIG, DESI.PROX1_ECHO)
Voyager2 = VoyagerHCSR04.Voyager("Voyager2", DESI.PROX2_TRIG, DESI.PROX2_ECHO)
TouchSense = MPR121.MPR121()
CONST_REDUX = 0.1
CONST_ZONE_FIX = 0.0
Proximity = 0
FlagDisparity = False

def main():
    global FlagDisparity
    # Variables
    proxError = 0.0
    distv1 = 0.0
    distv2 = 0.0
    slack = 0.0
    contact = False
    ave = 0.0
    dFlag = True
    tStart = False
    tPause = False
    tS0 = False
    tS1 = False
    tS2 = False
    tS3 = False
    lastZone = -1.0
    subZone = 0.0
    redFlag = False
    saveSpeed = DESI.State_Speed
    # Initialize DESI States
    DESI.initDESI()
    # Initialize Voyager Proximity Sensors
    DESI.initProximity(Voyager1, Voyager2)
    if not TouchSense.begin():  # Init TouchSense Capacitive Sensor Array
        print("TSense")
        sys.exit(1)
    GPIO.add_event_detect(DESI.IN_START, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_PAUSE, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED0, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED1, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED2, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED3, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED4, GPIO.FALLING)
    try:
        print("Listening")
        #DESI.DESIListen()
        activeFlag = True
        while activeFlag == True:
            i = 0
            if(GPIO.event_detected(DESI.IN_START)):
                print("start")
                DESI.DESISend("Start")
            elif(GPIO.event_detected(DESI.IN_PAUSE)):
                print("pause")
                DESI.DESISend("Pause")
            elif(GPIO.event_detected(DESI.IN_SPEED0)):
                print("0")
                DESI.DESISend("Send00")
            elif(GPIO.event_detected(DESI.IN_SPEED1)):
                print("1")
                DESI.DESISend("Send01")
            elif(GPIO.event_detected(DESI.IN_SPEED2)):
                print("2")
                DESI.DESISend("Send02")
            elif(GPIO.event_detected(DESI.IN_SPEED3)):
                print("3")
                DESI.DESISend("Send03")
            elif(GPIO.event_detected(DESI.IN_SPEED4)):
                print("4")
                DESI.DESISend("Send04")
            else:
                pass

            Proximity = queryDistance()
            if FlagDisparity:
                self.FlagDisparity = False;
            print(Proximity)
            subZone = floor(Proximity - DESI.Zone_Yellow) + 1.0
            if Proximity == -1.0:
                print ("Error")
            # elif(Proximity > DESI.Zone_Yellow and subZone != lastZone):
            #     subRedux = DESI.State_Speed * CONST_REDUX * 10
            #     redux = subZone * subRedux
            #     print(subRedux)
            #     print(subZone)
            #     print(redux)
            #     while i < redux:
            #         DESI.DESISend("SendDown")
            #         i+=1
            #     lastZone = subZone
            #     print("refresh")
            elif Proximity > DESI.Zone_Red and not redFlag:
                saveSpeed = DESI.State_Speed
                DESI.DESISend("Send00")
                print(ave)
                redFlag = True
            elif Proximity < DESI.Zone_Red and redFlag:
                DESI.DESISend("Send01")
                redFlag = False
            else:
                pass
            time.sleep(0.05)
            # Query for the proximity of Megan #
            #time.sleep(0.3)

            #distAverage = (distv1 + distv2) / 2
            #proxError = distv1 - distv2
            #contact = checkContact()
            #state = checkState(distAverage)
            #if state == "Red":
            #    print("Red!")
            #    past_state = state
            #    DESI.send("Pause")
            #    time.sleep(5)
            #    DESI.send(past_state)
            #elif state == "Yellow":
            #    DESI.send("Down")
            #    time.sleep(0.4)
            #    DESI.send("Down")
            #    time.sleep(0.4)
            #    DESI.send("Down")
            #else:
            #    print("Green!")
            #    slack = 30 - distAverage
            #    redux = ((distAverage - 10) / 2) * 10
            #    redux = int(redux)
    #           time.sleep(1)
    # Catch Ctrl+C
    except KeyboardInterrupt:
        GPIO.cleanup()
        print("Shutdown Mission.")
        #Detector.terminate()

### END OF MAIN ###
"""Helper Functions"""
def activateAlexa():
    GPIO.output(DESI.OUT_ALEXA, GPIO.LOW)
    time.sleep(2)
    GPIO.output(DESI.OUT_ALEXA, GPIO.HIGH)
def play_audio_file(fname=DING):
    """Plays audio
    :param str fname: wave file name
    :return: None
    """
    ding_wav = wave.open(fname, 'rb')
    ding_data = ding_wav.readframes(ding_wav.getnframes())
    audio = pyaudio.PyAudio()
    stream_out = audio.open(
        format=audio.get_format_from_width(ding_wav.getsampwidth()),
        channels=ding_wav.getnchannels(),
        rate=ding_wav.getframerate(), input=False, output=True)
    stream_out.start_stream()
    stream_out.write(ding_data)
    time.sleep(0.2)
    stream_out.stop_stream()
    stream_out.close()
    audio.terminate()
def queryDistance():
    global FlagDisparity
    error = False
    distv1 = Voyager1.get_distance()
    distv2 = Voyager2.get_distance()
    # Sanitize
    distv1 = distv1 - 3.5
    distv2 = distv2 - 3.5
    if distv1 < 0 or distv1 > 15:
        distv1 = distv2
        error = True
    if distv2 < 0 or distv2 > 15 and not error:
        distv2 = distv1
    if error:
        ave = -1.0
    #print(distv1)
    #print(distv2)
    ave = floor((distv1 + distv2) / 2)
    if (abs(ave - Proximity) > 4) and not FlagDisparity:
        ave = Proximity
        FlagDisparity = True
    else:
        FlagDisparity == False
    #    return Distance
    return ave
#def signal_handler(signal, frame):
#    global HotwordInterrupt
#    HotwordInterrupt = True
#def interrupt_callback():
#    global HotwordInterrupt
#    return HotwordInterrupt
### MAIN CALL ###
if __name__ == "__main__":
    main()<commit_msg>Script<commit_after>#!/usr/bin/python
# @Author: Eddie Ruano
# @Date:   2017-05-01 05:14:54
# @Last Modified by:   Eddie Ruano
# @Last Modified time: 2017-06-04 03:28:02
#
"""
    MissionControl.py is a debugging tool for DESI_Sentinel
"""
### IMPORT MODULES ###
import sys
import os.path
import signal
import collections
import pyaudio
import wave
import time
from math import floor
# Customs Mods #
import Adafruit_MPR121.MPR121 as MPR121
import RPi.GPIO as GPIO
# Local Modules #
### Set path ###
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import drivers.VoyagerHCSR04 as VoyagerHCSR04
import drivers.DESIConfig as DESIConfig
TOP_DIR = os.path.dirname(os.path.abspath(__file__))
DING = os.path.join(TOP_DIR, "resources/ding.wav")
### Global Variables ###
DESI = DESIConfig.DESI()
Voyager1 = VoyagerHCSR04.Voyager("Voyager1", DESI.PROX1_TRIG, DESI.PROX1_ECHO)
Voyager2 = VoyagerHCSR04.Voyager("Voyager2", DESI.PROX2_TRIG, DESI.PROX2_ECHO)
TouchSense = MPR121.MPR121()
CONST_REDUX = 0.1
CONST_ZONE_FIX = 0.0
Proximity = 0
FlagDisparity = False

def main():
    global FlagDisparity
    # Variables
    proxError = 0.0
    distv1 = 0.0
    distv2 = 0.0
    slack = 0.0
    contact = False
    ave = 0.0
    dFlag = True
    tStart = False
    tPause = False
    tS0 = False
    tS1 = False
    tS2 = False
    tS3 = False
    lastZone = -1.0
    subZone = 0.0
    redFlag = False
    saveSpeed = DESI.State_Speed
    # Initialize DESI States
    DESI.initDESI()
    # Initialize Voyager Proximity Sensors
    DESI.initProximity(Voyager1, Voyager2)
    if not TouchSense.begin():  # Init TouchSense Capacitive Sensor Array
        print("TSense")
        sys.exit(1)
    GPIO.add_event_detect(DESI.IN_START, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_PAUSE, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED0, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED1, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED2, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED3, GPIO.FALLING)
    GPIO.add_event_detect(DESI.IN_SPEED4, GPIO.FALLING)
    try:
        print("Listening")
        #DESI.DESIListen()
        activeFlag = True
        while activeFlag == True:
            i = 0
            if(GPIO.event_detected(DESI.IN_START)):
                print("start")
                DESI.DESISend("Start")
            elif(GPIO.event_detected(DESI.IN_PAUSE)):
                print("pause")
                DESI.DESISend("Pause")
            elif(GPIO.event_detected(DESI.IN_SPEED0)):
                print("0")
                DESI.DESISend("Send00")
            elif(GPIO.event_detected(DESI.IN_SPEED1)):
                print("1")
                DESI.DESISend("Send01")
            elif(GPIO.event_detected(DESI.IN_SPEED2)):
                print("2")
                DESI.DESISend("Send02")
            elif(GPIO.event_detected(DESI.IN_SPEED3)):
                print("3")
                DESI.DESISend("Send03")
            elif(GPIO.event_detected(DESI.IN_SPEED4)):
                print("4")
                DESI.DESISend("Send04")
            else:
                pass

            Proximity = queryDistance()
            if FlagDisparity:
                FlagDisparity = False;
            print(Proximity)
            subZone = floor(Proximity - DESI.Zone_Yellow) + 1.0
            if Proximity == -1.0:
                print ("Error")
            # elif(Proximity > DESI.Zone_Yellow and subZone != lastZone):
            #     subRedux = DESI.State_Speed * CONST_REDUX * 10
            #     redux = subZone * subRedux
            #     print(subRedux)
            #     print(subZone)
            #     print(redux)
            #     while i < redux:
            #         DESI.DESISend("SendDown")
            #         i+=1
            #     lastZone = subZone
            #     print("refresh")
            elif Proximity > DESI.Zone_Red and not redFlag:
                saveSpeed = DESI.State_Speed
                DESI.DESISend("Send00")
                print(ave)
                redFlag = True
            elif Proximity < DESI.Zone_Red and redFlag:
                DESI.DESISend("Send01")
                redFlag = False
            else:
                pass
            time.sleep(0.05)
            # Query for the proximity of Megan #
            #time.sleep(0.3)

            #distAverage = (distv1 + distv2) / 2
            #proxError = distv1 - distv2
            #contact = checkContact()
            #state = checkState(distAverage)
            #if state == "Red":
            #    print("Red!")
            #    past_state = state
            #    DESI.send("Pause")
            #    time.sleep(5)
            #    DESI.send(past_state)
            #elif state == "Yellow":
            #    DESI.send("Down")
            #    time.sleep(0.4)
            #    DESI.send("Down")
            #    time.sleep(0.4)
            #    DESI.send("Down")
            #else:
            #    print("Green!")
            #    slack = 30 - distAverage
            #    redux = ((distAverage - 10) / 2) * 10
            #    redux = int(redux)
    #           time.sleep(1)
    # Catch Ctrl+C
    except KeyboardInterrupt:
        GPIO.cleanup()
        print("Shutdown Mission.")
        #Detector.terminate()

### END OF MAIN ###
"""Helper Functions"""
def activateAlexa():
    GPIO.output(DESI.OUT_ALEXA, GPIO.LOW)
    time.sleep(2)
    GPIO.output(DESI.OUT_ALEXA, GPIO.HIGH)
def play_audio_file(fname=DING):
    """Plays audio
    :param str fname: wave file name
    :return: None
    """
    ding_wav = wave.open(fname, 'rb')
    ding_data = ding_wav.readframes(ding_wav.getnframes())
    audio = pyaudio.PyAudio()
    stream_out = audio.open(
        format=audio.get_format_from_width(ding_wav.getsampwidth()),
        channels=ding_wav.getnchannels(),
        rate=ding_wav.getframerate(), input=False, output=True)
    stream_out.start_stream()
    stream_out.write(ding_data)
    time.sleep(0.2)
    stream_out.stop_stream()
    stream_out.close()
    audio.terminate()
def queryDistance():
    global FlagDisparity
    error = False
    distv1 = Voyager1.get_distance()
    distv2 = Voyager2.get_distance()
    # Sanitize
    distv1 = distv1 - 3.5
    distv2 = distv2 - 3.5
    if distv1 < 0 or distv1 > 15:
        distv1 = distv2
        error = True
    if distv2 < 0 or distv2 > 15 and not error:
        distv2 = distv1
    if error:
        ave = -1.0
    #print(distv1)
    #print(distv2)
    ave = floor((distv1 + distv2) / 2)
    if (abs(ave - Proximity) > 4) and not FlagDisparity:
        ave = Proximity
        FlagDisparity = True
    else:
        FlagDisparity == False
    #    return Distance
    return ave
#def signal_handler(signal, frame):
#    global HotwordInterrupt
#    HotwordInterrupt = True
#def interrupt_callback():
#    global HotwordInterrupt
#    return HotwordInterrupt
### MAIN CALL ###
if __name__ == "__main__":
    main()<|endoftext|>


<commit_before>"""
A filter which can perform many types of text-to-HTML conversion.

"""

from django.template import Library
from template_utils.markup import markup_filter

def apply_markup(value):
    """
    Applies text-to-HTML conversion.

    """
    return markup_filter(value)

register = Library()
register.filter(apply_markup)
<commit_msg>Make markup template filter take filter_name argument<commit_after>"""
A filter which can perform many types of text-to-HTML conversion.

"""

from django.template import Library
from template_utils.markup import markup_filter

def apply_markup(value, arg=None):
    """
    Applies text-to-HTML conversion.

    Takes an optional argument to specify the name of a filter to use.

    """
    if arg is not None:
        return markup_filter(value, filter_name=arg)
    return markup_filter(value)

register = Library()
register.filter(apply_markup)
<|endoftext|>