package vnsim.vehicular.routePlan.cityRouting; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import vnsim.applications.trafficview.SimulatedCarInfo; import vnsim.applications.vitp.CarRunningVITP; import vnsim.core.Communicator; import vnsim.core.Engine; import vnsim.core.events.SendEvent; import vnsim.map.object.Globals; import vnsim.vehicular.generator.Mobility; import vnsim.vehicular.simulator.CarInstance; import vnsim.vehicular.simulator.NotMovingPersonality; import vnsim.vehicular.simulator.RouteSegment; import vnsim.vehicular.simulator.intersections.DirectedRoadSegment; import vnsim.vehicular.simulator.intersections.Intersection; import vnsim.vehicular.simulator.intersections.TrafficLightInfo; public class IntersectionNode extends CarRunningVITP { // time interval at which route metrics are sent to cars private static final int kRouteMetricsInterval = Globals.SECOND / 1; private static final double kTrafficLightFlow = 0.5; // cars per second private static final double kDistanceBetweenCars = 5; // meters private static final int kDefaultGreenTime = 30; // seconds private static final double kMaxAllowedSpeed = 70; // km/h private CityTrafficLight correspondingIntersection = null; // mediated costs for each segment private ArrayList correspondingSegmentsCost; // incoming cost list for each segment private ArrayList> incomingCost; // the time when the mediated costs were sent to server private ArrayList lastUpdateTime; // distance of the segments private ArrayList segmentsLength; private Server server; // from server private int crossIndex; // list of segments with their actual congestion // updated from server private ArrayList updatedCongestion; public IntersectionNode(int vehicleId, short roadIdx, short pointIdx, CityTrafficLight p, Server s) { super(vehicleId, (byte) 0, 0.0, roadIdx, pointIdx, (byte) 0, 0.0); correspondingIntersection = p; correspondingSegmentsCost = new ArrayList(); incomingCost = new ArrayList>(); lastUpdateTime = new ArrayList(); segmentsLength = new ArrayList(); for (int i = 0; i < correspondingIntersection.segments.size(); i++) { for (int j = 0; j < Globals.routePlanConstants.segmentsCost.size(); j++) { if (Globals.routePlanConstants.segmentsCost.get(j).equals( correspondingIntersection.segments.get(i))) { this.correspondingSegmentsCost .add(Globals.routePlanConstants.segmentsCost.get(j)); break; } } incomingCost.add(new HashMap()); lastUpdateTime.add(0); DirectedRoadSegment drs = correspondingIntersection.segments.get(i); segmentsLength.add(CityRouteComputingUtlis.getRoadSegmentDistance(drs)); } if (this.correspondingIntersection.segments.size() != this.correspondingSegmentsCost .size()) { System.out .println("Err: segmentsCost are not properly initialized"); System.exit(0); } server = s; crossIndex = server.addIntersectionNode(this); updatedCongestion = new ArrayList(); } public static void createIntersectionNodes(Server s) { for (int i = 0; i < Globals.map.allIntersections.size(); i++) { Intersection it = Globals.map.allIntersections.get(i); if (!(it instanceof CityTrafficLight)) { continue; } DirectedRoadSegment dr = it.segments.get(0); CarInstance car = null; car = Mobility .createNewInvisibleCar(dr.roadIndex, dr.pointIndex, 0, 0, 0.0, new NotMovingPersonality(), 0.0, Engine.lastCarID, dr.roadIndex, dr.pointIndex + 1, new RouteSegment((short) dr.roadIndex, (short) dr.pointIndex, (short) (dr.pointIndex + 1)), 5); if (car != null) { Engine.lastCarID++; System.out.println("Created invisible carReceivingMsg id=" + (Engine.lastCarID - 1) + " at road " + dr.roadIndex + " point " + dr.pointIndex); addIntersectionNode(car, (CityTrafficLight) it, s); } else { System.out.println("Err: could not create IntersectionNode"); } } } public static void addIntersectionNode(CarInstance car, CityTrafficLight pos, Server s) { if (car == null) return; synchronized (Globals.engine.cars) { IntersectionNode in; if (car.routingType == 5) { if (Globals.engine.crtTime == 0) { in = new IntersectionNode(car.ID, car.getRoadIdx(), car .getPointIdx(), pos, s); in.setTimestamp(Globals.engine.crtTime); in.setRealPos(car); Globals.engine.cars.add(in); Globals.engine.infrastructure.add(in); in.init(); } else { int poz = Globals.engine.cars.indexOf(new SimulatedCarInfo( car.ID)); if (poz == -1) { in = new IntersectionNode(car.ID, car.getRoadIdx(), car .getPointIdx(), pos, s); in.setTimestamp(Globals.engine.crtTime); in.setRealPos(car); Globals.engine.schedEvent(new SendEvent( Globals.engine.crtTime + 1, in, SimulatedCarInfo.STANDARD_MESSAGE_ID)); Globals.engine.cars.add(in); Globals.engine.infrastructure.add(in); in.init(); } else { ((SimulatedCarInfo) Globals.engine.cars.get(poz)) .setRealPos(car); } } } } } public void onReceive(byte[] bytesReceived, Serializable m, Communicator sender) { if (!isEquipped || bytesReceived == null) return; // is it a VITP packet? byte header = bytesReceived[0]; byte[] message = null; switch (header) { case Globals.PROT_NEIGHBOR_DISCOVERY: super.onReceive(bytesReceived, m, sender); break; case Globals.VITP_PROT: super.onReceive(bytesReceived, m, sender); break; case Globals.ROAD_METRICS_PROT: message = new byte[bytesReceived.length - 1]; for (int i = 0; i < message.length; i++) { message[i] = bytesReceived[i + 1]; } parseMetrics(message); break; } } // calculate the congestion from a road metric packet private void parseMetrics(byte[] metrics) { String metricsStr = new String(metrics); StringTokenizer st = new StringTokenizer(metricsStr); String type = st.nextToken(); if (type == null || !type.equals("RM")) { return; } int carID = Integer.parseInt(st.nextToken()); double avgSpeed = Double.parseDouble(st.nextToken()); int nTLCycles = Integer.parseInt(st.nextToken()); int segmentIndex = Integer.parseInt(st.nextToken()); HashMap data = incomingCost.get(segmentIndex); if (data.containsKey(carID)) { // data from this car exists return; } TrafficLightInfo tlInfo = correspondingIntersection.segments.get( segmentIndex).getNewLightInfo(); int greenTime; if (tlInfo == null) { greenTime = kDefaultGreenTime; } else { greenTime = tlInfo.greenEnd - tlInfo.greenStart; } int nTLMax = (int) Math.ceil(segmentsLength.get(segmentIndex) / (kTrafficLightFlow * greenTime * kDistanceBetweenCars)); avgSpeed = avgSpeed * (1 - (double) nTLCycles / nTLMax); double congestion; if (avgSpeed > kMaxAllowedSpeed) { congestion = 0; } else { congestion = 255 * (1 - avgSpeed / kMaxAllowedSpeed); } data.put(carID, congestion); // System.out.println("intersection received routemetrics from "+carID); } private Double mediateCosts(int segmentNo) { Double m = new Double(0); HashMap data = incomingCost.get(segmentNo); if (data.size() == 0) { return m; } Collection values = data.values(); Iterator valuesIt = values.iterator(); while (valuesIt.hasNext()) { m = m + valuesIt.next(); } m = m / data.size(); return m; } public void step(int crtTime) { if (crtTime % Globals.SECOND == 0) { sendCostsToServer(crtTime); } if (crtTime % kRouteMetricsInterval == 0) { sendCostsToCars(); } } // if traffic light is on red send the segment cost to server private void sendCostsToServer(int crtTime) { for (int i = 0; i < correspondingIntersection.segments.size(); i++) { Integer lastRed = correspondingIntersection.lastRed(i); if (!(lastUpdateTime.get(i).equals(lastRed))) { lastUpdateTime.set(i, lastRed); Double newCost = mediateCosts(i); if (newCost != 0) server.setCongestion(crossIndex, i, crtTime, newCost); correspondingSegmentsCost.get(i).setCost(newCost); // clear hashmap incomingCost.get(i).clear(); } } } private void sendCostsToCars() { String toSend = "RMR "; for (int i = 0; i < updatedCongestion.size(); i++) { toSend = toSend + "C " + updatedCongestion.get(i).toString(); } broadcastRoadPacket(toSend); } public void updateCongestions(ArrayList congestions) { updatedCongestion = congestions; } public int getSegmentsNb() { return correspondingIntersection.segments.size(); } }