Example #1
0
 def test_negative_speeds(self):
     """should raise error if max speed or speed is negative"""
     self.assertRaises(vehicle.OutOfRangeError, vehicle.vehicle.get_speed,
                       vehicle.vehicle("test", 10, 10, -1))
     self.assertRaises(vehicle.OutOfRangeError,
                       vehicle.vehicle.get_max_speed,
                       vehicle.vehicle('test', 3, -1, 2))
Example #2
0
def matchVehicles(currentFrameVehicles,im_width,im_height,image):
	if len(vehicles)==0:
		for box,color in currentFrameVehicles:
			(y1,x1,y2,x2)=box
			(x,y,w,h)=(x1*im_width,y1*im_height,x2*im_width-x1*im_width,y2*im_height-y1*im_height)
			X=int((x+x+w)/2)
			Y=int((y+y+h)/2)
			if Y>yl5:
				#cv2.circle(image,(X,Y),2,(0,255,0),4)
				#print('Y=',Y,'  y1=',yl1)
				vehicles.append(vehicle((x,y,w,h)))


	else:
		for i in range(len(vehicles)):
			vehicles[i].setCurrentFrameMatch(False)
			vehicles[i].predictNext()
		for box,color in currentFrameVehicles:
			(y1,x1,y2,x2)=box
			(x,y,w,h)=(x1*im_width,y1*im_height,x2*im_width-x1*im_width,y2*im_height-y1*im_height)
			#print((x1*im_width,y1*im_height,x2*im_width,y2*im_height),'\n',(x,y,w,h))
			index = 0
			ldistance = 999999999999999999999999.9
			X=int((x+x+w)/2)
			Y=int((y+y+h)/2)
			if Y>yl5:
				#print('Y=',Y,'  y1=',yl1)
				#cv2.circle(image,(X,Y),4,(0,0,255),8)
				for i in range(len(vehicles)):
					if vehicles[i].getTracking() == True:
						#print(vehicles[i].getNext(),i)
						distance = ((X-vehicles[i].getNext()[0])**2+(Y-vehicles[i].getNext()[1])**2)**0.5

						if distance<ldistance:
							ldistance = distance
							index = i


				diagonal=vehicles[index].diagonal

				if ldistance < diagonal:
					vehicles[index].updatePosition((x,y,w,h))
					vehicles[index].setCurrentFrameMatch(True)
				else:
					#blue for last position
					#cv2.circle(image,tuple(vehicles[index].points[-1]),2,(255,0,0),4)
					#red for predicted point
					#cv2.circle(image,tuple(vehicles[index].getNext()),2,(0,0,255),2)
					#green for test point
					#cv2.circle(image,(X,Y),2,(0,255,0),4)

					#cv2.imshow('culprit',image)
					#time.sleep(5)
					#print(diagonal,'               ',ldistance)
					vehicles.append(vehicle((x,y,w,h)))

		for i in range(len(vehicles)):
			if vehicles[i].getCurrentFrameMatch() == False:
				vehicles[i].increaseFrameNotFound()
 def parallel_missing_previous_available(self):
     car1 = vehicle('car', self.canvas, 1, 0, 1)
     car3 = vehicle('car', self.canvas, 1, 80, 3)
     car5 = vehicle('car', self.canvas, 2, 40, 5)
     bus = vehicle('bus', self.canvas, 2, 100, 6)
     v_list = [car1, car3, car5, bus]
     g = GetNeighbour(v_list)
     self.vehicle_list = v_list
    def parallel_available_previous_missing(self):

        car2 = vehicle('car', self.canvas, 1, 40, 2)
        car3 = vehicle('car', self.canvas, 1, 80, 3)
        car4 = vehicle('car', self.canvas, 2, 0, 4)
        car5 = vehicle('car', self.canvas, 2, 40, 5)
        bus = vehicle('bus', self.canvas, 2, 100, 6)
        v_list = [car2, car3, car4, car5, bus]
        g = GetNeighbour(v_list)
        self.vehicle_list = v_list
Example #5
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)
	

	timestamp = feed.header.timestamp
        nytime = datetime.fromtimestamp(timestamp,self.TIMEZONE)
	
	for entity in feed.entity:
	    # Trip update represents a change in timetable
	    if entity.trip_update and entity.trip_update.trip.trip_id:
		update = tripupdate.tripupdate()
		
		##### INSERT TRIPUPDATE CODE HERE ####			

	    if entity.vehicle and entity.vehicle.trip.trip_id:
	    	v = vehicle.vehicle()
		##### INSERT VEHICLE CODE HERE #####
	    
	    if entity.alert:
                a = alert.alert()
		#### INSERT ALERT CODE HERE #####

	return self.tripUpdates
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

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

        for entity in feed.entity:
            # Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()
                ##### INSERT TRIPUPDATE CODE HERE ####
                update.tripId = str(entity.trip_update.trip.trip_id)
                update.routeId = str(entity.trip_update.trip.route_id)
                update.startDate = entity.trip_update.trip.start_date
                update.direction = str(entity.trip_update.trip.trip_id[10])
                curr_vehicle = self.returnVehicle(update.tripId)
                num = 0
                for i in entity.trip_update.stop_time_update:
                    update.futureStops[num] = (
                        '"'
                        + str(i.stop_id)
                        + '": [{"arrivalTime": '
                        + str(i.arrival.time)
                        + '}, {"departureTime": '
                        + str(i.departure.time)
                        + "}]"
                    )
                    #                    print update.futureStops[num]
                    num += 1
                if curr_vehicle is not None:
                    update.vehicleData = curr_vehicle
                self.tripUpdates.append(update)
            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                ##### INSERT VEHICLE CODE HERE #####
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = str(entity.vehicle.stop_id)
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status
                v.trip_id = str(entity.vehicle.trip.trip_id)
                v.start_date = entity.vehicle.trip.start_date
                v.route_id = entity.vehicle.trip.route_id
                self.vehicles.append(v)
                cor_trip = self.returnTrip(v.trip_id)
                cor_alert = self.returnAlert(v.trip_id)
                if cor_trip is not None:
                    cor_trip.vehicleData = v

            if entity.alert:
                a = alert.alert()
                #### INSERT ALERT CODE HERE #####
                a.alertMessage = entity.alert.header_text.translation
                self.alerts.append(a)

        return self.tripUpdates
Example #7
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)
	

	timestamp = feed.header.timestamp
        nytime = datetime.fromtimestamp(timestamp,self.TIMEZONE)
	
	for entity in feed.entity:
	    # Trip update represents a change in timetable
	    if entity.trip_update and entity.trip_update.trip.trip_id:
		update = tripupdate.tripupdate()

		##### INSERT TRIPUPDATE CODE HERE ####	

	    if entity.vehicle and entity.vehicle.trip.trip_id:
	    	v = vehicle.vehicle()

		##### INSERT VEHICLE CODE HERE #####
	    
	    if entity.alert:
                a = alert.alert()=

                #### INSERT ALERT CODE HERE #####

	return self.tripUpdates
Example #8
0
 def verify_rental(self, n=0):
     self.errors = []
     print self.data
     if self.data[n]['rental_startdate'] == '':
         self.errors.append("You must enter the start date of the rental.")
     if self.data[n]['rental_duration'] == '':
         self.errors.append("You must enter the end date of the rental.")
     if self.data[n]['rental_duration'] < 1:
         self.errors.append("You must a positive number of days")
     else:
         v = vehicle()
         v.getById(self.data[n]['vehicle_id'])
         self.data[n]['rental_price'] = int(
             self.data[n]['rental_duration']) * int(
                 v.data[0]['price_per_day'])
         print self.data[n]['rental_price']
     if self.data[n]['rental_price'] == '':
         self.errors.append("You must enter the price of the rental.")
     if self.data[n]['rental_insurance'] == '':
         self.errors.append("You must enter the insurance of the vehicle.")
     if self.data[n]['vehicle_id'] == '':
         self.errors.append("You must enter the ID of the vehicle.")
     if len(self.errors) > 0:
         return False
     else:
         return True
Example #9
0
def retrieve_vehicle(s_veh_id):
    global L_VEHICLES
    veh = vehicle.vehicle(s_veh_id)
    # If we're already tracking the vehicle in L_VEHICLES then we
    # can copy the existing one. We'll remove it from the list until
    # we're finished modifying it.
    for _veh in L_VEHICLES:
        if _veh.get_id() == s_veh_id:
            veh = _veh
            L_VEHICLES.remove(_veh)
            break

    # Store the exit destination edge before we change route
    # so that we keep memory of where the vehicle was supposed
    # to go.
    if veh.get_final_dest_edge_id() == "":
        veh.set_final_dest_edge_id(traci.vehicle.getRoute(s_veh_id)[-1])

    # Set the capacity of the vehicle if it doesn't have one yet
    if veh.get_capacity() == -1:
        veh.set_capacity(
            random.randint(config.n_min_capacity, config.n_max_capacity))

    del s_veh_id
    return veh
def matchVehicles(currentFrameVehicles, im_width, im_height, image):
    if len(vehicles) == 0:
        for box, color in currentFrameVehicles:
            (y1, x1, y2, x2) = box
            (x, y, w, h) = (x1 * im_width, y1 * im_height,
                            x2 * im_width - x1 * im_width,
                            y2 * im_height - y1 * im_height)
            X = int((x + x + w) / 2)
            Y = int((y + y + h) / 2)
            if Y > yl5:
                vehicles.append(vehicle((x, y, w, h)))

    else:
        for i in range(len(vehicles)):
            vehicles[i].setCurrentFrameMatch(False)
            vehicles[i].predictNext()
        for box, color in currentFrameVehicles:
            (y1, x1, y2, x2) = box
            (x, y, w, h) = (x1 * im_width, y1 * im_height,
                            x2 * im_width - x1 * im_width,
                            y2 * im_height - y1 * im_height)
            index = 0
            ldistance = 999999999999999999999999.9
            X = int((x + x + w) / 2)
            Y = int((y + y + h) / 2)
            if Y > yl5:
                for i in range(len(vehicles)):
                    if vehicles[i].getTracking() == True:
                        distance = ((X - vehicles[i].getNext()[0])**2 +
                                    (Y - vehicles[i].getNext()[1])**2)**0.5

                        if distance < ldistance:
                            ldistance = distance
                            index = i

                diagonal = vehicles[index].diagonal

                if ldistance < diagonal:
                    vehicles[index].updatePosition((x, y, w, h))
                    vehicles[index].setCurrentFrameMatch(True)
                else:
                    vehicles.append(vehicle((x, y, w, h)))

        for i in range(len(vehicles)):
            if vehicles[i].getCurrentFrameMatch() == False:
                vehicles[i].increaseFrameNotFound()
def generate_vehicle(pubKey, seed_date):
    state = generate_random_string(str_len=2, lc=False, digits=False)
    model = generate_random_string(str_len=5, digits=False)
    registrationExp = seed_date + timedelta(days=random.randrange(4*30, 8*30))
    vin = generate_random_string(str_len=10, lc=False) + generate_random_string(str_len=7, lc=False, uc=False)

    new_vehicle = vehicle(pubKey, model, state, registrationExp, vin)
    return new_vehicle
Example #12
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

        timestamp = feed.header.timestamp
        print "Timestamp: ", timestamp
        nytime = datetime.fromtimestamp(timestamp, self.TIMEZONE)
        print "NYC Time: ", nytime

        self.timestamp = timestamp
        self.tripUpdates = []
        self.alerts = []

        for entity in feed.entity:
            # Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                # Assign the tripupdate fields
                t = tripupdate.tripupdate()
                t.tripId = entity.trip_update.trip.trip_id
                t.routeId = entity.trip_update.trip.route_id
                t.startDate = entity.trip_update.trip.start_date
                t.direction = entity.trip_update.trip.direction_id

                # There can be many StopTimeUpdate messages
                for st_update in entity.trip_update.stop_time_update:
                    times = []
                    times.append({"arrivalTime": st_update.arrival.time})
                    times.append({"departureTime": st_update.departure.time})
                    t.futureStops[st_update.stop_id] = times

                self.tripUpdates.append(t)

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = entity.vehicle.stop_id
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status

                # Using the trip_id on a vehicle, associate that vehicle with the trip update object
                vehicleTripId = entity.vehicle.trip.trip_id
                self.setVehicleDataOnTripUpdate(vehicleTripId, v)

            if entity.HasField('alert') and entity.alert:
                a = alert.alert()
                a.alertMessage = entity.alert.header_text.translation[0].text
                for informed_entity in entity.alert.informed_entity:
                    tripId = informed_entity.trip.trip_id
                    a.tripId.append(tripId)
                    a.routeId[tripId] = informed_entity.trip.route_id
                    a.startDate[tripId] = informed_entity.trip.start_time
                self.alerts.append(a)

        return self.tripUpdates
Example #13
0
def edit_rentalcustomer(rental_id):
    emsg = ''
    if not checkSession(1):
        return redirect("/mainmenu")
    r = rental()
    v = vehicle()
    v.getAvailableVehicles()
    if request.args.get('action') == 'insert':
        r.createBlank()
        print r.data
        r.data[0]['rental_startdate'] = request.form.get('rental_startdate')
        r.data[0]['rental_duration'] = request.form.get('rental_duration')
        r.data[0]['rental_price'] = request.form.get('rental_price')
        r.data[0]['rental_insurance'] = request.form.get('rental_insurance')
        r.data[0]['user_id'] = session['user_data']['user_id']
        r.data[0]['vehicle_id'] = request.form.get('vehicle_id')
        if r.verify_rental():
            r.insert()
            emsg = 'Rental added.'
        else:
            emsg = '<div style="color:red;">' + r.getErrorHTML() + '</div>'

    if rental_id == 'new':
        r.createBlank()
        w = 'Add'
        a = 'insert'
    else:
        r.getById(rental_id)
        w = 'Edit'
        a = 'update'
    html = '''
    <b>''' + w + ''' Rental ''' + rental_id + '''</b><br><br>
    ''' + emsg + '''
    <form action="/rental/''' + str(
        rental_id) + '''?action=''' + a + '''" method="POST">
        Rental Start Date<br>
        <input name="rental_startdate" type="date" value="''' + r.data[0][
            'rental_startdate'] + '''" /><br>
        Rental Duration<br>
        <input name="rental_duration" type="number" value="''' + r.data[0][
                'rental_duration'] + '''" /><br>
        Vehicle<br>
        ''' + v.getAvailableDropDown() + '''<br>
        Rental Price<br>
        <input name="rental_price" type="text" value="''' + str(
                    r.data[0]['rental_price']) + '''" /><br>
        Rental Insurance<br>
        <input name="rental_insurance" type="text" value="''' + r.data[0][
                        'rental_insurance'] + '''" /><br>
        <br><br>
        <input type="submit" value="Submit"/><br>
        <a href="/mainmenu">Main Menu</a><br>
    </form>
    
    '''

    return header() + html + footer()
Example #14
0
 def test_overspeed(self):
     for test_speed, KnownResult in self.knownOverspeedValues:
         # create test vehicle
         testDrive = vehicle.vehicle("testDrive", self.horsepower,
                                     self.max_speed, test_speed)
         print("Testing if %d is overspeed for testDrive of max speed %d" %
               (test_speed, testDrive.max_speed))
         functionResult = testDrive.is_overspeed()
         self.assertIs(functionResult, KnownResult)
Example #15
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

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

        for entity in feed.entity:
            #Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                trip_id = entity.trip_update.trip.trip_id
                update = tripupdate.tripupdate()

                update.tripId = entity.trip_update.trip.trip_id
                update.routeId = entity.trip_update.trip.route_id
                update.startDate = entity.trip_update.trip.start_date

                # parse trip id for direction
                if (re.search('N', str(entity.trip_update.trip.trip_id))):
                    update.direction = 'N'
                else:
                    update.direction = 'S'

                ### stop_time_update is a LIST ###
                for stop_time_updates in entity.trip_update.stop_time_update:
                    departureTime = None
                    arrivalTime = stop_time_updates.arrival.time
                    stopId = stop_time_updates.stop_id
                    if stop_time_updates.departure:
                        departureTime = stop_time_updates.departure.time
                    update.futureStops[stopId] = [{
                        "arrivalTime":
                        arrivalTime,
                        "departureTime":
                        departureTime
                    }]

                self.tripUpdates[trip_id] = update

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()

                v.currentStopId = entity.vehicle.stop_id
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status

                update.vehicleData = v

                self.tripUpdates[str(entity.vehicle.trip.trip_id)] = update

        return self.tripUpdates, timestamp
Example #16
0
 def do_work_if_vehicles_empty(x, y, w, h):
     # ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ Ρ†Π΅Π½Ρ‚Ρ€ΠΎΠΈΠ΄Π°
     X = int((x + x + w) / 2)
     Y = int((y + y + h) / 2)
     # условиС пСрСсСчСния послСднСй Π²Π΅Ρ€Ρ…Π½Π΅ΠΉ Π»ΠΈΠ½ΠΈΠΈ, Ссли машина Π½Π΅ пСрСсСкла линию:
     if Y > yl5:
         # cv2.circle(image,(X,Y),2,(0,255,0),4)
         # print('Y=',Y,'  y1=',yl1)
         vehicles.append(vehicle((x, y, w, h)))
Example #17
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)
	

        timestamp = feed.header.timestamp
        nytime = datetime.fromtimestamp(timestamp,self.TIMEZONE)
	
        for entity in feed.entity:
            # Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()
		
                ##### INSERT TRIPUPDATE CODE HERE ####	

                update.tripId       = entity.trip_update.trip.trip_id
                update.routeId      = entity.trip_update.trip.route_id
                update.startDate    = entity.trip_update.trip.start_date
                update.direction    = entity.trip_update.stop_time_update[-1].stop_id[-1]
                update.vehicleData  = entity.trip_update.vehicle
		newkey = entity.trip_update.stop_time_update[-1].stop_id
		low    = entity.trip_update.stop_time_update[-1].arrival.time
		hi     = entity.trip_update.stop_time_update[-1].departure.time
                update.futureStops.update({ newkey : [low,hi] })# Format {stopId : [arrivalTime,departureTime]})

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                
                ##### INSERT VEHICLE CODE HERE #####
                
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId     = entity.vehicle.stop_id
                v.timestamp         = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status
            if entity.alert:
                a = alert.alert()
                
                #### INSERT ALERT CODE HERE #####
                #print entity.alert.informed_entity
                a.tripId            = entity.trip_update.trip.trip_id
                a.routeId           = entity.trip_update.trip.route_id
                a.startDate         = entity.trip_update.trip.start_date
		try:
                    a.alertMessage  = entity.alert.header_text.translation.text
		except:
		    a.alertMessage  = ''
	
	self.tripUpdates.append(update)
	self.tripUpdates.append(v)
	self.tripUpdates.append(a)

	return self.tripUpdates
Example #18
0
 def test_speed_down(self):
     '''speed_down shoudl return known outputs'''
     for initial_speed, known_result in self.knownSpeedDownValues:
         # creat test vehicle called "test drive"
         # print("Testing speed down from: %d km/h" %(initial_speed))
         testDrive = vehicle.vehicle("testDrive", self.horsepower,
                                     self.max_speed, initial_speed)
         testDrive.speed_down()
         final_speed = testDrive.get_speed()
         self.assertEqual(final_speed, known_result)
Example #19
0
 def test_speed_up(self):
     """ speed_up should return known outputs"""
     for initial_speed, known_result in self.knownSpeedUpValues:
         # create test vehicle called "test drive"
         # print("Testing speed up value from %d km/h" %(initial_speed))
         testDrive = vehicle.vehicle('testDrive', self.horsepower,
                                     self.max_speed, initial_speed)
         testDrive.speed_up()
         final_speed = testDrive.get_speed()
         self.assertEqual(final_speed, known_result)
Example #20
0
def main():
    #Instatiate vehicle here
    #car = vehicle("Car",("",""),{"":"","":""})
    highlander = ("Car","2014","Toyota","Highlander")
    car = vehicle(highlander)
    car.setDoorCount(4)
    car.setNumberOFWheels(4)
    car.setCapacity(7)
    car.printVehicle()
    car.start()
    car.stop()
Example #21
0
 def get_send_packets(self, time):
     vehicles = []
     for trace in self.vehicle_traces:
         if trace.get_xy_from_time(time) is not None:
             v = vehicle(packet_loss_rate=self.packet_loss_rate)
             v.set_vehicleID(trace.get_vehicleID())
             v.set_time(time)
             v.set_location(trace.get_xy_from_time(time=time))
             v.set_packet_loss()
             v.set_transmission_delay()
             vehicles.append(v)
     return vehicles
def tracker(vehicle_list, new_bounding_box):
    '''
    parameters :
    vehicle_list -> list of previously detected vehicle
    new_bounding_box -> currently detected bounding box
  '''
    #DEBUG INFO
    print(f'no of current detection : {len(new_bounding_box)}')
    print(f'no of previous detection : {len(vehicle_list)}')
    #END

    unassigned = [i for i in range(len(new_bounding_box))]
    updated_list = []

    #assigning new coordinates to previously detected vehicle
    for index, bounding_box in enumerate(new_bounding_box):
        nearest = (None, None)  #(vehicle index, distance)
        for v_index, vehicle_obj in enumerate(vehicle_list):
            distance = euclidean_distance(vehicle_obj, bounding_box)
            if (distance >= 0):
                if nearest[1] is None:
                    nearest = (v_index, distance)
                else:
                    if (distance < nearest[1]):
                        nearest = (v_index, distance)

        #update previously detected vehicle
        if nearest[0] is not None:
            vehicle_obj = vehicle_list[nearest[0]]
            vehicle_obj.update(new_bounding_box[index])

            del (vehicle_list[nearest[0]])
            updated_list.append(vehicle_obj)
            unassigned.remove(index)

    #unassigned bounding box
    new_bounding_box = new_bounding_box[unassigned]
    for box in new_bounding_box:
        updated_list.append(vehicle(box))

    #undetected vehicle
    for vehicle_obj in vehicle_list:
        vehicle_obj.undetected_for += 1
        if vehicle_obj.undetected_for <= MAX_UNDETECTION:
            updated_list.append(vehicle_obj)

    #DEBUG INFO
    print(f'total assigned : {len(updated_list)}')
    #END

    #return updated vehicle object list
    return updated_list
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

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

        for entity in feed.entity:
            # Trip update represents a change in timetable
            update = None
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()
                update.tripId = entity.trip_update.trip.trip_id
                update.routeId = entity.trip_update.trip.route_id
                update.startDate = entity.trip_update.trip.start_date
                update.direction = entity.trip_update.trip.trip_id[
                    entity.trip_update.trip.trip_id.find("..") + 2]
                update.vehicleData = entity.vehicle

                for e in entity.trip_update.stop_time_update:
                    arrivalTime = e.arrival.time
                    departureTime = e.departure.time
                    v1 = {"arrivalTime": arrivalTime}
                    v2 = {"departureTime": departureTime}
                    value = [v1, v2]
                    update.futureStops[e.stop_id] = value

            v = None
            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = entity.vehicle.stop_id
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status

            a = None
            if entity.alert:
                a = alert.alert()
                for trip in entity.alert.informed_entity:
                    a.tripId.append(trip.trip_id)
                    a.routeId[trip.trip_id] = trip.route_id
                    a.startDate[trip.trip_id] = trip.start_date

            self.tripUpdates.append([update, v, a])

        return self.tripUpdates
Example #24
0
 def get_packet_in_seconds(self):
     start_time = self.get_start_time(self.time)
     for time in range(start_time, start_time + self.during_time):
         vehicles = []
         for trace in self.vehicle_traces:
             if trace.get_xy_from_time(time) is not None:
                 v = vehicle()
                 v.set_vehicleID(trace.get_vehicleID())
                 v.set_time(time)
                 v.set_location(trace.get_xy_from_time(time=time))
                 v.set_packet_loss(self.packet_loss_rate)
                 v.set_transmission_delay()
                 vehicles.append(v)
         self.packets_in_seconds.append(vehicles)
    def parallel_and_previous_car_available(self):

        car1 = vehicle('car', self.canvas, 1, 0, 1)
        car2 = vehicle('car', self.canvas, 1, 40, 2)
        car3 = vehicle('car', self.canvas, 1, 80, 3, True)
        car6 = vehicle('car', self.canvas, 2, -40, 7)
        car4 = vehicle('car', self.canvas, 2, 0, 4)
        car5 = vehicle('car', self.canvas, 2, 40, 5)
        bus = vehicle('bus', self.canvas, 2, 100, 6, True)

        v_list = [car1, car2, car3, car6, car4, car5, bus]
        g = GetNeighbour(v_list)
        self.vehicle_list = v_list
Example #26
0
 def get_prediction_trace(self, saver):
     trace = self.origin_trace
     origin_time = trace[-1].time
     origin_id = trace[-1].vehicleID
     for i in range(self.prediction_seconds):
         prediction_location = self.predict(trace, saver)
         if prediction_location is not None:
             v = vehicle()
             v.set_vehicleID(origin_id)
             v.set_location(prediction_location)
             v.set_time(origin_time + i + 1)
             trace.append(v)
         else:
             break
     return trace
def final_cal(orbit_name,crater_percent, vehicle_list, distance, craters, traffic_speed, result):
    if crater_percent < 0:
        actual_crater = craters - (craters*(abs(crater_percent))/100)
    elif crater_percent >= 0 :
        actual_crater = craters + ((craters*crater_percent)/100)

    
    for vc in vehicle_list:
        vc_obj = vehicle.vehicle(vc)
        vehicle_speed,crater_time,rank = vc_obj.get_vehicle_details()
        if vehicle_speed >= traffic_speed:
            speed = traffic_speed
        else:
            speed = vehicle_speed
        time = ((60/speed)*distance)+(actual_crater*crater_time)
        result.append([time, vc, orbit_name,rank])
    return result
Example #28
0
 def get_prediction_trace(self, saver):
     prediction_trace = None
     trace = self.origin_trace
     origin_time = trace[-1].time
     origin_id = trace[-1].vehicleID
     for i in range(self.prediction_seconds):
         prediction_location = self.predict(trace, saver)
         if prediction_location is not None:
             v = vehicle(self.packet_loss_rate)
             v.set_vehicleID(origin_id)
             v.set_location(prediction_location)
             v.set_time(origin_time + i + 1)
             trace.append(v)
         else:
             # print("prediction location is none in HMM_MODEL get prediction trace")
             break
     prediction_trace = trace
     return prediction_trace
Example #29
0
    def do_work_if_vehicles_full(x, y, w, h):
        index = 0
        # растояниС ΠΌΠ΅ΠΆΠ΄Ρƒ points ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ Π½Π° сопоставлСниС: Ρ‚ΠΎΡ‚-ΠΆΠ΅ Π°Π²Ρ‚ΠΎΠΌΠΎΠ±ΠΈΠ»ΡŒ отслСТиваСтся ΠΈΠ»ΠΈ
        # это Π΄Ρ€ΡƒΠ³ΠΎΠΉ Π°Π²Ρ‚ΠΎΠΌΠΎΠ±ΠΈΠ»ΡŒ, ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ΡΡ: distance, ΠΈ diagonal; Π² классС vehicles для этого
        # ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹: updatePosition, setCurrentFrameMatch, getTracking, getNext... ΠΈ Ρ‚Π΄.
        ldistance = 999999999999999999999999.9
        X = int((x + x + w) / 2)
        Y = int((y + y + h) / 2)
        if Y > yl5:
            # print('Y=',Y,'  y1=',yl1)
            # cv2.circle(image,(X,Y),4,(0,0,255),8)
            # провСряСм какая Ρ‚ΠΎΡ‡ΠΊΠ° ΠΈΠ· боксов соотвСтствуСт ΠΊΠ°ΠΊΠΎΠΌΡƒ ΠΎΠ±ΡŒΠ΅ΠΊΡ‚Ρƒ vehicle
            for i in range(len(vehicles)):
                if vehicles[i].getTracking() == True:
                    # print(vehicles[i].getNext(),i)
                    # distance Ρ€Π°Π·Π½ΠΈΡ†Π° ΠΌΠ΅ΠΆΠ΄Ρƒ прСдсказанным Ρ†Π΅Π½Ρ‚Ρ€ΠΎΠΌ ΠΎΠ±ΡŒΠ΅ΠΊΡ‚Π°, ΠΈ фактичСскими ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Π°ΠΌΠΈ Ρ†Π΅Π½Ρ‚Ρ€Π° бокса,
                    # Ссли растояниС ΠΌΠ΅ΠΆΠ΄Ρƒ Π½ΠΈΠΌΠΈ мСньшС Ρ‡Π΅ΠΌ диагональ ΠΎΠ±ΡŒΠ΅ΠΊΡ‚Π°, Π·Π½Π°Ρ‡ΠΈΡ‚ новая Ρ‚ΠΎΡ‡ΠΊΠ° относится ΠΊ Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΌΡƒ
                    # ΠΎΠ±ΡŒΠ΅ΠΊΡ‚Ρƒ, Ссли Π½Π΅Ρ‚, Ρ‚ΠΎ Ρ‚ΠΎΡ‡ΠΊΠ° относится ΠΊ Π΄Ρ€ΡƒΠ³ΠΎΠΌΡƒ ΠΎΠ±ΡŒΠ΅ΠΊΡ‚Ρƒ (ΠΊ Π΄Ρ€ΡƒΠ³ΠΎΠΉ машинС)
                    distance = ((X - vehicles[i].getNext()[0])**2 +
                                (Y - vehicles[i].getNext()[1])**2)**0.5

                    if distance < ldistance:
                        ldistance = distance
                        index = i

            diagonal = vehicles[index].diagonal

            # Ссли растояниС ΠΌΠ΅ΠΆΠ΄Ρƒ Ρ‚ΠΎΡ‡ΠΊΠ°ΠΌΠΈ мСньшС Ρ‡Π΅ΠΌ диагональ бокса, для ΠΎΠ±ΡŒΠ΅ΠΊΡ‚Π° добавляСм Π½ΠΎΠ²Ρ‹ΠΉ Ρ†Π΅Π½Ρ‚Ρ€ ΠΈ Π½ΠΎΠ²ΡƒΡŽ диагональ
            if ldistance < diagonal:
                vehicles[index].updatePosition((x, y, w, h))
                vehicles[index].setCurrentFrameMatch(True)
            # Ссли Π½Π΅Ρ‚, создаём Π½ΠΎΠ²Ρ‹ΠΉ ΠΎΠ±ΡŒΠ΅ΠΊΡ‚ класса vehicle ΠΈ добавляСм Π΅Π³ΠΎ Π² лист vehicles
            else:
                # blue for last position
                # cv2.circle(image,tuple(vehicles[index].points[-1]),2,(255,0,0),4)
                # red for predicted point
                # cv2.circle(image,tuple(vehicles[index].getNext()),2,(0,0,255),2)
                # green for test point
                # cv2.circle(image,(X,Y),2,(0,255,0),4)

                # cv2.imshow('culprit',image)
                # time.sleep(5)
                # print(diagonal,'               ',ldistance)
                vehicles.append(vehicle((x, y, w, h)))
Example #30
0
 def get_prediction_trace_by_traditional_using_original(self, origin_trace):
     if len(origin_trace) >= 2:
         trace_last_one = origin_trace[-1]
         trace_last_two = origin_trace[-2]
         # add_x = trace_last_one.location_x - trace_last_two.location_x
         # add_y = trace_last_one.location_y - trace_last_two.location_y
         prediction_x = 2 * trace_last_one.location_x - trace_last_two.location_x
         prediction_y = 2 * trace_last_one.location_y - trace_last_two.location_y
         xy = []
         xy.append(prediction_x)
         xy.append(prediction_y)
         new_vehicle = vehicle()
         new_vehicle.set_vehicleID(trace_last_one.vehicleID)
         new_vehicle.set_location(xy)
         new_vehicle.set_time(trace_last_one.time + 1)
         origin_trace.append(new_vehicle)
         return origin_trace
     else:
         return origin_trace
Example #31
0
def list_vehicle():
    if not checkSession(2):
        return redirect("/mainmenu")
    html = ''' <b> Vehicles </b>
    <table style="width:600px;">
        <tr style="background-color:#bbb;">
            <td>Vehicle ID</td>
            <td>Make</td>
            <td>Model</td>
            <td>Year</td>
            <td>Vehicle Type</td>
            <td>Color</td>
            <td>Price per Day</td>
            <td>Vin Number</td>
            <td>Rental Status</td>
        </tr>'''
    v = vehicle()
    v.getAll()
    i = 0
    for row in v.data:
        c = '#eee;'
        if i % 2 == 0:
            c = '#ddd;'
        html += '''<tr style="background-color:''' + c + ''''">
            <td> <a href="/vehicle/''' + str(
            row['vehicle_id']) + '''">''' + str(
                row['vehicle_id']) + '''</a> </td>
            <td>''' + str(row['make']) + '''</td>
            <td>''' + str(row['model']) + '''</td>
            <td>''' + str(row['year']) + '''</td>
            <td>''' + str(row['vehicle_type']) + '''</td>
            <td>''' + str(row['color']) + '''</td>
            <td>''' + str(row['price_per_day']) + '''</td>
            <td>''' + str(row['vin_number']) + '''</td>
            <td>''' + str(row['rental_status']) + '''</td>
        </tr>'''
        i += 1

    html += '''</table>
    <a href="vehicle/new">Add New Vehicle</a><br>
    <br><a href = "/mainmenu">Main Menu</a><br>
    '''
    return header() + html + footer()
Example #32
0
    def set_vehicle_traces_and_collision_time_matrix_and_vehicle_id_array(
            self):
        self.vehicle_traces = self.get_trace()
        self.vehicle_number = len(self.vehicle_traces)
        self.vehicle_id_array = []
        self.collision_number = 0
        self.collision_message = []
        self.send_packets = []
        for i in range(self.vehicle_number - 1):
            for j in range(i + 1, self.vehicle_number):
                collision_time = self.get_collision_time(
                    vehicle_one=self.vehicle_traces[i],
                    vehicle_two=self.vehicle_traces[j])
                if collision_time == 0:
                    pass
                else:
                    self.collision_number += 1
                    self.collision_message.append({
                        'vehicleOne':
                        self.vehicle_traces[i].get_vehicleID(),
                        'vehicleTwo':
                        self.vehicle_traces[j].get_vehicleID(),
                        'collisionTime':
                        collision_time
                    })
            self.vehicle_id_array.append(
                int(self.vehicle_traces[i].get_vehicleID()))
        self.vehicle_id_array.append(int(
            self.vehicle_traces[-1].vehicleID))  # get the last one

        start_time = self.get_start_time(self.time)
        for time in range(start_time, start_time + self.during_time + 1):
            vehicles = []
            for trace in self.vehicle_traces:
                if trace.get_xy_from_time(time) is not None:
                    v = vehicle(packet_loss_rate=self.packet_loss_rate)
                    v.set_vehicleID(trace.get_vehicleID())
                    v.set_time(time)
                    v.set_location(trace.get_xy_from_time(time=time))
                    v.set_packet_loss()
                    v.set_transmission_delay()
                    vehicles.append(v)
            self.send_packets.append(vehicle)
Example #33
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

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

        for entity in feed.entity:
            # Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()

                ##### INSERT TRIPUPDATE CODE HERE ####
                update.tripId = entity.trip_update.trip.trip_id
                update.routeId = entity.trip_update.trip.route_id
                update.startDate = entity.trip_update.trip.start_date
                update.direction = entity.trip_update.trip.trip_id[10]
                update.futureStop[
                    entity.trip_update.stop_time_update.stop_id] = [
                        entity.trip_update.stop_time_update.arrival.time,
                        entity.trip_update.stop_time_update.departure.time
                    ]

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                ##### INSERT VEHICLE CODE HERE #####
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = entity.vehicle.stop_id
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status

            if entity.alert:
                a = alert.alert()
                #### INSERT ALERT CODE HERE #####
                alert.tripId = entity.alert.informed_entity.trip.trip_id
                alert.routeId = entity.alert.informed_entity.trip.route_id
                alert.startDate = entity.trip_update.trip.start_date

        return self.tripUpdates
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        #print type(time)
	try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)
    

        timestamp = feed.header.timestamp
        nytime = datetime.fromtimestamp(timestamp,self.TIMEZONE)
        tripUpdates = []
	uList = []
        vList = []
    	aList = []
        for entity in feed.entity:
            # Trip update represents a change in timetable
            
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()
                update.tripId = entity.trip_update.trip.trip_id
                update.routeId = entity.trip_update.trip.route_id
                update.startDate = entity.trip_update.trip.start_date
                tripId = entity.trip_update.trip.trip_id
                
                update.direction = tripId[tripId.rfind('.')+1]# n/s  parse from trip id

                #update.vehicleData = None

                d = OrderedDict()
                for stop in entity.trip_update.stop_time_update:
                    arrivalDict = {}
		    departDict = {}
		    arrive = None
                    depart = None
            
                    arrive = stop.arrival.time
                    depart = stop.departure.time

                    arrivalDict["arrival_time"] = arrive
		    departDict["depart_time"] = depart
		    d[stop.stop_id] = [arrivalDict, departDict]
                update.futureStops = d # Format {stopId : [arrivalTime,departureTime]}
                
                uList.append(update)            
            ##### INSERT TRIPUPDATE CODE HERE ####          

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = entity.vehicle.stop_id
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = entity.vehicle.current_status
                v.tripId = entity.vehicle.trip.trip_id
                vList.append(v)
            ##### INSERT VEHICLE CODE HERE #####
            if entity.alert:
                a = alert.alert()
        if hasattr(entity.alert, 'trip'):
                    a.tripId = entity.alert.trip.trip_id
                    a.routeId = entity.alert.trip.route_id
                    a.startDate = entity.alert.trip.start_date
                    a.alertMessage = entity.alert.header_text.translation           
            #### INSERT ALERT CODE HERE #####
        
        tripUpdates.append(uList)
        tripUpdates.append(vList)
        tripUpdates.append(aList)
        tripUpdates.append(timestamp)
        return tripUpdates
Example #35
0
import matplotlib.pyplot as plt
import numpy as np

import route
import vehicle

car = vehicle.vehicle(7, 10, 5, 3200, 4, 31.29, 9.8, 12, 12, 0.0, np.pi/4.0, \
                      [0, 0], [10, 20])

print car.pos
car.getOnHighway(car.pos, np.array([50, 50]), 0.01)
print car.vel
print car.speed


x = route.route(42.170350, -72.479596, 42.210243, -71.784453)
plt.plot(x.coords[:, 0], x.coords[:, 1])
plt.scatter(x.coords[:, 0], x.coords[:, 1])
plt.show()
Example #36
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

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

        for entity in feed.entity:
            # Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()
                ##### INSERT TRIPUPDATE CODE HERE ####
                header_time = feed.header.timestamp
                update.tripId = entity.trip_update.trip.trip_id
                update.routeId = entity.trip_update.trip.route_id
                update.startDate = entity.trip_update.trip.start_date
                directionId = update.tripId.rfind('.')
                directionInt = int(directionId)

                update.direction = update.tripId[int(directionInt+1):int(directionInt+2)]
                update.time = header_time
                update.futureStops = OrderedDict()

                for stop in entity.trip_update.stop_time_update:
                    stopId = stop.stop_id
                    stopInfo = OrderedDict()
                    stopInfo['arrivalTime'] = stop.arrival.time
                    stopInfo['departureTime'] = stop.departure.time
                    stopInfo['arrivalTime'] = stop.arrival.time
                    stopInfo['departureTime'] = stop.departure.time
                    update.futureStops[stopId] = stopInfo
                    #print "check1"
                self.tripUpdates.append(update)
                    #print self.tripUpdates

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                ##### INSERT VEHICLE CODE HERE #####
                header_time_v = entity.vehicle.timestamp
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = entity.vehicle.stop_id
                v.timestamp = header_time_v
                v.currentStopStatus = entity.vehicle.current_status

                for trip in self.tripUpdates:
                    if trip.tripId == entity.vehicle.trip.trip_id:
                        trip.vehicleData = v
                        #print "check2"

            if entity.alert:
                a = alert.alert()
                #### INSERT ALERT CODE HERE #####
                if entity.alert and entity.alert.header_text and entity.alert.header_text.translation and hasattr(entity.alert.header_text.translation,'text'):
                    a.alertMessage = entity.alert.header_text.translation.text
                if entity.alert and entity.alert.informed_entity and hasattr(entity.alert.informed_entity,'trip'):
                    if hasattr(entity.alert.informed_entity.trip,'trip_id'):
                        a.tripId = entity.alert.informed_entity.trip.trip_id
                        for tripUpdate in self.tripUpdates:
                            if tripUpdate.tripId == entity.alert.informed_entity.trip.trip_id:
                                a.startDate = tripUpdate.startDate
                    if entity.alert.informed_entity.trip.route_id:
                        a.routeId = entity.alert.informed_entity.trip.route_id
                        #print "check3"

                self.alerts.append(a)

        return self.tripUpdates
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)
	

	timestamp = feed.header.timestamp
        nytime = datetime.fromtimestamp(timestamp,self.TIMEZONE)
	
	for entity in feed.entity:
	    # Trip update represents a change in timetable
	    if entity.trip_update and entity.trip_update.trip.trip_id:
		update = tripupdate.tripupdate()
		update.tripId = entity.trip_update.trip.trip_id
		update.routeId = entity.trip_update.trip.route_id
		update.startDate = entity.trip_update.trip.start_date
		# We can get direction from tripId
		update.direction = update.tripId[10]
		
		# Route id could be 1,2,3,4,5,6 or S.
                # However for S they use  GS
                if update.routeId == 'GS':
                    update.routeId = 'S'
		
		# Create an ordered dictionary
		for stopUpdate in entity.trip_update.stop_time_update:
		    arrivalTime = {"arrivalTime" : stopUpdate.arrival.time}
		    departureTime = {"departureTime" : stopUpdate.departure.time}    
		    update.futureStops[stopUpdate.stop_id] = [arrivalTime, departureTime]
		
		
		self.tripUpdates.append(update)

	    if entity.vehicle and entity.vehicle.trip.trip_id:
	    	v = vehicle.vehicle()
		vehicleData = entity.vehicle
		tripId = vehicleData.trip.trip_id
		v.currentStopNumber = vehicleData.current_stop_sequence
		v.currentStopId = vehicleData.stop_id
		v.timestamp   =  vehicleData.timestamp
		if not vehicleData.current_status:
		    v.currentStopStatus = self.VCS[1]
		else:
		    v.currentStopStatus = self.VCS[vehicleData.current_status]
		# Find the tripUpdate object with the exact tripId
	    	tripUpdateObject = next((trip for trip in self.tripUpdates if trip.tripId == tripId), None)
		tripUpdateObject.vehicleData = v
	    
	    if entity.alert:
                a = alert.alert()
		for item in entity.alert.informed_entity:
		    trip = item.trip.trip_id
                    a.tripId.append(trip)
                    a.routeId[trip] = item.trip.route_id  
		a.alertMessage = entity.alert.header_text
		self.alerts.append(a)

	return self.tripUpdates
Example #38
0
 def test_vehicle(self):
     test_vehicle = vehicle(5, 4.1, 2, False)
     self.assertEqual(test_vehicle.wheels, 5)
     self.assertAlmostEqual(test_vehicle.fuel, 4.1)
     self.assertEqual(test_vehicle.doors, 2)
     self.assertFalse(test_vehicle.roof)
Example #39
0
    def getTripUpdates(self):
        feed = gtfs_realtime_pb2.FeedMessage()
        try:
            with contextlib.closing(urllib2.urlopen(self.feedurl)) 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)

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

        trips={}

        for entity in feed.entity:
            # print entity
            # Trip update represents a change in timetable
            if entity.trip_update and entity.trip_update.trip.trip_id:
                update = tripupdate.tripupdate()
                ##### INSERT TRIPUPDATE CODE HERE ####
                update.tripId = str(entity.trip_update.trip.trip_id)
		#print str(update.tripId)[-4]
                update.routeId = entity.trip_update.trip.route_id
                update.startDate = entity.trip_update.trip.start_date
		st = update.tripId
                if st.split('.')[1] == '':
			update.direction = st.split('.')[2][0]
                else:
         		update.direction = st.split('.')[1][0]
		#print update.direction
		#print entity.trip_update.trip.direction_id
                if entity.trip_update.vehicle:
                      update.vehicleData = entity.trip_update.vehicle
                tmp = collections.OrderedDict()
                len_stop = len(entity.trip_update.stop_time_update)
                for i in range(len_stop):
            	    #print entity.trip_update.stop_time_update[i].stop_id
		    #print entity.trip_update.stop_time_update[i].arrival.time
 		    #print entity.trip_update.stop_time_update[i].departure.time
                    tmp[str(entity.trip_update.stop_time_update[i].stop_id)] = [
                        entity.trip_update.stop_time_update[i].arrival.time,
                        entity.trip_update.stop_time_update[i].departure.time
                    ]
		#print tmp.items()
		#tmp = collections.OrderedDict()
                update.futureStops = str(tmp.items())
		#print update.futureStops

                if update.tripId not in trips.keys():
                    trips[update.tripId] = ini()
                trips[update.tripId]['routeId'] = update.routeId
                trips[update.tripId]['startDate'] = update.startDate
                trips[update.tripId]['direction'] = update.direction
                trips[update.tripId]['futureStopData'] = update.futureStops
		trips[update.tripId]['timeStamp'] =  timestamp
                
		#print 'tripId: ',update.tripId, 
	        #print 'routeId: ',update.routeId, 
                #print 'startDate: ',update.startDate

            if entity.vehicle and entity.vehicle.trip.trip_id:
                v = vehicle.vehicle()
                ##### INSERT VEHICLE CODE HERE #####
                v.currentStopNumber = entity.vehicle.current_stop_sequence
                v.currentStopId = entity.vehicle.stop_id
                v.timestamp = entity.vehicle.timestamp
                v.currentStopStatus = self.VCS[int(entity.vehicle.current_status)+1]
                #print v.currentStopNumber, v.currentStopId, 
		#print v.currentStopStatus
                if entity.vehicle.trip.trip_id not in trips.keys():
                    trips[entity.vehicle.trip.trip_id] = ini()
                trips[entity.vehicle.trip.trip_id]['currentStopId'] = v.currentStopNumber
                trips[entity.vehicle.trip.trip_id]['currentStopStatus'] = v.currentStopStatus
                trips[entity.vehicle.trip.trip_id]['vehicleTimeStamp'] = v.timestamp
                trips[entity.vehicle.trip.trip_id]['timeStamp']= timestamp
		
            if entity.alert:
                a = alert.alert()
                #### INSERT ALERT CODE HERE #####
                a.alertMessage = []
                mes_len = len(entity.alert.header_text.translation)
                for i in range(mes_len):
                    a.alertMessage.append(entity.alert.header_text.translation[i].text)
                a.tripId = []
		trip_len = len(entity.alert.informed_entity)
                for i in range(trip_len):
                     a.tripId.append(entity.alert.informed_entity[i].trip.trip_id)
                     a.routeId[entity.alert.informed_entity[i].trip.trip_id] = entity.alert.informed_entity[i].trip.route_id
                     if entity.alert.informed_entity[i].trip.start_date:
		                  a.startDate[entity.alert.informed_entity[i].trip.trip_id] = entity.alert.informed_entity[i].trip.start_date
                self.alerts.append(a)
		
        #print trips
        self.tripUpdates.append(trips) 
	return self.tripUpdates