Esempio n. 1
0
def main():
    dynamodb = aws.getResource('dynamodb','us-east-1')
    snsClient = aws.getClient('sns','us-east-1')
    snsResource = aws.getResource('sns','us-east-1')
    
    dynamoTable = dynamodb.Table(DYNAMODB_TABLE_NAME)

    # Get list of all stopIds
    stations = buildStationssDB()


    while True:
        prompt()
        sys.stdout.write(">select a command : ")
        userIn = sys.stdin.readline().strip()
        if len(userIn) < 1 :
            print "Command not recognized"
        else:
            if userIn == '1':
                sys.stdout.write(">Enter source : ")
                sourceStop = sys.stdin.readline().strip()
                if sourceStop not in stations:
                    sys.stdout.write(">Invalid stop id. Enter a valid stop id")
                    sys.stdout.flush()
                    continue

                sys.stdout.write(">Enter destination : ")
                destinationStop = sys.stdin.readline().strip()
                if destinationStop not in stations:
                    sys.stdout.write(">Invalid stop id. Enter a valid stop id")
                    sys.stdout.flush()
                    continue

                sys.stdout.write(">Type N for uptown, S for downtown: ")
                direction = sys.stdin.readline().strip()

                # Validate direction
                if direction not in ['N','S']:
                    sys.stdout.write(">Invalid direction. Enter a valid direction")
                    sys.stdout.flush()
                    continue
                ###############################
                # YOUR CODE HERE #
                ###############################

            elif userIn == '2':
                sys.stdout.write(">Enter phonenumber")
                phoneNumber = sys.stdin.readline().strip()
                ###############################
                # YOUR CODE HERE #
                ###############################

            else:
                sys.exit()
Esempio n. 2
0
def main(fileName):
    # API key
    with open('../../config.txt', 'rb') as keyfile:
        APIKEY = keyfile.read().rstrip('\n')
        keyfile.close()

	### INSERT YOUR CODE HERE ###
	Dynamodb_table_name = "mataData"
	dynamodb = aws.getResource('dynamodb', 'us-east-1')
	table = dynamodb.Table('mtaData')
	f = open(fileName, 'a')
	f_csv = csv.writer(f)
	# f_csv.writerow(columns)	
	for i in range(ITERATIONS):
		data = mtaUpdates.mtaUpdates("")
	

		tripUpdate, alerts, vehicle, timestamp = data.getTripUpdates()
	
		#headers = ['Timestamp', 'tripId', 'Route', 'Day of the week', 'Time at which it reaches express station', 'Time at which it reaches the destination']
		#f = open(fileName, 'a')
		#f_csv = csv.writer(f)
		row = matchdata(columns, tripUpdate, alerts, vehicle, timestamp)
		#print row
		f_csv.writerows(row)
		#f.close()	
		print "file write success iter:", i
	f.close()
    def getTable(self, table_name):
        dynamodb = aws.getResource('dynamodb', 'us-east-1')
        try:
            # Create the DynamoDB table.
            table = dynamodb.create_table(TableName=self.table_name,
                                          KeySchema=[{
                                              'AttributeName': 'timeStamp',
                                              'KeyType': 'HASH'
                                          }, {
                                              'AttributeName': 'roomID',
                                              'KeyType': 'RANGE'
                                          }],
                                          AttributeDefinitions=[
                                              {
                                                  'AttributeName': 'timeStamp',
                                                  'AttributeType': 'S'
                                              },
                                              {
                                                  'AttributeName': 'roomID',
                                                  'AttributeType': 'S'
                                              },
                                          ],
                                          ProvisionedThroughput={
                                              'ReadCapacityUnits': 5,
                                              'WriteCapacityUnits': 5
                                          })

        except:
            table = dynamodb.Table(table_name)
            print("Table already exists.")

        return table
def initial_table():
	client_dynamo = aws.getResource('dynamodb','us-east-1')
	try:
		this_table = client_dynamo.create_table(
			TableName = table_name,
			KeySchema=[
				{
					'AttributeName': 'tripId',
					'KeyType': 'HASH'
				}
			],
			AttributeDefinitions=[
				{	'AttributeName': 'tripId',
					'AttributeType': 'S'
				}
			],
			ProvisionedThroughput={
				'ReadCapacityUnits': 5,
				'WriteCapacityUnits': 5
			}
		)
		print "table created"
	except:
		this_table = client_dynamo.Table(table_name)
		print 'using existing table'
	return this_table
Esempio n. 5
0
def initial_table():
    client_dynamo = aws.getResource('dynamodb', 'us-east-1')
    if ifCreateTable == 1:
        print 'creating table'
        this_table = client_dynamo.create_table(TableName=table_name,
                                                KeySchema=[{
                                                    'AttributeName': 'tripId',
                                                    'KeyType': 'HASH'
                                                }, {
                                                    'AttributeName':
                                                    'timestamp',
                                                    'KeyType': 'RANGE'
                                                }],
                                                AttributeDefinitions=[{
                                                    'AttributeName':
                                                    'tripId',
                                                    'AttributeType':
                                                    'S'
                                                }, {
                                                    'AttributeName':
                                                    'timestamp',
                                                    'AttributeType':
                                                    'N'
                                                }],
                                                ProvisionedThroughput={
                                                    'ReadCapacityUnits': 5,
                                                    'WriteCapacityUnits': 5
                                                })
    else:
        print 'using existing table'
        this_table = client_dynamo.Table(table_name)
    return this_table
Esempio n. 6
0
def table_scan():
    client_dynamo = aws.getResource('dynamodb', 'us-east-1')
    global this_table
    this_table = client_dynamo.Table(table_name)
    response1 = this_table.scan(
        FilterExpression=Attr('currentStopId').not_exists())
    return response1
Esempio n. 7
0
def db_operation(userid, item, amount):
    dynamodb = aws.getResource('dynamodb', 'us-east-1')
    DYNAMO_TABLE_NAME = "shopping_cart"
    table_dynamo = dynamodb.Table(DYNAMO_TABLE_NAME)
    response = table_dynamo.scan()
    current_record = None
    for record in response['Items']:
        if (record["user_id"] == userid) and (record["item"]
                                              == item) and (record["payment"]
                                                            == "unpaid"):
            current_record = record
    if (current_record == None) and (amount > 0):
        response = table_dynamo.put_item(
            Item={
                'timestamp': str(time.time()),
                'user_id': userid,
                'amount': amount,
                'price': price_dict[item],
                'item': item,
                'payment': "unpaid"
            })
        return
    elif (current_record != None) and (amount < 0):
        table_dynamo.delete_item(
            Key={'timestamp': current_record["timestamp"]})
    elif (current_record != None) and (amount > 0):
        response = table_dynamo.update_item(
            Key={'timestamp': current_record["timestamp"]},
            UpdateExpression="set amount = :a",
            ExpressionAttributeValues={
                ':a': str(float(current_record["amount"]) + float(amount))
            },
            ReturnValues="UPDATED_NEW")
def main():
    with open('../../key.txt', 'rb') as keyfile:
        APIKEY = keyfile.read().rstrip('\n')
        keyfile.close()



    dynamodb = aws.getResource('dynamodb','us-east-1')
    dynamoTable = dynamodb.Table(DYNAMODB_TABLE_NAME)

     # Thread 1 check update dynamo db
    updateDbThread = Thread(target = updateDb, name = 'updateDb',args=(APIKEY,dynamoTable))

    # Thread 2 send clean up old dynamodb entries
    cleanUpDbThread = Thread(target = cleanUpDb, name = 'cleanUpDb',args=(dynamoTable,))

    updateDbThread.daemon = True
    cleanUpDbThread.daemon = True

    # Start all the threads
    updateDbThread.start()

    # Start clean up after 2 minutes
    # if you start clean up db thread right away, you get an error since 
    # udpate db thread hasnt finished writing to dynamodb
    # use only when you start with empty table
    #time.sleep(120)
    cleanUpDbThread.start()


    # Join threads
    updateDbThread.join()    
    cleanUpDbThread.join()
def table_scan():
	client_dynamo = aws.getResource('dynamodb','us-east-1')
	global this_table
	this_table = client_dynamo.Table(table_name)
	response1 = this_table.scan(
		FilterExpression = Attr('currentStopId').not_exists()
		)
	return response1
Esempio n. 10
0
  def run(self):
    global open_fan_edison
    global ml_flag
    app_serverPORT=5555
      while True:
        try:
          app_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          app_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
          app_soc.bind(('0.0.0.0',app_serverPORT))
          app_soc.listen(5)
          app_conn,app_addr = app_soc.accept()
          print 'New app connection'
          while True:
            try:
              app_conn.send("Ready"+'\r\n')
              app_conn.settimeout(2.0)
              app_msg1 = app_conn.recv(1024)
              app_conn.settimeout(None)
              if(app_msg1.find('OK') == -1):


              app_conn.close()
              break
            except socket.timeout:
              app_conn.close()
              break                                         
          if (int(ml_flag) ==1):
            snsResource = aws.getResource('sns', 'us-east-1')
            snsClient = aws.getClient('sns', 'us-east-1')
            subject_content = 'Alert! '
            message_content = subject_content
            topic = snsResource.Topic('**********')
            snsClient.publish(TopicArn='**********', Message=message_content, Subject=subject_content)


          alert_msg="Dangerous! Temperature Now is:"+str(temp_now)
          print ("Alert!!",alert_msg)
          app_conn.send(alert_msg+'\r\n')
          print "msg has been sent"
          app_msg2 = app_conn.recv(1024)
          appThread = threading.Lock()
          if appThread.acquire():
                  ml_flag = 0 #tempory 0 for one minute
                  appThread.release()
                  #If it can run to this sentence, it means that app has sent a msg, 
                  #Change here to open fan
          if (app_msg2.find('OPEN') == -1):
                  app_conn.close()
                  break
          open_fan_edison =1
          print ("change in ML in FAN FLAG", open_fan_edison)
          print ("Got connection from",app_addr)
          print (app_msg2)
        except:
          app_soc.close()
          app_conn.close()
          continue
    def __init__(self):
        dynamo = aws.getResource('dynamodb')

        # First try and create the table
        try:
            table = dynamo.create_table(
                TableName=DYNAMO_TABLE_NAME,
                KeySchema=[
                    {
                        'AttributeName': 'userName',
                        'KeyType': 'HASH'  # Partition Key
                    },
                    {
                        'AttributeName' : 'time',
                        'KeyType' : 'RANGE'
                    }
                ],
                AttributeDefinitions=[
                    {
                        'AttributeName': 'userName',
                        'AttributeType': 'S'
                    },
                    {
                        'AttributeName': 'time',
                        'AttributeType': 'S'
                    }
                ],
                ProvisionedThroughput={
                    'ReadCapacityUnits': 10,
                    'WriteCapacityUnits': 10
                }
            )
            while table.table_status != 'ACTIVE':
                table.reload()
            print ('Table ' + DYNAMO_TABLE_NAME + ' has been created.')
        except Exception as e:
            # print e
            table = dynamo.Table(DYNAMO_TABLE_NAME)
            print ('Table ' + DYNAMO_TABLE_NAME + ' has been retrieved.')
        self.table_dynamo = table
def initial_table():
    client_dynamo = aws.getResource('dynamodb', 'us-east-1')
    try:
        this_table = client_dynamo.create_table(TableName=table_name,
                                                KeySchema=[{
                                                    'AttributeName': 'tripId',
                                                    'KeyType': 'HASH'
                                                }],
                                                AttributeDefinitions=[{
                                                    'AttributeName':
                                                    'tripId',
                                                    'AttributeType':
                                                    'S'
                                                }],
                                                ProvisionedThroughput={
                                                    'ReadCapacityUnits': 5,
                                                    'WriteCapacityUnits': 5
                                                })
        print "table created"
    except:
        this_table = client_dynamo.Table(table_name)
        print 'using existing table'
    return this_table
Esempio n. 13
0
from datetime import datetime, timedelta
import boto3
from boto3.dynamodb.conditions import Key, Attr
import threading

sys.path.append('../utils')
import tripupdate, vehicle, alert, mtaUpdates, aws

with open('../key.txt', 'rb') as keyfile:
    APIKEY = keyfile.read().rstrip('\n')
    keyfile.close()

mtaUpdate = mtaUpdates.mtaUpdates(APIKEY)
tripUpdates = mtaUpdate.getTripUpdates()

dynamodb = aws.getResource('dynamodb', 'us-east-1')
table = dynamodb.Table('mtaData')

global e_flag
e_flag = False


def addData(data):
    while (1):
        print 'thread2'
        print e_flag
        if e_flag:
            print "addData return"
            return
        time.sleep(1)
Esempio n. 14
0
import sys


from collections import OrderedDict
from threading import Thread
import urllib3
urllib3.disable_warnings(urllib3.exceptions.SNIMissingWarning)
import boto3
import aws
from boto3.dynamodb.conditions import Key,Attr
from time import sleep
import datetime
DYNAMO_TABLE_NAME1 = 'project'
DYNAMO_TABLE_NAME2 = "temperature"
REALTIME_TABLE = "realtime"
dynamodb = aws.getResource('dynamodb', '*****')
APIKEY = '***********'

table_dynamo1 = dynamodb.Table(DYNAMO_TABLE_NAME1)
table_dynamo2 = dynamodb.Table(DYNAMO_TABLE_NAME2)
real_table = dynamodb.Table(REALTIME_TABLE)


app = Flask(__name__)

_default_directory = os.path.abspath('static/')

def transfer_to_json():
    now = datetime.datetime.now()
    d = datetime.datetime.strptime(str(now), "%Y-%m-%d %H:%M:%S.%f")
    now_ts = int(time.mktime(d.timetuple()))
Esempio n. 15
0
	def __init__(self,trainingData):
		# Get s3 resource , function for this is in utils/aws
		self.S3 = aws.getResource('s3','us-east-1')
		self.trainingData = trainingData
Esempio n. 16
0
	def __init__(self, threadName, trainingData = FILENAME):
		threading.Thread.__init__(self)
		self.S3 = aws.getResource('s3','us-east-1')
		self.trainingData = trainingData
		self.threadName = threadName
Esempio n. 17
0
from picamera import PiCamera
import time
import sys
import threading
#-------dynamodb------
import boto3
# from boto3.dynamodb.conditions import Key,Attr

import aws
from datetime import datetime
import calendar
from PIL import Image
# postgresql

# dynamoDB
dynamodb = aws.getResource('dynamodb', "us-east-1")

# S3
s3 = aws.getResource('s3', 'us-east-1')
# s3 = aws.getClient('s3', 'us-east-1')

# sns
snsClient = aws.getClient("sns","us-east-1")
# topic_arn = "arn:aws:sns:us-east-1:810588570945:fruit-alert"

import sys
MACHINE = sys.argv[1]
print('machine{}'.format(MACHINE))


def create_topic():
 def refresh(self):
     global dynamodb
     dynamodb = aws.getResource('dynamodb', 'us-east-1')
     self.table = dynamodb.Table('mtadata')
Esempio n. 19
0
 def __init__(self):
     # Get s3 resource , function for this is in utils/aws
     self.S3 = aws.getResource('s3', 'us-east-1')
def main():
    dynamodb = aws.getResource('dynamodb','us-east-1')
    snsClient = aws.getClient('sns','us-east-1')
    snsResource = aws.getResource('sns','us-east-1')
    
    dynamoTable = dynamodb.Table(DYNAMODB_TABLE_NAME)

    # Get list of all stopIds
    stations = buildStationssDB()


    while True:
        prompt()
        sys.stdout.write(">select a command : ")
        userIn = sys.stdin.readline().strip()
        if len(userIn) < 1 :
            print "Command not recognized"
        else:
            if userIn == '1':
                sys.stdout.write(">Enter source : ")
                sourceStop = sys.stdin.readline().strip()
                if sourceStop not in stations:
                    sys.stdout.write(">Invalid stop id. Enter a valid stop id")
                    sys.stdout.flush()
                    continue

                sys.stdout.write(">Enter destination : ")
                destinationStop = sys.stdin.readline().strip()
                if destinationStop not in stations:
                    sys.stdout.write(">Invalid stop id. Enter a valid stop id")
                    sys.stdout.flush()
                    continue

                sys.stdout.write(">Type N for uptown, S for downtown: ")
                direction = sys.stdin.readline().strip()

                # Validate direction
                if direction not in ['N','S']:
                    sys.stdout.write(">Invalid direction. Enter a valid direction")
                    sys.stdout.flush()
                    continue

                response = getLocalTrains(dynamoTable,direction,'1',int(sourceStop[:-1]))

                earliestTrainData = getEarliestTrain(response,sourceStop)

                print "local train is ",earliestTrainData['tripId']
                timeToReachExpressStation = getTimeToReachDestination(earliestTrainData,'120S')


                # get list of 2 and 3 trains 

                # List of trains with route id 2 and are either at 96th or before it
                # Note that 2 train's stop starts from 201S and goes till 227S and merges with 96th street(120S)
                # range2 is a list of all stations on 2 train route before and including 96th
                range2 = range(201,228)
                range2.append(120)

                expressTrains2 = getExpress(dynamoTable,direction,'2',range2)

                # List of trains with route id 3 and are either at 96th or before it
                # Note that 3 train's stop starts from 301S and goes till 302S and merges with 2 train lane at 135th street lenox 224S 
                # range3 is a list of all stations on 3 train route before and including 96th
                range3 = range(224,228)
                range3.extend([301,302,120])
                expressTrains3 = getExpress(dynamoTable,direction,'3',range3)

                expressTrains = expressTrains2 + expressTrains3

                # filter the trains that reach 96th before the earliest one reaches.
                for e in expressTrains:
                    stops = json.loads(e['futureStopData'])
                    if stops['120S'][0]['arrivalTime'] - timeToReachExpressStation < 10:
                        expressTrains.remove(e)

                timeTakenByLocal    = getTimeToReachDestination(earliestTrainData,destinationStop)

                print "time taken by local to 96",timeToReachExpressStation
                # If there is an express train find the time at which it reaches time square
                if expressTrains:
                    expressTrainData = getEarliestTrain(expressTrains,'120S')
                    print expressTrainData['tripId']

                    print "time taken by express to 96",getTimeToReachDestination(expressTrainData,'120S')


                    timeTakenByExpress  = getTimeToReachDestination(expressTrainData,destinationStop)
                    timeTakenByLocal    = getTimeToReachDestination(earliestTrainData,destinationStop)
                    print "time taken by local to 42nd",timeTakenByLocal
                    print "Time taken by expres to 42nd",timeTakenByExpress

                    if timeTakenByLocal > timeTakenByExpress:
                        print ">Switch to express"
                    else:
                        print ">Do not switch to express"
                else:
                    print "No express at this time"
                    print ">Do not switch to express"

            elif userIn == '2':
                sys.stdout.write(">Enter phonenumber")
                phoneNumber = sys.stdin.readline().strip()
                phoneNumber = '1'+phoneNumber                

                topic = snsResource.Topic('arn:aws:sns:us-east-1:013162866752:mtaSub')
                topic.subscribe(Protocol='sms', 
                                 Endpoint=phoneNumber)

                snsClient.publish(TopicArn='arn:aws:sns:us-east-1:013162866752:mtaSub', 
                                          Message='You have subscribed to mta data',
                                          Subject='MTAFEED')


            else:
                sys.exit()
Esempio n. 21
0
    def getTripUpdates(self):
        ## Using the gtfs_realtime_pb2 file created by the
        ## proto compiler, we view the feed using the method below.
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(
                    self.FEED_URL)) as response:
                d = feed.ParseFromString(response.read())
        except (urllib2.URLError, google.protobuf.message.DecodeError) as e:
            print "Error while connecting to mta server " + str(e)

        ########################################################################
        ####### Run code above this point to validate your connection ##########
        ########################################################################

        ## The MTA feed gives entities which give information regarding,
        ## vehicle status, trip_update information & alerts

        self.timestamp = feed.header.timestamp
        self.nytime = datetime.fromtimestamp(self.timestamp, self.TIMEZONE)

        try:
            # Get the dynamoDB service resource
            #dynamodb = aws.getResource('dynamodb', 'us-east-1')
            #table = dynamodb.Table("mtaData")
            #with table.batch_writer() as batch:
            for entity in feed.entity:
                try:
                    if entity.HasField('vehicle'):

                        # timeStamp: Feed timestamp [EDIT: This timestamp can be
                        #  obtained from the mta feed's header message]
                        self.D['ts'] = feed.header.timestamp

                        e = entity

                        # tripId: The unique trip identifier
                        self.D['tripId'] = e.vehicle.trip.trip_id

                        # currentStopId: Applicable to vehicle messages, stop ID info.
                        self.D['currentStopId'] = e.vehicle.stop_id

                        # currentStopStatus:
                        #  {1:"INCOMING_AT", 2:"STOPPED_AT", 3:"IN_TRANSIT_TO"},
                        #  refer manual for more details.
                        self.D['currentStopStatus'] = e.vehicle.current_status

                        # vehicleTimeStamp: The time stamp obtained from the vehicle
                        self.D['vehicleTimeStamp'] = e.vehicle.timestamp

                        # Post dict
                        try:
                            dynamodb = aws.getResource('dynamodb', 'us-east-1')
                            table = dynamodb.Table("mtaData")
                            table.update_item(
                                Key={'tripId': self.D['tripId']},
                                UpdateExpression=
                                "set ts = :a,currentStopId=:b,currentStopStatus=:c,vehicleTimeStamp=:d",
                                ExpressionAttributeValues={
                                    ':a': self.D['ts'],
                                    ':b': self.D['currentStopId'],
                                    ':c': self.D['currentStopStatus'],
                                    ':d': self.D['vehicleTimeStamp']
                                })
                        except KeyboardInterrupt:
                            exit
                        except:
                            print "Update Error 1"

                    if entity.HasField('trip_update'):

                        # timeStamp: Feed timestamp [EDIT: This timestamp can be
                        #  obtained from the mta feed's header message]
                        self.D['ts'] = feed.header.timestamp

                        e = entity

                        # tripId: The unique trip identifier
                        self.D['tripId'] = e.trip_update.trip.trip_id

                        # routeId: Train Route, eg, 1, 2, 3 etc. or "S" for the Grand
                        #  Shuttle Service between Times Square & Grand Central
                        self.D['routeId'] = e.trip_update.trip.route_id

                        # startDate: Journey Start Date
                        self.D['startDate'] = e.trip_update.trip.start_date

                        # direction: "N" or "S" depending on whether the journey is
                        #  uptown or downtown, respectively. (on the Grand Central
                        #  Shuttle, N: Times Square to Grand Central, S: reverse trip)
                        self.D['direction'] = e.trip_update.trip.trip_id[10:11]

                        # Message feed, regarding the message itself.
                        # futureStopData: Information from the trip_update message.
                        #  Should contain:
                        #  {<stop_id>: ["arrivaltime": <arrival_at_stop>, "departuretime": <departure_from_stop>]}
                        #  for eg.
                        #  {"247N": [{"arrivalTime":1454802090}, {"departureTime": 1454802090}], "246N": [{"arrivalTime": 1454802210}, {"departureTime": 1454802210}]}
                        self.D['futureStopData'] = str(
                            e.trip_update.stop_time_update)

                        # Post dict
                        try:
                            dynamodb = aws.getResource('dynamodb', 'us-east-1')
                            table = dynamodb.Table("mtaData")

                            table.update_item(
                                Key={'tripId': self.D['tripId']},
                                UpdateExpression=
                                "set ts = :a,routeId=:b,startDate=:c,direction=:d,futureStopData=:e",
                                ExpressionAttributeValues={
                                    ':a': self.D['ts'],
                                    ':b': self.D['routeId'],
                                    ':c': self.D['startDate'],
                                    ':d': self.D['direction'],
                                    ':e': self.D['futureStopData']
                                })
                        except KeyboardInterrupt:
                            exit
                        except:
                            print "Update Error 2"
                except KeyboardInterrupt:
                    exit
                except:
                    print "For Loop Error 1"

        except KeyboardInterrupt:
            exit
        except:
            print "mtaUpdates Error"
	def __init__(self,trainingData):
		# Get s3 resource , function for this is in utils/aws
		self.S3 = aws.getResource('s3','us-west-1')
		self.trainingData = trainingData
Esempio n. 23
0
def main():
    dynamodb = aws.getResource('dynamodb', 'us-east-1')
    snsClient = aws.getClient('sns', 'us-east-1')
    snsResource = aws.getResource('sns', 'us-east-1')

    # Create topic if it doesn't already exist
    createResponse = snsClient.create_topic(Name='mtaSub')
    topicArn = createResponse['TopicArn']

    dynamoTable = dynamodb.Table(DYNAMODB_TABLE_NAME)

    # Get list of all stopIds
    stations = buildStationssDB()

    while True:
        prompt()
        sys.stdout.write(">select a command : ")
        userIn = sys.stdin.readline().strip()
        if len(userIn) < 1:
            print "Command not recognized"
        else:
            if userIn == '1':
                sys.stdout.write(">Enter source : ")
                sourceStop = sys.stdin.readline().strip()
                if sourceStop not in stations:
                    sys.stdout.write(">Invalid stop id. Enter a valid stop id")
                    sys.stdout.flush()
                    continue

                if not isValidSourceStation(sourceStop):
                    sys.stdout.write(
                        '>You must start north of 96th street or at Times Sq.')
                    sys.stdout.flush()
                    continue

                sys.stdout.write(">Enter destination : ")
                destinationStop = sys.stdin.readline().strip()
                if destinationStop not in stations:
                    sys.stdout.write(">Invalid stop id. Enter a valid stop id")
                    sys.stdout.flush()
                    continue

                if not isValidDestinationStation(sourceStop):
                    sys.stdout.write(
                        '>You must end north of 96th street or at Times Sq.')
                    sys.stdout.flush()
                    continue

                if sourceStop == destinationStop:
                    sys.stdout.write('>You are already at the station!')
                    sys.stdout.flush()
                    continue

                sys.stdout.write(">Type N for uptown, S for downtown: ")
                direction = sys.stdin.readline().strip()

                # Validate direction
                if direction not in ['N', 'S']:
                    sys.stdout.write(
                        ">Invalid direction. Enter a valid direction")
                    sys.stdout.flush()
                    continue

                # You can figure out the direction from the source and destinations
                actualDirection = getDirectionOfStops(stations, sourceStop,
                                                      destinationStop)
                if actualDirection != direction:
                    sys.stdout.write(">Wrong direction!")
                    sys.stdout.flush()
                    continue

                if sourceStop == timesSquareStopId:
                    sourceStop = getDirectedStopId(sourceStop, direction)
                    destinationStop = getDirectedStopId(
                        destinationStop, direction)
                    # Find incoming local trains
                    incomingLocals = getIncomingTrainsToStation(
                        dynamoTable, direction, '1', sourceStop)
                    print "Local trains incoming to ", sourceStop
                    for l in incomingLocals:
                        print l['tripId']
                    earliestLocal = getEarliestTrain(incomingLocals,
                                                     sourceStop, direction)
                    print "The next local train coming is ", earliestLocal[
                        'tripId']
                    print "It arrives at ", earliestLocal['futureStopData'][
                        sourceStop][0]['arrivalTime']

                    incomingExpresses = getIncomingTrainsToStation(
                        dynamoTable, direction, ['2', '3'], sourceStop)
                    print "Express trains incoming to ", sourceStop
                    for e in incomingExpresses:
                        print e["tripId"]
                    earliestExpress = getEarliestTrain(incomingExpresses,
                                                       sourceStop, direction)
                    print "The next express train coming is ", earliestExpress[
                        'tripId']
                    print "It arrives at ", earliestExpress['futureStopData'][
                        sourceStop][0]['arrivalTime']

                    # Go directly on local
                    localArrivalTime = getTimeToReachFutureStop(
                        earliestLocal, destinationStop, direction)
                    print "The local train will arrive at destination ", destinationStop, " at ", localArrivalTime

                    # Stop at 96th and get off the express
                    expressTo96thTime = getTimeToReachFutureStop(
                        earliestExpress, ninetySixthStopId, direction)
                    # Next local arriving at 96th after that
                    incomingLocals = getIncomingTrainsToStation(
                        dynamoTable, direction, '1', ninetySixthStopId)
                    earliestLocal = getEarliestTrain(incomingLocals,
                                                     ninetySixthStopId,
                                                     direction,
                                                     expressTo96thTime)
                    expressAndLocalArrivalTime = getTimeToReachFutureStop(
                        earliestLocal, destinationStop, direction)
                    print "If you take an express, you must switch at ", ninetySixthStopId
                    print "Express will be at your destination at ", expressAndLocalArrivalTime

                    if localArrivalTime < expressAndLocalArrivalTime:
                        print "Take the next local"
                        sendNotification(snsClient, topicArn, "Take Local")
                    else:
                        print "Take the express to 96th"
                        sendNotification(snsClient, topicArn, "Take Express")
                    continue

                sourceStop = getDirectedStopId(sourceStop, direction)
                destinationStop = getDirectedStopId(destinationStop, direction)
                ninetySixthStop = getDirectedStopId(ninetySixthStopId,
                                                    direction)

                # The next train coming at your source station
                potentialTrains = getIncomingTrainsToStation(
                    table=dynamoTable,
                    direction=direction,
                    routeId='1',
                    stopId=sourceStop)
                currentLocalTrain = getEarliestTrain(trains=potentialTrains,
                                                     stopId=sourceStop,
                                                     direction=direction)
                print "The next local train to ", sourceStop, " will arrive at ", \
                    currentLocalTrain['futureStopData'][sourceStop][0]['arrivalTime']

                # Time it gets to 96th street
                arrival96th = currentLocalTrain['futureStopData'][
                    ninetySixthStop][0]['arrivalTime']
                print "It will arrive at 96th Street at ", arrival96th

                # Next local train when you arrive at 96th
                print "When you get to 96th street . . . "
                localsTo96th = getIncomingTrainsToStation(
                    dynamoTable, direction, '1', ninetySixthStop)
                # Task 1: Print trip IDs
                for l in localsTo96th:
                    print l['tripId']
                local96th = getEarliestTrain(localsTo96th, ninetySixthStop,
                                             direction, arrival96th)
                # Task 3
                print "Earliest Local Train: ", local96th['tripId']
                print "It will arrive at ", local96th['futureStopData'][
                    ninetySixthStop][0]['arrivalTime']

                # Next express train when you arrive at 96th
                expressesTo96th = getIncomingTrainsToStation(
                    dynamoTable, direction, ['2', '3'], ninetySixthStop)
                # Task 2: Print express trip IDs
                for e in expressesTo96th:
                    print e['tripId']
                express96th = getEarliestTrain(expressesTo96th,
                                               ninetySixthStop, direction,
                                               arrival96th)
                print "Earliest Express Train: ", express96th['tripId']
                print "It will arrive at ", express96th['futureStopData'][
                    ninetySixthStop][0]['arrivalTime']

                # local time to get to 42nd
                timeToDestinationLocal = currentLocalTrain['futureStopData'][
                    destinationStop][0]['arrivalTime']
                timeToDestinationExpress = express96th['futureStopData'][
                    destinationStop][0]['arrivalTime']

                # Task 5
                print "Local will arrive at destination ", destinationStop, " at ", timeToDestinationLocal
                print "Express will arrive at destination ", destinationStop, " at ", timeToDestinationExpress

                # Task 6a
                if timeToDestinationLocal > timeToDestinationExpress:
                    print "Switch over to express"
                    sendNotification(snsClient, topicArn,
                                     "Switch to express @ 96th")
                else:
                    print "Stay with Local"
                    sendNotification(snsClient, topicArn,
                                     "Stay on local @ 96th")

            elif userIn == '2':
                sys.stdout.write(">Enter Phone No. ")
                phone_number = sys.stdin.readline().strip()
                # Task 9
                addSubscriber(snsClient, topicArn, phone_number)
            elif userIn == '3':
                print "Bye, Felicia . . ."
                exit(0)
            else:
                print "Unknown command. Terminating."
                sys.exit(6)
Esempio n. 24
0
def s3_operation(filename, userid, amount):
    s3 = aws.getResource('s3', 'us-east-1')
    s3.Bucket('iot-bucket-llha').upload_file(filename,
                                             userid + '_' + amount + '.jpg')
Esempio n. 25
0
from datetime import datetime
import time
import calendar
from collections import deque
import os
# boto3 s3
import boto3
import aws
from boto3.dynamodb.conditions import Key,Attr

# ml
import predict
from sqlalchemy import *

# initial s3
s3 = aws.getResource('s3', '')
dynamodb = aws.getResource('dynamodb', "")
curtime = calendar.timegm(time.gmtime())

"""sns"""
client = aws.getClient("","")
topic_arn = ""

TIMEPOINTER = None

expire_table = dynamodb.Table('fruit-expire')


def download_img(filename):

    s3.meta.client.download_file('iotfruit',filename, filename)
Esempio n. 26
0
# Usage python dynamodata.py
# *********************************************************************************************
import json,time,sys
from collections import OrderedDict
import threading
import time

import boto3
from boto3.dynamodb.conditions import Key,Attr
from decimal import Decimal 

sys.path.append('../utils')
import tripupdate,vehicle,alert,mtaUpdates,aws

### YOUR CODE HERE ####
dynamodb = aws.getResource('dynamodb','us-east-1')
#endpoint_url="https://dynamodb.us-east-1.amazonaws.com")
#dynamodb = aws.getResource('dynamodb','us-east-1')

# Create the DynamoDB table.
try:
    mta = dynamodb.create_table(
        TableName='mta',
        KeySchema=[
            {
                'AttributeName': 'tripId',
                'KeyType': 'HASH'
	    },

            {
                'AttributeName': 'routeId',
Esempio n. 27
0
import aws as aws

# Constants
DYNAMODB_TABLE_NAME = "mtaData"
DEBUG = True
with open('Lab4/config.json') as json_config:
    config = json.load(json_config)
    client = boto3.client(
        'sns',
        aws_access_key_id=config['aws_access_key_id'],
        aws_secret_access_key=config['aws_secret_access_key'],
        region_name=config['aws_region'])
    topic = client.create_topic(Name="mtaSub")
    topic_arn = topic['TopicArn']

dynamodb = aws.getResource("dynamodb", "us-east-1")


def Dprint(context):
    if DEBUG:
        print context


# prompt
def prompt():
    print ""
    print "> Available Commands are: "
    print "1. plan trip"
    print "2. subscribe to message feed"
    print "3. exit"