Search in sources :

Example 1 with TimepointPredictionRecord

use of org.onebusaway.realtime.api.TimepointPredictionRecord in project onebusaway-application-modules by camsys.

the class GtfsRealtimeServiceImpl method getTripUpdates.

@Override
public FeedMessage getTripUpdates() {
    FeedMessage.Builder feedMessage = createFeedWithDefaultHeader();
    List<BlockLocation> activeBlocks = _blockStatusService.getAllActiveBlocks(SystemTime.currentTimeMillis());
    for (BlockLocation activeBlock : activeBlocks) {
        // Only interested in blocks with real-time data
        if (!activeBlock.isPredicted())
            continue;
        // Only interested in blocks with a next stop
        BlockStopTimeEntry nextBlockStop = activeBlock.getNextStop();
        if (nextBlockStop == null)
            continue;
        // Only interested in blocks with a schedule deviation set
        if (!activeBlock.isScheduleDeviationSet())
            continue;
        TripUpdate.Builder tripUpdate = TripUpdate.newBuilder();
        BlockTripEntry activeBlockTrip = nextBlockStop.getTrip();
        TripEntry activeTrip = activeBlockTrip.getTrip();
        if (activeBlock.getTimepointPredictions() != null && activeBlock.getTimepointPredictions().size() > 0) {
            // If multiple stoptime predictions were originally obtained,
            // pass them through as received
            List<TimepointPredictionRecord> timepointPredictions = activeBlock.getTimepointPredictions();
            for (TimepointPredictionRecord tpr : timepointPredictions) {
                StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder();
                stopTimeUpdate.setStopId(AgencyAndId.convertToString(tpr.getTimepointId()));
                stopTimeUpdate.setScheduleRelationship(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED);
                if (tpr.getTimepointPredictedArrivalTime() != -1) {
                    StopTimeEvent.Builder arrivalStopTimeEvent = StopTimeEvent.newBuilder();
                    arrivalStopTimeEvent.setTime(tpr.getTimepointPredictedArrivalTime());
                    stopTimeUpdate.setArrival(arrivalStopTimeEvent);
                }
                if (tpr.getTimepointPredictedDepartureTime() != -1) {
                    StopTimeEvent.Builder departureStopTimeEvent = StopTimeEvent.newBuilder();
                    departureStopTimeEvent.setTime(tpr.getTimepointPredictedDepartureTime());
                    stopTimeUpdate.setDeparture(departureStopTimeEvent);
                }
                tripUpdate.addStopTimeUpdate(stopTimeUpdate);
            }
        } else {
            // No matter what our active trip is, we let our current trip be the the
            // trip of our next stop
            StopTimeEntry nextStopTime = nextBlockStop.getStopTime();
            StopEntry stop = nextStopTime.getStop();
            StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder();
            stopTimeUpdate.setStopId(AgencyAndId.convertToString(stop.getId()));
            stopTimeUpdate.setStopSequence(nextStopTime.getSequence());
            stopTimeUpdate.setScheduleRelationship(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED);
            StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder();
            stopTimeEvent.setDelay((int) activeBlock.getScheduleDeviation());
            stopTimeUpdate.setDeparture(stopTimeEvent);
            tripUpdate.addStopTimeUpdate(stopTimeUpdate);
        }
        AgencyAndId routeId = activeTrip.getRouteCollection().getId();
        AgencyAndId tripId = activeTrip.getId();
        BlockInstance blockInstance = activeBlock.getBlockInstance();
        String startDate = String.format("%1$ty%1$tm%1$td", new Date(blockInstance.getServiceDate()));
        TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder();
        tripDescriptor.setRouteId(AgencyAndId.convertToString(routeId));
        tripDescriptor.setScheduleRelationship(ScheduleRelationship.SCHEDULED);
        tripDescriptor.setStartDate(startDate);
        tripDescriptor.setTripId(AgencyAndId.convertToString(tripId));
        tripUpdate.setTrip(tripDescriptor);
        AgencyAndId vehicleId = activeBlock.getVehicleId();
        VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder();
        vehicleDescriptor.setId(AgencyAndId.convertToString(vehicleId));
        tripUpdate.setVehicle(vehicleDescriptor);
        FeedEntity.Builder feedEntity = FeedEntity.newBuilder();
        feedEntity.setTripUpdate(tripUpdate);
        feedEntity.setId(vehicleDescriptor.getId());
        feedMessage.addEntity(feedEntity);
    }
    return feedMessage.build();
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) ServiceAlertLocalizedString(org.onebusaway.transit_data_federation.impl.service_alerts.ServiceAlertLocalizedString) BlockLocation(org.onebusaway.transit_data_federation.services.realtime.BlockLocation) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate) Date(java.util.Date) StopTimeEvent(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent) BlockInstance(org.onebusaway.transit_data_federation.services.blocks.BlockInstance) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord)

Example 2 with TimepointPredictionRecord

use of org.onebusaway.realtime.api.TimepointPredictionRecord in project onebusaway-application-modules by camsys.

the class GtfsRealtimeTripLibrary method applyTripUpdatesToRecord.

private void applyTripUpdatesToRecord(MonitoredResult result, BlockDescriptor blockDescriptor, List<TripUpdate> tripUpdates, VehicleLocationRecord record, String vehicleId, String bestTripId) {
    BlockInstance instance = blockDescriptor.getBlockInstance();
    BlockConfigurationEntry blockConfiguration = instance.getBlock();
    List<BlockTripEntry> blockTrips = blockConfiguration.getTrips();
    Map<String, List<TripUpdate>> tripUpdatesByTripId = MappingLibrary.mapToValueList(tripUpdates, "trip.tripId");
    long t = currentTime();
    int currentTime = (int) ((t - instance.getServiceDate()) / 1000);
    BestScheduleDeviation best = new BestScheduleDeviation();
    long lastStopScheduleTime = Long.MIN_VALUE;
    boolean singleTimepointRecord = false;
    List<TimepointPredictionRecord> timepointPredictions = new ArrayList<TimepointPredictionRecord>();
    for (BlockTripEntry blockTrip : blockTrips) {
        TripEntry trip = blockTrip.getTrip();
        AgencyAndId tripId = trip.getId();
        List<TripUpdate> updatesForTrip = tripUpdatesByTripId.get(tripId.getId());
        boolean tripUpdateHasDelay = false;
        // onBestTrip is only relevant if bestTripId is set, which indicates that the TripUpdates
        // came from the vehicleId map (as opposed to block index).
        boolean onBestTrip = bestTripId == null || tripId.getId().equals(bestTripId);
        if (updatesForTrip != null) {
            for (TripUpdate tripUpdate : updatesForTrip) {
                /**
                 * TODO: delete this code once all upstream systems have been
                 * migrated the new "delay" and "timestamp" fields.
                 */
                if (tripUpdate.hasExtension(GtfsRealtimeOneBusAway.obaTripUpdate) && onBestTrip) {
                    OneBusAwayTripUpdate obaTripUpdate = tripUpdate.getExtension(GtfsRealtimeOneBusAway.obaTripUpdate);
                    if (obaTripUpdate.hasDelay()) {
                        /**
                         * TODO: Improved logic around picking the "best" schedule deviation
                         */
                        int delay = obaTripUpdate.getDelay();
                        best.delta = 0;
                        best.isInPast = false;
                        best.scheduleDeviation = delay;
                        best.tripId = tripId;
                        tripUpdateHasDelay = true;
                    }
                    if (obaTripUpdate.hasTimestamp() && onBestTrip) {
                        best.timestamp = obaTripUpdate.getTimestamp() * 1000;
                    }
                }
                if (tripUpdate.hasDelay() && onBestTrip) {
                    /**
                     * TODO: Improved logic around picking the "best" schedule deviation
                     */
                    best.delta = 0;
                    best.isInPast = false;
                    best.scheduleDeviation = tripUpdate.getDelay();
                    best.tripId = tripId;
                    tripUpdateHasDelay = true;
                }
                if (tripUpdate.hasTimestamp() && onBestTrip) {
                    best.timestamp = tripUpdate.getTimestamp() * 1000;
                }
                for (StopTimeUpdate stopTimeUpdate : tripUpdate.getStopTimeUpdateList()) {
                    BlockStopTimeEntry blockStopTime = getBlockStopTimeForStopTimeUpdate(result, tripUpdate, stopTimeUpdate, blockTrip.getStopTimes(), instance.getServiceDate());
                    // loop through and store last stop time on trip
                    List<BlockStopTimeEntry> stopTimes = blockTrip.getStopTimes();
                    for (BlockStopTimeEntry bste : stopTimes) {
                        long scheduleTime = instance.getServiceDate() + bste.getStopTime().getArrivalTime() * 1000;
                        if (scheduleTime > lastStopScheduleTime) {
                            lastStopScheduleTime = scheduleTime;
                        }
                    }
                    if (blockStopTime == null)
                        continue;
                    StopTimeEntry stopTime = blockStopTime.getStopTime();
                    TimepointPredictionRecord tpr = new TimepointPredictionRecord();
                    tpr.setTimepointId(stopTime.getStop().getId());
                    tpr.setTripId(stopTime.getTrip().getId());
                    tpr.setTimepointScheduledTime(instance.getServiceDate() + stopTime.getArrivalTime() * 1000);
                    if (stopTimeUpdate.hasStopSequence()) {
                        tpr.setStopSequence(stopTimeUpdate.getStopSequence());
                    }
                    int currentArrivalTime = computeArrivalTime(stopTime, stopTimeUpdate, instance.getServiceDate());
                    int currentDepartureTime = computeDepartureTime(stopTime, stopTimeUpdate, instance.getServiceDate());
                    if (currentArrivalTime >= 0) {
                        if (onBestTrip) {
                            updateBestScheduleDeviation(currentTime, stopTime.getArrivalTime(), currentArrivalTime, best, tripId, vehicleId);
                        }
                        long timepointPredictedTime = instance.getServiceDate() + (currentArrivalTime * 1000L);
                        tpr.setTimepointPredictedArrivalTime(timepointPredictedTime);
                    }
                    if (currentDepartureTime >= 0) {
                        if (onBestTrip) {
                            updateBestScheduleDeviation(currentTime, stopTime.getDepartureTime(), currentDepartureTime, best, tripId, vehicleId);
                        }
                        long timepointPredictedTime = instance.getServiceDate() + (currentDepartureTime * 1000L);
                        tpr.setTimepointPredictedDepartureTime(timepointPredictedTime);
                    }
                    if (tpr.getTimepointPredictedArrivalTime() != -1 || tpr.getTimepointPredictedDepartureTime() != -1) {
                        timepointPredictions.add(tpr);
                    }
                }
            }
        }
        if (timepointPredictions.size() == 1 && tripUpdates.get(0).getStopTimeUpdateList().size() == 1) {
            singleTimepointRecord = true;
        }
        // tripUpdateHasDelay = true => best.scheduleDeviation is TripUpdate delay
        if ((timepointPredictions.size() > 0 && tripUpdateHasDelay) || singleTimepointRecord) {
            Set<AgencyAndId> records = new HashSet<AgencyAndId>();
            for (TimepointPredictionRecord tpr : timepointPredictions) {
                records.add(tpr.getTimepointId());
            }
            long tprStartTime = getEarliestTimeInRecords(timepointPredictions);
            for (StopTimeEntry stopTime : trip.getStopTimes()) {
                if (records.contains(stopTime.getStop().getId())) {
                    continue;
                }
                long predictionOffset = instance.getServiceDate() + (best.scheduleDeviation * 1000L);
                long predictedDepartureTime = (stopTime.getDepartureTime() * 1000L) + predictionOffset;
                long predictedArrivalTime = (stopTime.getArrivalTime() * 1000L) + predictionOffset;
                long scheduledArrivalTime = instance.getServiceDate() + stopTime.getArrivalTime() * 1000;
                long time = best.timestamp != 0 ? best.timestamp : currentTime();
                /*
             * if the timpepointrecord needs interpolated (one before, one after),
             * OR
             * we have a single Timepoint record and the arrival is
              * in the future and before the last stop
             */
                if ((predictedDepartureTime > time && predictedDepartureTime < tprStartTime) || (singleTimepointRecord && (predictedDepartureTime > time && scheduledArrivalTime <= lastStopScheduleTime))) {
                    TimepointPredictionRecord tpr = new TimepointPredictionRecord();
                    tpr.setTimepointId(stopTime.getStop().getId());
                    tpr.setTripId(stopTime.getTrip().getId());
                    tpr.setStopSequence(stopTime.getGtfsSequence());
                    tpr.setTimepointPredictedArrivalTime(predictedArrivalTime);
                    tpr.setTimepointPredictedDepartureTime(predictedDepartureTime);
                    tpr.setTimepointScheduledTime(scheduledArrivalTime);
                    timepointPredictions.add(tpr);
                }
            }
        }
    }
    record.setServiceDate(instance.getServiceDate());
    if (blockDescriptor.getStartTime() != null) {
        record.setBlockStartTime(blockDescriptor.getStartTime());
    }
    record.setScheduleDeviation(best.scheduleDeviation);
    if (best.timestamp != 0) {
        record.setTimeOfRecord(best.timestamp);
    }
    record.setTimepointPredictions(timepointPredictions);
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) BlockTripEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockTripEntry) ArrayList(java.util.ArrayList) StopTimeEntry(org.onebusaway.transit_data_federation.services.transit_graph.StopTimeEntry) BlockStopTimeEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate) List(java.util.List) ArrayList(java.util.ArrayList) BlockConfigurationEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry) BlockStopTimeEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry) HashSet(java.util.HashSet) TripUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate) OneBusAwayTripUpdate(com.google.transit.realtime.GtfsRealtimeOneBusAway.OneBusAwayTripUpdate) TripEntry(org.onebusaway.transit_data_federation.services.transit_graph.TripEntry) BlockTripEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockTripEntry) CoordinatePoint(org.onebusaway.geospatial.model.CoordinatePoint) BlockInstance(org.onebusaway.transit_data_federation.services.blocks.BlockInstance) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) OneBusAwayTripUpdate(com.google.transit.realtime.GtfsRealtimeOneBusAway.OneBusAwayTripUpdate)

Example 3 with TimepointPredictionRecord

use of org.onebusaway.realtime.api.TimepointPredictionRecord in project onebusaway-application-modules by camsys.

the class TrivialPredictionHelperService method getPredictionRecordsForTrip.

@Override
public List<TimepointPredictionRecord> getPredictionRecordsForTrip(String agencyId, TripStatusBean tripStatus) {
    List<TimepointPredictionRecord> records = null;
    if (agencyId == null)
        return records;
    if (tripStatus == null)
        return records;
    if (!tripStatus.isPredicted())
        return records;
    records = new ArrayList<TimepointPredictionRecord>();
    List<TimepointPredictionBean> beans = tripStatus.getTimepointPredictions();
    if (beans != null && beans.size() > 0) {
        for (TimepointPredictionBean bean : beans) {
            TimepointPredictionRecord tpr = new TimepointPredictionRecord();
            tpr.setTimepointId(AgencyAndIdLibrary.convertFromString(bean.getTimepointId()));
            tpr.setTimepointScheduledTime(bean.getTimepointScheduledTime());
            tpr.setTimepointPredictedArrivalTime(bean.getTimepointPredictedArrivalTime());
            tpr.setTimepointPredictedDepartureTime(bean.getTimepointPredictedDepartureTime());
            tpr.setStopSequence(bean.getStopSequence());
            tpr.setTripId(AgencyAndIdLibrary.convertFromString(bean.getTripId()));
            records.add(tpr);
        }
        return records;
    }
    TimepointPredictionRecord tpr = new TimepointPredictionRecord();
    tpr.setTimepointId(AgencyAndIdLibrary.convertFromString(tripStatus.getNextStop().getId()));
    tpr.setTimepointScheduledTime(tripStatus.getLastUpdateTime() + tripStatus.getNextStopTimeOffset() * 1000);
    tpr.setTimepointPredictedArrivalTime((long) (tpr.getTimepointScheduledTime() + tripStatus.getScheduleDeviation()));
    tpr.setTimepointPredictedDepartureTime((long) (tpr.getTimepointScheduledTime() + tripStatus.getScheduleDeviation()));
    records.add(tpr);
    return records;
}
Also used : TimepointPredictionBean(org.onebusaway.transit_data.model.trips.TimepointPredictionBean) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord)

Example 4 with TimepointPredictionRecord

use of org.onebusaway.realtime.api.TimepointPredictionRecord in project onebusaway-application-modules by camsys.

the class RealtimeServiceV2Impl method getVehicleActivityForVehicle.

@Override
public VehicleActivityStructure getVehicleActivityForVehicle(String vehicleId, int maximumOnwardCalls, DetailLevel detailLevel, long currentTime) {
    TripForVehicleQueryBean query = new TripForVehicleQueryBean();
    query.setTime(new Date(currentTime));
    query.setVehicleId(vehicleId);
    TripDetailsInclusionBean inclusion = new TripDetailsInclusionBean();
    inclusion.setIncludeTripStatus(true);
    inclusion.setIncludeTripBean(true);
    query.setInclusion(inclusion);
    TripDetailsBean tripDetailsForCurrentTrip = _transitDataService.getTripDetailsForVehicleAndTime(query);
    if (tripDetailsForCurrentTrip != null) {
        if (!_presentationService.include(tripDetailsForCurrentTrip.getStatus()))
            return null;
        VehicleActivityStructure output = new VehicleActivityStructure();
        output.setRecordedAtTime(DateUtil.toXmlGregorianCalendar(tripDetailsForCurrentTrip.getStatus().getLastUpdateTime()));
        List<TimepointPredictionRecord> timePredictionRecords = null;
        timePredictionRecords = _transitDataService.getPredictionRecordsForTrip(AgencyAndId.convertFromString(vehicleId).getAgencyId(), tripDetailsForCurrentTrip.getStatus());
        output.setMonitoredVehicleJourney(new MonitoredVehicleJourney());
        SiriSupportV2.fillMonitoredVehicleJourney(output.getMonitoredVehicleJourney(), tripDetailsForCurrentTrip.getTrip(), tripDetailsForCurrentTrip.getStatus(), null, OnwardCallsMode.VEHICLE_MONITORING, _presentationService, _transitDataService, maximumOnwardCalls, timePredictionRecords, tripDetailsForCurrentTrip.getStatus().isPredicted(), detailLevel, currentTime, null);
        return output;
    }
    return null;
}
Also used : TripForVehicleQueryBean(org.onebusaway.transit_data.model.trips.TripForVehicleQueryBean) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) TripDetailsInclusionBean(org.onebusaway.transit_data.model.trips.TripDetailsInclusionBean) VehicleActivityStructure(uk.org.siri.siri_2.VehicleActivityStructure) Date(java.util.Date) TripDetailsBean(org.onebusaway.transit_data.model.trips.TripDetailsBean) MonitoredVehicleJourney(uk.org.siri.siri_2.VehicleActivityStructure.MonitoredVehicleJourney)

Example 5 with TimepointPredictionRecord

use of org.onebusaway.realtime.api.TimepointPredictionRecord in project onebusaway-application-modules by camsys.

the class SiriSupportV2 method fillMonitoredVehicleJourney.

/**
 * NOTE: The tripDetails bean here may not be for the trip the vehicle is
 * currently on in the case of A-D for stop!
 * @param filters
 */
public static void fillMonitoredVehicleJourney(MonitoredVehicleJourneyStructure monitoredVehicleJourney, TripBean framedJourneyTripBean, TripStatusBean currentVehicleTripStatus, StopBean monitoredCallStopBean, OnwardCallsMode onwardCallsMode, PresentationService presentationService, TransitDataService transitDataService, int maximumOnwardCalls, List<TimepointPredictionRecord> stopLevelPredictions, boolean hasRealtimeData, DetailLevel detailLevel, long responseTimestamp, Map<Filters, String> filters) {
    BlockInstanceBean blockInstance = transitDataService.getBlockInstance(currentVehicleTripStatus.getActiveTrip().getBlockId(), currentVehicleTripStatus.getServiceDate());
    List<BlockTripBean> blockTrips = blockInstance.getBlockConfiguration().getTrips();
    if (monitoredCallStopBean == null) {
        monitoredCallStopBean = currentVehicleTripStatus.getNextStop();
    }
    /**
     *******************************************
     */
    // Route ID
    LineRefStructure lineRef = new LineRefStructure();
    lineRef.setValue(framedJourneyTripBean.getRoute().getId());
    DirectionRefStructure directionRef = new DirectionRefStructure();
    directionRef.setValue(framedJourneyTripBean.getDirectionId());
    // Route Short Name
    NaturalLanguageStringStructure routeShortName = new NaturalLanguageStringStructure();
    String shortName = framedJourneyTripBean.getRoute().getShortName();
    if (!isBlank(currentVehicleTripStatus.getActiveTrip().getRouteShortName())) {
        // look for an override like an express desginator
        shortName = currentVehicleTripStatus.getActiveTrip().getRouteShortName();
    }
    if (shortName == null) {
        shortName = framedJourneyTripBean.getRoute().getId().split("_")[1];
    }
    routeShortName.setValue(shortName);
    // Agency Id
    OperatorRefStructure operatorRef = new OperatorRefStructure();
    operatorRef.setValue(AgencySupportLibrary.getAgencyForId(framedJourneyTripBean.getRoute().getId()));
    // Framed Journey
    FramedVehicleJourneyRefStructure framedJourney = new FramedVehicleJourneyRefStructure();
    DataFrameRefStructure dataFrame = new DataFrameRefStructure();
    dataFrame.setValue(String.format("%1$tY-%1$tm-%1$td", currentVehicleTripStatus.getServiceDate()));
    framedJourney.setDataFrameRef(dataFrame);
    framedJourney.setDatedVehicleJourneyRef(framedJourneyTripBean.getId());
    // Shape Id
    JourneyPatternRefStructure journeyPattern = new JourneyPatternRefStructure();
    journeyPattern.setValue(framedJourneyTripBean.getShapeId());
    // Destination
    NaturalLanguageStringStructure headsign = new NaturalLanguageStringStructure();
    headsign.setValue(framedJourneyTripBean.getTripHeadsign());
    // Vehicle Id
    VehicleRefStructure vehicleRef = new VehicleRefStructure();
    if (currentVehicleTripStatus.getVehicleId() == null) {
        String tripId = framedJourneyTripBean.getId();
        String blockId = framedJourneyTripBean.getBlockId();
        String directionId = framedJourneyTripBean.getDirectionId();
        String vehicleIdHash = Integer.toString((tripId + blockId + directionId).hashCode());
        String agencyName = tripId.split("_")[0];
        String vehicleId = agencyName + "_" + vehicleIdHash;
        vehicleRef.setValue(vehicleId);
    } else {
        vehicleRef.setValue(currentVehicleTripStatus.getVehicleId());
    }
    // Set Origin and Destination stops from Block trips.
    StopBean lastStop = new StopBean();
    JourneyPlaceRefStructure origin = new JourneyPlaceRefStructure();
    for (int i = 0; i < blockTrips.size(); i++) {
        BlockTripBean blockTrip = blockTrips.get(i);
        if (blockTrip.getTrip().getId().equals(framedJourneyTripBean.getId())) {
            List<BlockStopTimeBean> stops = blockTrip.getBlockStopTimes();
            origin.setValue(stops.get(0).getStopTime().getStop().getId());
            lastStop = stops.get(stops.size() - 1).getStopTime().getStop();
            break;
        }
    }
    // location
    // if vehicle is detected to be on detour, use actual lat/lon, not
    // snapped location.
    LocationStructure location = new LocationStructure();
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(6);
    if (presentationService.isOnDetour(currentVehicleTripStatus)) {
        location.setLatitude(new BigDecimal(df.format(currentVehicleTripStatus.getLastKnownLocation().getLat())));
        location.setLongitude(new BigDecimal(df.format(currentVehicleTripStatus.getLastKnownLocation().getLon())));
    } else {
        location.setLatitude(new BigDecimal(df.format(currentVehicleTripStatus.getLocation().getLat())));
        location.setLongitude(new BigDecimal(df.format(currentVehicleTripStatus.getLocation().getLon())));
    }
    // progress status
    List<String> progressStatuses = new ArrayList<String>();
    if (presentationService.isInLayover(currentVehicleTripStatus)) {
        progressStatuses.add("layover");
    }
    // "prevTrip" really means not on the framedvehiclejourney trip
    if (!framedJourneyTripBean.getId().equals(currentVehicleTripStatus.getActiveTrip().getId())) {
        progressStatuses.add("prevTrip");
    }
    if (!progressStatuses.isEmpty()) {
        NaturalLanguageStringStructure progressStatus = new NaturalLanguageStringStructure();
        progressStatus.setValue(StringUtils.join(progressStatuses, ","));
        monitoredVehicleJourney.getProgressStatus().add(progressStatus);
    }
    // scheduled depature time
    if (presentationService.isBlockLevelInference(currentVehicleTripStatus) && (presentationService.isInLayover(currentVehicleTripStatus) || !framedJourneyTripBean.getId().equals(currentVehicleTripStatus.getActiveTrip().getId()))) {
        BlockStopTimeBean originDepartureStopTime = null;
        for (int t = 0; t < blockTrips.size(); t++) {
            BlockTripBean thisTrip = blockTrips.get(t);
            BlockTripBean nextTrip = null;
            if (t + 1 < blockTrips.size()) {
                nextTrip = blockTrips.get(t + 1);
            }
            if (thisTrip.getTrip().getId().equals(currentVehicleTripStatus.getActiveTrip().getId())) {
                // just started new trip
                if (currentVehicleTripStatus.getDistanceAlongTrip() < (0.5 * currentVehicleTripStatus.getTotalDistanceAlongTrip())) {
                    originDepartureStopTime = thisTrip.getBlockStopTimes().get(0);
                // at end of previous trip
                } else {
                    if (nextTrip != null) {
                        originDepartureStopTime = nextTrip.getBlockStopTimes().get(0);
                    }
                }
                break;
            }
        }
        if (originDepartureStopTime != null) {
            long departureTime = currentVehicleTripStatus.getServiceDate() + (originDepartureStopTime.getStopTime().getDepartureTime() * 1000);
            monitoredVehicleJourney.setOriginAimedDepartureTime(DateUtil.toXmlGregorianCalendar(departureTime));
        }
    }
    Map<String, TimepointPredictionRecord> stopIdToPredictionRecordMap = new HashMap<String, TimepointPredictionRecord>();
    // (build map of stop IDs to TPRs)
    if (stopLevelPredictions != null) {
        for (TimepointPredictionRecord tpr : stopLevelPredictions) {
            stopIdToPredictionRecordMap.put(AgencyAndId.convertToString(tpr.getTimepointId()), tpr);
        }
    }
    // monitored call
    if (!presentationService.isOnDetour(currentVehicleTripStatus))
        fillMonitoredCall(monitoredVehicleJourney, blockInstance, currentVehicleTripStatus, monitoredCallStopBean, presentationService, transitDataService, stopIdToPredictionRecordMap, hasRealtimeData, detailLevel, responseTimestamp);
    // detail level - minimal
    if (detailLevel.equals(DetailLevel.MINIMUM) || detailLevel.equals(DetailLevel.BASIC) || detailLevel.equals(DetailLevel.NORMAL) || detailLevel.equals(DetailLevel.CALLS)) {
        monitoredVehicleJourney.getPublishedLineName().add(routeShortName);
        monitoredVehicleJourney.getDestinationName().add(headsign);
        monitoredVehicleJourney.setMonitored(currentVehicleTripStatus.isPredicted());
        monitoredVehicleJourney.getVehicleMode().add(toVehicleMode(currentVehicleTripStatus.getVehicleType()));
        monitoredVehicleJourney.setVehicleRef(vehicleRef);
        monitoredVehicleJourney.setBearing((float) currentVehicleTripStatus.getOrientation());
        monitoredVehicleJourney.setVehicleLocation(location);
    }
    // detail level - basic
    if (detailLevel.equals(DetailLevel.BASIC) || detailLevel.equals(DetailLevel.NORMAL) || detailLevel.equals(DetailLevel.CALLS)) {
        monitoredVehicleJourney.setFramedVehicleJourneyRef(framedJourney);
        monitoredVehicleJourney.setDirectionRef(directionRef);
        // since LineRef is fully qualified with operatorref, moving OperatorRef to normal detail
        // monitoredVehicleJourney.setOperatorRef(operatorRef);
        DestinationRefStructure dest = new DestinationRefStructure();
        dest.setValue(lastStop.getId());
        monitoredVehicleJourney.setDestinationRef(dest);
        monitoredVehicleJourney.setLineRef(lineRef);
        monitoredVehicleJourney.setProgressRate(getProgressRateForPhaseAndStatus(currentVehicleTripStatus.getStatus(), currentVehicleTripStatus.getPhase()));
    }
    // detail level - normal
    if (detailLevel.equals(DetailLevel.NORMAL) || detailLevel.equals(DetailLevel.CALLS)) {
        monitoredVehicleJourney.setOperatorRef(operatorRef);
        // block ref
        if (presentationService.isBlockLevelInference(currentVehicleTripStatus)) {
            BlockRefStructure blockRef = new BlockRefStructure();
            blockRef.setValue(framedJourneyTripBean.getBlockId());
            monitoredVehicleJourney.setBlockRef(blockRef);
        }
        monitoredVehicleJourney.setOriginRef(origin);
        monitoredVehicleJourney.setJourneyPatternRef(journeyPattern);
    }
    // onward calls
    if (detailLevel.equals(DetailLevel.CALLS)) {
        if (!presentationService.isOnDetour(currentVehicleTripStatus))
            fillOnwardCalls(monitoredVehicleJourney, blockInstance, framedJourneyTripBean, currentVehicleTripStatus, onwardCallsMode, presentationService, transitDataService, stopIdToPredictionRecordMap, maximumOnwardCalls, responseTimestamp);
    }
    // situations
    fillSituations(monitoredVehicleJourney, currentVehicleTripStatus);
    return;
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri_2.NaturalLanguageStringStructure) BlockTripBean(org.onebusaway.transit_data.model.blocks.BlockTripBean) HashMap(java.util.HashMap) DestinationRefStructure(uk.org.siri.siri_2.DestinationRefStructure) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) LocationStructure(uk.org.siri.siri_2.LocationStructure) DataFrameRefStructure(uk.org.siri.siri_2.DataFrameRefStructure) BlockStopTimeBean(org.onebusaway.transit_data.model.blocks.BlockStopTimeBean) OperatorRefStructure(uk.org.siri.siri_2.OperatorRefStructure) JourneyPlaceRefStructure(uk.org.siri.siri_2.JourneyPlaceRefStructure) FramedVehicleJourneyRefStructure(uk.org.siri.siri_2.FramedVehicleJourneyRefStructure) JourneyPatternRefStructure(uk.org.siri.siri_2.JourneyPatternRefStructure) BlockRefStructure(uk.org.siri.siri_2.BlockRefStructure) LineRefStructure(uk.org.siri.siri_2.LineRefStructure) BigDecimal(java.math.BigDecimal) BlockInstanceBean(org.onebusaway.transit_data.model.blocks.BlockInstanceBean) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) StopBean(org.onebusaway.transit_data.model.StopBean) DirectionRefStructure(uk.org.siri.siri_2.DirectionRefStructure) VehicleRefStructure(uk.org.siri.siri_2.VehicleRefStructure)

Aggregations

TimepointPredictionRecord (org.onebusaway.realtime.api.TimepointPredictionRecord)36 Test (org.junit.Test)20 ArrivalAndDepartureInstance (org.onebusaway.transit_data_federation.services.realtime.ArrivalAndDepartureInstance)17 ArrayList (java.util.ArrayList)10 Date (java.util.Date)6 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)6 BlockInstance (org.onebusaway.transit_data_federation.services.blocks.BlockInstance)6 BlockConfigurationEntry (org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry)6 StopTimeUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate)5 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)4 VehicleLocationRecord (org.onebusaway.realtime.api.VehicleLocationRecord)4 TripDetailsBean (org.onebusaway.transit_data.model.trips.TripDetailsBean)4 BlockStopTimeEntry (org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry)4 StopTimeEntry (org.onebusaway.transit_data_federation.services.transit_graph.StopTimeEntry)4 StopTimeEvent (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent)3 HashMap (java.util.HashMap)3 StopBean (org.onebusaway.transit_data.model.StopBean)3 TripBean (org.onebusaway.transit_data.model.trips.TripBean)3 TripStatusBean (org.onebusaway.transit_data.model.trips.TripStatusBean)3 BlockEntryImpl (org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl)3