Search in sources :

Example 31 with VehicleLocationRecord

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

the class BlockLocationServiceImpl method getBlockLocation.

/**
 * @param blockInstance
 * @param cacheElements
 * @param scheduledLocation
 * @param targetTime
 * @return null if the effective scheduled block location cannot be determined
 */
private BlockLocation getBlockLocation(BlockInstance blockInstance, VehicleLocationCacheElements cacheElements, ScheduledBlockLocation scheduledLocation, long targetTime) {
    BlockLocation location = new BlockLocation();
    location.setTime(targetTime);
    location.setBlockInstance(blockInstance);
    VehicleLocationCacheElement cacheElement = null;
    if (cacheElements != null)
        cacheElement = cacheElements.getElementForTimestamp(targetTime);
    if (cacheElement != null) {
        VehicleLocationRecord record = cacheElement.getRecord();
        if (scheduledLocation == null)
            scheduledLocation = getScheduledBlockLocationForVehicleLocationCacheRecord(blockInstance, cacheElement, targetTime);
        if (scheduledLocation != null) {
            location.setEffectiveScheduleTime(scheduledLocation.getScheduledTime());
            location.setDistanceAlongBlock(scheduledLocation.getDistanceAlongBlock());
        }
        location.setBlockStartTime(record.getBlockStartTime());
        location.setPredicted(true);
        location.setLastUpdateTime(record.getTimeOfRecord());
        location.setLastLocationUpdateTime(record.getTimeOfLocationUpdate());
        location.setScheduleDeviation(record.getScheduleDeviation());
        location.setScheduleDeviations(cacheElement.getScheduleDeviations());
        if (record.isCurrentLocationSet()) {
            CoordinatePoint p = new CoordinatePoint(record.getCurrentLocationLat(), record.getCurrentLocationLon());
            location.setLastKnownLocation(p);
        }
        location.setOrientation(record.getCurrentOrientation());
        location.setPhase(record.getPhase());
        location.setStatus(record.getStatus());
        location.setVehicleId(record.getVehicleId());
        List<TimepointPredictionRecord> timepointPredictions = record.getTimepointPredictions();
        location.setTimepointPredictions(timepointPredictions);
        if (timepointPredictions != null && !timepointPredictions.isEmpty()) {
            SortedMap<Integer, Double> scheduleDeviations = new TreeMap<Integer, Double>();
            BlockConfigurationEntry blockConfig = blockInstance.getBlock();
            int tprIndexCounter = 0;
            for (TimepointPredictionRecord tpr : timepointPredictions) {
                AgencyAndId stopId = tpr.getTimepointId();
                long predictedTime;
                if (tpr.getTimepointPredictedDepartureTime() != -1) {
                    predictedTime = tpr.getTimepointPredictedDepartureTime();
                } else {
                    predictedTime = tpr.getTimepointPredictedArrivalTime();
                }
                if (stopId == null || predictedTime == 0)
                    continue;
                for (BlockStopTimeEntry blockStopTime : blockConfig.getStopTimes()) {
                    StopTimeEntry stopTime = blockStopTime.getStopTime();
                    StopEntry stop = stopTime.getStop();
                    // StopSequence equals to -1 when there is no stop sequence in the GTFS-rt
                    if (stopId.equals(stop.getId()) && stopTime.getTrip().getId().equals(tpr.getTripId()) && (tpr.getStopSequence() == -1 || stopTime.getSequence() == tpr.getStopSequence())) {
                        if (tpr.getStopSequence() == -1 && isFirstOrLastStopInTrip(stopTime) && isLoopRoute(stopTime)) {
                            if (isSinglePredictionForTrip(timepointPredictions, tpr, tprIndexCounter)) {
                                continue;
                            }
                            // If this isn't the last prediction, and we're on the first stop, then apply it
                            if (isLastPrediction(stopTime, timepointPredictions, tpr, tprIndexCounter) && isFirstStopInRoute(stopTime)) {
                                // Do not calculate schedule deviation
                                continue;
                            }
                            // If this is the last prediction, and we're on the last stop, then apply it
                            if (isFirstPrediction(stopTime, timepointPredictions, tpr, tprIndexCounter) && isLastStopInRoute(stopTime)) {
                                // Do not calculate schedule deviation
                                continue;
                            }
                        }
                        int arrivalOrDepartureTime;
                        // We currently use the scheduled arrival time of the stop as the search index
                        // This MUST be consistent with the index search in ArrivalAndSepartureServiceImpl.getBestScheduleDeviation()
                        int index = stopTime.getArrivalTime();
                        if (tpr.getTimepointPredictedDepartureTime() != -1) {
                            // Prefer departure time, because if both exist departure deviations should be the ones propagated downstream
                            arrivalOrDepartureTime = stopTime.getDepartureTime();
                        } else {
                            arrivalOrDepartureTime = stopTime.getArrivalTime();
                        }
                        int deviation = (int) ((predictedTime - blockInstance.getServiceDate()) / 1000 - arrivalOrDepartureTime);
                        scheduleDeviations.put(index, (double) deviation);
                    }
                }
                tprIndexCounter++;
            }
            double[] scheduleTimes = new double[scheduleDeviations.size()];
            double[] scheduleDeviationMus = new double[scheduleDeviations.size()];
            double[] scheduleDeviationSigmas = new double[scheduleDeviations.size()];
            int index = 0;
            for (Map.Entry<Integer, Double> entry : scheduleDeviations.entrySet()) {
                scheduleTimes[index] = entry.getKey();
                scheduleDeviationMus[index] = entry.getValue();
                index++;
            }
            ScheduleDeviationSamples samples = new ScheduleDeviationSamples(scheduleTimes, scheduleDeviationMus, scheduleDeviationSigmas);
            location.setScheduleDeviations(samples);
        }
    } else {
        if (scheduledLocation == null)
            scheduledLocation = getScheduledBlockLocationForBlockInstance(blockInstance, targetTime);
    }
    /**
     * Will be null in the following cases:
     *
     * 1) When the effective schedule time is beyond the last scheduled stop
     * time for the block.
     *
     * 2) When the effective distance along block is outside the range of the
     * block's shape.
     */
    if (scheduledLocation == null)
        return null;
    // if we have route info, set the vehicleType
    if (scheduledLocation.getActiveTrip() != null && scheduledLocation.getActiveTrip().getTrip() != null && scheduledLocation.getActiveTrip().getTrip().getRoute() != null) {
        location.setVehicleType(EVehicleType.toEnum(scheduledLocation.getActiveTrip().getTrip().getRoute().getType()));
    }
    location.setInService(scheduledLocation.isInService());
    location.setActiveTrip(scheduledLocation.getActiveTrip());
    location.setLocation(scheduledLocation.getLocation());
    location.setOrientation(scheduledLocation.getOrientation());
    location.setScheduledDistanceAlongBlock(scheduledLocation.getDistanceAlongBlock());
    location.setClosestStop(scheduledLocation.getClosestStop());
    location.setClosestStopTimeOffset(scheduledLocation.getClosestStopTimeOffset());
    location.setNextStop(scheduledLocation.getNextStop());
    location.setNextStopTimeOffset(scheduledLocation.getNextStopTimeOffset());
    location.setPreviousStop(scheduledLocation.getPreviousStop());
    return location;
}
Also used : CoordinatePoint(org.onebusaway.geospatial.model.CoordinatePoint) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) VehicleLocationCacheElement(org.onebusaway.transit_data_federation.services.realtime.VehicleLocationCacheElement) ScheduledBlockLocation(org.onebusaway.transit_data_federation.services.blocks.ScheduledBlockLocation) BlockLocation(org.onebusaway.transit_data_federation.services.realtime.BlockLocation) TreeMap(java.util.TreeMap) CoordinatePoint(org.onebusaway.geospatial.model.CoordinatePoint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StopTimeEntry(org.onebusaway.transit_data_federation.services.transit_graph.StopTimeEntry) BlockStopTimeEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry) ScheduleDeviationSamples(org.onebusaway.transit_data_federation.services.realtime.ScheduleDeviationSamples) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) StopEntry(org.onebusaway.transit_data_federation.services.transit_graph.StopEntry) BlockConfigurationEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry) Map(java.util.Map) FactoryMap(org.onebusaway.collections.FactoryMap) SortedMap(java.util.SortedMap) TreeMap(java.util.TreeMap) BlockStopTimeEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry)

Example 32 with VehicleLocationRecord

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

the class SiriLikeRealtimeSource method parse.

public VehicleLocationRecord parse(Node node, long timestamp) throws Exception {
    String tripId = (String) tripIdExpression.evaluate(node, XPathConstants.STRING);
    if (tripId == null) {
        _log.error("no trip for node=" + node);
        return null;
    }
    if (timestamp == 0) {
        timestamp = SystemTime.currentTimeMillis();
    }
    String serviceDateStr = (String) serviceDateExpression.evaluate(node, XPathConstants.STRING);
    Date serviceDate = parseServiceDate(serviceDateStr);
    VehicleLocationRecord vlr = new VehicleLocationRecord();
    try {
        vlr.setTimeOfLocationUpdate(timestamp);
        vlr.setTimeOfRecord(timestamp);
        vlr.setTripId(new AgencyAndId(getAgency(), tripId));
        vlr.setServiceDate(serviceDate.getTime());
        vlr.setVehicleId(new AgencyAndId(getAgency(), (String) vehicleIdExpression.evaluate(node, XPathConstants.STRING)));
        vlr.setCurrentLocationLat(asDouble(latExpression.evaluate(node, XPathConstants.STRING)));
        vlr.setCurrentLocationLon(asDouble(lonExpression.evaluate(node, XPathConstants.STRING)));
        Integer scheduleDeviation = calculateScheduleDeviation(vlr);
        if (scheduleDeviation != null) {
            vlr.setScheduleDeviation(scheduleDeviation);
        }
    } catch (NumberFormatException nfe) {
        _log.info("caught nfe", nfe);
        return null;
    }
    _log.debug("return vlr=" + vlr);
    return vlr;
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) Date(java.util.Date) ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate)

Example 33 with VehicleLocationRecord

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

the class SiriLikeRealtimeSource method handleUpdates.

private synchronized void handleUpdates(MonitoredResult result) throws Exception {
    int vehicles = 0;
    int trips = 0;
    for (String route : getRoutes()) {
        NodesAndTimestamp nodesAndTimestamp = parseVehicles(new URL(constructUrl(route, getApiKey(), getUrl())));
        _log.debug("found " + nodesAndTimestamp.getNodes().size() + " nodes");
        for (Node n : nodesAndTimestamp.getNodes()) {
            vehicles++;
            VehicleLocationRecord vlr = parse(n, nodesAndTimestamp.getTimestamp());
            if (vlr != null) {
                trips++;
                result.addMatchedTripId(vlr.getTripId().getId());
                try {
                    _vehicleLocationListener.handleVehicleLocationRecord(vlr);
                } catch (Exception any) {
                // bury
                }
            }
        }
    }
    _log.info("updated " + trips + " of " + vehicles + " for agency " + getAgency());
}
Also used : Node(org.w3c.dom.Node) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) CoordinatePoint(org.onebusaway.geospatial.model.CoordinatePoint) NodesAndTimestamp(org.onebusaway.transit_data_federation.impl.realtime.SiriLikeRealtimeSource.NodesAndTimestamp) URL(java.net.URL)

Example 34 with VehicleLocationRecord

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

the class VehicleStatusServiceImpl method getVehicleStatusForId.

/**
 **
 * {@link VehicleStatusService} Interface
 ***
 */
@Override
public VehicleStatus getVehicleStatusForId(AgencyAndId vehicleId) {
    VehicleLocationRecord record = _vehicleRecordsById.get(vehicleId);
    if (record == null)
        return null;
    List<VehicleLocationRecord> records = new ArrayList<VehicleLocationRecord>();
    VehicleLocationCacheElements elements = _vehicleLocationRecordCache.getRecordForVehicleId(vehicleId);
    if (elements != null) {
        for (VehicleLocationCacheElement element : elements.getElements()) records.add(element.getRecord());
    }
    VehicleStatus status = new VehicleStatus();
    status.setRecord(record);
    status.setAllRecords(records);
    return status;
}
Also used : VehicleLocationCacheElements(org.onebusaway.transit_data_federation.services.realtime.VehicleLocationCacheElements) VehicleLocationCacheElement(org.onebusaway.transit_data_federation.services.realtime.VehicleLocationCacheElement) ArrayList(java.util.ArrayList) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) VehicleStatus(org.onebusaway.transit_data_federation.services.realtime.VehicleStatus)

Aggregations

VehicleLocationRecord (org.onebusaway.realtime.api.VehicleLocationRecord)34 BlockConfigurationEntry (org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry)17 BlockInstance (org.onebusaway.transit_data_federation.services.blocks.BlockInstance)16 BlockEntryImpl (org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl)15 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)11 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)10 Test (org.junit.Test)10 TripEntryImpl (org.onebusaway.transit_data_federation.impl.transit_graph.TripEntryImpl)10 Date (java.util.Date)8 StopTimeUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate)7 ScheduledBlockLocation (org.onebusaway.transit_data_federation.services.blocks.ScheduledBlockLocation)7 BlockLocation (org.onebusaway.transit_data_federation.services.realtime.BlockLocation)6 BlockStopTimeEntry (org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry)6 ArrayList (java.util.ArrayList)5 CoordinatePoint (org.onebusaway.geospatial.model.CoordinatePoint)5 ScheduledBlockLocationServiceImpl (org.onebusaway.transit_data_federation.impl.blocks.ScheduledBlockLocationServiceImpl)5 VehicleLocationRecordCacheImpl (org.onebusaway.transit_data_federation.impl.realtime.VehicleLocationRecordCacheImpl)5 StopTimeInstance (org.onebusaway.transit_data_federation.model.StopTimeInstance)5 TargetTime (org.onebusaway.transit_data_federation.model.TargetTime)5 ArrivalAndDepartureInstance (org.onebusaway.transit_data_federation.services.realtime.ArrivalAndDepartureInstance)5