source: proiecte/ptvs/src/vnsim/core/Engine.java @ 38

Last change on this file since 38 was 38, checked in by (none), 14 years ago
File size: 66.5 KB
Line 
1package vnsim.core;
2
3
4import java.io.BufferedWriter;
5import java.io.DataInputStream;
6import java.io.DataOutputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileOutputStream;
10import java.io.FileWriter;
11import java.io.IOException;
12import java.io.PrintWriter;
13import java.util.ArrayList;
14import java.util.Collections;
15import java.util.Iterator;
16import java.util.ListIterator;
17import java.util.Random;
18
19import vnsim.applications.adaptiveTL.IntersectionCarRecord;
20import vnsim.applications.adaptiveTL.WirelessTrafficLight;
21import vnsim.applications.emissions.EmissionsTrafficLight;
22import vnsim.applications.ezcab.EzcabCar;
23import vnsim.applications.ezcab.EzcabClient;
24import vnsim.applications.trafficview.SimulatedCarInfo;
25import vnsim.core.events.CleanupEvent;
26import vnsim.core.events.Event;
27import vnsim.core.events.GPSEvent;
28import vnsim.core.events.ReceiveEvent;
29import vnsim.core.events.SendEvent;
30import vnsim.core.events.UnicastSendEvent;
31import vnsim.map.object.Globals;
32import vnsim.map.object.Map;
33import vnsim.map.object.PeanoKey;
34import vnsim.map.object.Point;
35import vnsim.map.object.Road;
36import vnsim.map.utils.GPSutil;
37import vnsim.network.RadioDev;
38import vnsim.network.dsrc.Application;
39import vnsim.network.dsrc.CarRunningDSRC;
40import vnsim.network.dsrc.DSRCStatisticComponent;
41import vnsim.network.dsrc.DSRCStatistics;
42import vnsim.network.dsrc.EmergencyRequest;
43import vnsim.network.dsrc.MAC80211;
44import vnsim.network.dsrc.WirelessPhy;
45import vnsim.network.propagation.Ricean;
46import vnsim.network.scft.CarRunningSCFT;
47import vnsim.vehicular.emissions.EmissionsResults;
48import vnsim.vehicular.generator.EntryFlowVariation;
49import vnsim.vehicular.generator.Mobility;
50import vnsim.vehicular.generator.NewCarEvent;
51import vnsim.vehicular.routePlan.RoutingConstants;
52import vnsim.vehicular.routePlan.cityRouting.CarToIntersectionComm;
53import vnsim.vehicular.routePlan.cityRouting.CityTrafficLight;
54import vnsim.vehicular.routePlan.cityRouting.IntersectionNode;
55import vnsim.vehicular.routePlan.cityRouting.RoadSegmentCost;
56import vnsim.vehicular.routePlan.cityRouting.Server;
57import vnsim.vehicular.routePlan.infrastructureRouted.DelayRecord;
58import vnsim.vehicular.routePlan.infrastructureRouted.GuidanceRequest;
59import vnsim.vehicular.routePlan.infrastructureRouted.InfrastructureNode;
60import vnsim.vehicular.routePlan.selfRouted.QueryGeneration;
61import vnsim.vehicular.scenarios.EntryExitScenario;
62import vnsim.vehicular.scenarios.EntryScenario;
63import vnsim.vehicular.scenarios.Route;
64import vnsim.vehicular.simulator.AggresivePersonality;
65import vnsim.vehicular.simulator.CalmPersonality;
66import vnsim.vehicular.simulator.CarInstance;
67import vnsim.vehicular.simulator.Personality;
68import vnsim.vehicular.simulator.RegularPersonality;
69import vnsim.vehicular.simulator.SortedCarVector;
70import vnsim.vehicular.simulator.intersections.Intersection;
71import vnsim.vehicular.simulator.intersections.IntersectionWithTrafficLights;
72
73
74
75/**
76 *
77 * The Engine class is the main class that controlls the simulation. It manages
78 * the list of entities (cars, trafficlights) and the list of events and passes the
79 * control to the mobility layer or communication layer when needed.
80 *
81 * @author Victor Gradinescu
82 *
83 */
84
85public class Engine {
86       
87        /* EZCab - file informations about the client */
88        public static BufferedWriter bwClient, bwCab;
89       
90        public static double WIRELESS_RANGE = 0.1;
91        public static double EXTENDED_WIRELESS_RANGE = 1.0;
92
93//      Petroaca - simulation protocol type ( 802.11 or DSRC )
94        public static int simulationProtocol=Globals.PROTOCOL_80211;
95       
96        //Petroaca - propagation type ( tworay or shadowing )
97        public static int propagationModel=Globals.TWO_RAY_GROUND;
98       
99        //Petroaca - the Ricean propagation module
100        public static Ricean riceanModule;
101       
102        DataInputStream dis = null;
103
104        public static int fps;
105
106        static ArrayList<Event> eventQueue = null;
107       
108        /**
109         * Mihaela Teler
110         * de fiecare data cand vreau sa fac o adaugare in eventQueue, intai verific punctul de unde vine evenimentul si astfel asignez
111         * un thread pt procesarea ulterioara a acelui eveniment(cand va fi scos din coada..)
112         * folosesc un singur eventQueue dar modific clasa Event sa contina si o referinta la un Thread
113         */
114       
115
116        //Petroaca - the DSRC emergency channel
117        ArrayList<Event> eventQueueEmergency = null;
118       
119        public boolean pauseFlag = true;
120
121        static boolean doneFlag = false;
122
123        boolean doneFlagEmergency=false;
124
125        public static ArrayList<SimulatedCarInfo> cars = null;
126
127        public static int crtTime = 0;
128
129        public long t0 = 0L;
130
131        public boolean withGUI, startedWithGUI;
132
133        boolean runtimeMobility;
134
135        public static boolean disableComm = false;
136
137        File fText = null, fBin = null;
138
139        PrintWriter pwText = null;
140
141        DataOutputStream outBin = null;
142
143        long prevRealSec = 0;
144        double lastSimSecond = 0.0;
145       
146        int eventsTime = 0, mobilityTime = 0;//, netTime = 0, codeTime = 0;
147
148        static int cleanupTime = 0;
149        static int netTime = 0;
150        static int codeTime = 0;
151        static int schedTime = 0;
152
153        int moveTime = 0;
154
155        static int semTime = 0;
156
157        public double maxControlDelay = 0;
158       
159        public int mycnt = 0;
160        public long fincars;
161        public long crossedCars;
162        public double totalkm, totalControlDelay;
163        public EmissionsResults totalEM = new EmissionsResults();
164        private long totalTime;
165       
166        public static int created = 0;
167
168        // Routing
169        public static int simulationType = 0;
170        public static int applicationType = 0;
171        int jammed;
172
173        public ArrayList<SimulatedCarInfo> infrastructure = null;
174       
175        Object event;
176
177        //City Routing
178        private Server server= new Server(); 
179       
180        /**
181         *
182         *
183         * @param withGUI If the simulator is run at the same time with GUI, the code
184         * will have to be synchronized
185         * @param runtimeMobility
186         */
187        public Engine(boolean withGUI, boolean runtimeMobility) 
188        {
189                try {
190                        FileWriter fwClient = new FileWriter("client_request.txt");
191                        bwClient = new BufferedWriter(fwClient);
192                        FileWriter fwCab        = new FileWriter("client_answers.txt");
193                        bwCab    = new BufferedWriter(fwCab); 
194                } catch (IOException e1) {
195                        e1.printStackTrace();
196                }
197                this.withGUI = withGUI;
198                this.startedWithGUI = withGUI;
199                this.runtimeMobility = runtimeMobility;
200                // init();
201                prevRealSec = t0 = System.currentTimeMillis();
202       
203        }
204
205        /*
206         * Load the map, initialize eventqueue, init
207         */
208        public void init() {
209
210                Map map = Globals.map;
211               
212                //System.out.println("roads.size: "+map.roads.size()+" : "+map.roads.get(0).getName());
213               
214                //Road road = (Road)map.roads.get(0);
215               
216                //System.out.println("road.points: "+road.points);
217               
218                //System.out.println("strada:"+road.getName()+":"+" road.crosses.size(): "+road.crosses.size());
219               
220                       
221                ArrayList<Intersection> intersectii = map.allIntersections;
222                for(int q=0;q<intersectii.size();q++){
223                        System.out.println("intersectia "+q+": "+" nume: "+intersectii.get(q).toString()+" "+intersectii.get(q).getMapPoint());
224                }
225               
226                System.out.println(".........................aici4.........");
227               
228                //***************************************************************
229               
230                if (map.roads.get(0).getName().startsWith("Iuliu") || map.roads.get(0).getName().startsWith("Dr"))
231                {
232                       
233                        Globals.monitorWTL = (WirelessTrafficLight)map.allIntersections.get(1);
234                }
235                pauseFlag = false;
236                doneFlag = false;
237
238                // the positions of the cars may be updated by a mobility module by
239                // recomputing positions at each step or can be updated by reading a
240                // traces file
241                if (!runtimeMobility) 
242                {
243                        try 
244                        {
245                                if (dis != null) {
246                                        dis.close();
247                                }
248                                dis = new DataInputStream(new FileInputStream(Globals.inFile));
249                        } 
250                        catch (IOException e) 
251                        {
252                                System.err.println("Error reading scenario; file error"
253                                                + Globals.inFile);
254                                e.printStackTrace();
255                                System.exit(0);
256                        }
257                        try 
258                        {
259                                fps = dis.readInt();
260                        } 
261                        catch (IOException e)
262                        {
263                                System.err.println("Error reading file " + Globals.inFile);
264                                e.printStackTrace();
265                        }
266                }
267                else 
268                {
269                        fps = Globals.executionFPS;
270
271                        Globals.WIRELESS_TRANSMISSION_FRAMES = (int) Math
272                                        .ceil((double) Globals.WIRELESS_TRANSMISSION_TIME
273                                                        / (1000 / Globals.executionFPS));
274
275                }
276
277                // init cars and events
278                eventQueue = new ArrayList<Event>();
279               
280               
281                cars = new ArrayList<SimulatedCarInfo>();
282               
283       
284
285                //Petroaca - if DSRC simulation then initialize the emergency event queue
286                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
287                        eventQueueEmergency = new ArrayList<Event>();
288               
289                crtTime = 0;
290
291                if (!runtimeMobility) {
292                        readScenarioPhase();
293                } else {
294                        // Mobility.initCarsTest(this);
295                        // Mobility.initCarsAutostrada(this);
296//                      Mobility.initCars(this);
297                }
298
299                /**
300                 * Mihaela Teler
301                 * inainte sa adaug evenimentul aflu pozitia de unde vine..
302                 */
303                synchronized (eventQueue) {
304                       
305                                // exceptie pt evenimentele GPS si Cleanup.. pe acestea le proceseaza threadul main
306                                eventQueue.add(new GPSEvent(0));
307                                                               
308                                eventQueue.add(new CleanupEvent(1));
309                               
310                                Iterator<SimulatedCarInfo> it = cars.iterator();
311                                while (it.hasNext()) 
312                                {
313                                        System.out.println("nu ai cum sa intri pe aici!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! cars este vida");
314                                        SimulatedCarInfo r = it.next();
315                                        schedEvent(new SendEvent(4, r, SimulatedCarInfo.STANDARD_MESSAGE_ID));
316                                        System.out.println("add in the queue..");
317                                }
318                               
319                                /* Szekeres A. START_MODIFY - add broadcast event for each traffic light*/
320                                for(int i=0;i<Globals.map.allIntersections.size();i++) {
321                                        Intersection sender = Globals.map.allIntersections.get(i);
322                                        if (sender instanceof EmissionsTrafficLight)
323                                        {
324                                                ((EmissionsTrafficLight)sender).init();
325                                                schedEvent(new SendEvent(4, (EmissionsTrafficLight)sender, (int)Globals.PROT_TL_FEEDBACK));
326                                        }
327                                }                       
328                                /* Szekeres A. STOP_MODIFY */
329                }
330               
331               
332                try 
333                {
334                        if (runtimeMobility && outputToFile) 
335                        {
336
337                                fText = new File(Globals.inFile + ".txt");
338                                fBin = new File(Globals.inFile);
339                                fText.createNewFile();
340                                fBin.createNewFile();
341                                pwText = new PrintWriter(new FileOutputStream(fText));
342                                outBin = new DataOutputStream(new FileOutputStream(fBin));
343
344                                pwText.println("" + Globals.FPS);
345                                outBin.writeInt(Globals.FPS);
346                        }
347                }
348                catch (IOException e) 
349                {
350                        System.err.println("Error reading scenario; file error"
351                                        + Globals.inFile);
352                        e.printStackTrace();
353                        System.exit(0);
354                }
355
356                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
357                        DelayRecord.initDelays();
358                        this.infrastructure=new ArrayList<SimulatedCarInfo>();
359                        //create a fixed node for every intersection
360                        InfrastructureNode.createInfrastructureNodes();
361                }
362
363                //Petroaca - instantiate the ricean propagation module
364                try
365                {
366                  if(Engine.propagationModel==Globals.RICEAN)
367                        Engine.riceanModule=new Ricean(Globals.RICEAN_FILE_NAME,true);
368                }
369                catch(IOException ioe){System.out.println("Ricean file io error:"+ioe.getMessage());System.exit(1);}
370               
371                System.out.println(">>> Engine initialized - "+eventQueue.size()+" events in the queue");
372                System.out.println("CARS:"+cars);
373                System.out.println("Events:"+eventQueue);
374                 
375               
376                System.out.println();
377               
378                Road r = Globals.map.roads.get(1);
379                System.out.print("road:"+r.getName());
380                System.out.println("  r.points.size():"+r.points.size());
381               
382                Point p1 = r.points.get(r.points.size()-1);
383                System.out.println(p1);
384                Point p2 = r.points.get(r.points.size()-2);
385                System.out.println(p2);
386               
387                System.out.println("distanta: " +(p1.getDistance() - p2.getDistance()));
388                System.out.println("distanta: " +GPSutil.distance(p1, p2));
389                System.out.println("__________________end init____________________________\n");
390                               
391
392        }
393
394        /**
395         * Reset simulation
396         */
397        public void reset()
398        {
399                eventQueue = new ArrayList<Event>();
400                cars = new ArrayList<SimulatedCarInfo>();
401
402                //Petroaca - if DSRC simulation also reset the emergency channel
403                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
404                        eventQueueEmergency = new ArrayList<Event>();
405               
406                crtTime = 0;
407
408        }
409       
410        /**
411         * Turn on communication by scheduling transmission events for each car.
412         *
413         */
414        public void restartCommunication() {
415                disableComm = false;
416                synchronized (eventQueue) {
417                        // eventQueue.add(new CleanupEvent(crtTime+1));
418
419                        schedEvent(new CleanupEvent(crtTime + 1));
420
421                        synchronized (cars) 
422                        {
423                                Iterator<SimulatedCarInfo> it = cars.iterator();
424                                while (it.hasNext()) {
425                                        SimulatedCarInfo r = it.next();
426                                        schedEvent(new SendEvent(crtTime + 2, r, SimulatedCarInfo.STANDARD_MESSAGE_ID));
427                                }
428                        }
429                }
430               
431//              Petroaca - if DSRC simulation also reset the emergency channel
432                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
433                        eventQueueEmergency = new ArrayList<Event>();
434        }
435
436        /**
437         * Start simulation, execute events from queue continously
438         *
439         */
440        public void play() {
441                // supposed to be in the init()
442                // between init and play() Globals.map.allIntersections is changing
443                // need to find a fix
444               
445                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
446                        CityTrafficLight.upgradeToCityTL();
447                        RoadSegmentCost.initRoadSegmentsCost();
448                        this.infrastructure=new ArrayList<SimulatedCarInfo>();
449                        //create a fixed node for every intersection
450                        IntersectionNode.createIntersectionNodes(server);
451                        server.init();
452                }
453               
454                prevRealSec = t0 = System.currentTimeMillis();
455                pauseFlag = false;
456                while (!pauseFlag && !doneFlag) {
457                        step();
458                }
459        }
460
461        /**
462         * Execute all the events for the following <seconds> s
463         *
464         */
465        public void play(int seconds) {
466                int frames = seconds * fps;
467                pauseFlag = false;
468                for (int i = 0; i < frames && !pauseFlag && !doneFlag; i++) {
469                        step();
470                }
471        }
472
473        /**
474         * Request the interruption of the continous execution of events
475         *
476         */
477        public void pause() {
478                pauseFlag = true;
479        }
480
481        /**
482         * Execute all the events for the current moment of time (virtual time)
483         *
484         */
485        double dec1(double x){
486                return (double)((int)(x * 10)) / 10;
487        }
488       
489       
490        long lastTime = -1;
491       
492        ////////////////////////////////////// step ///////////////////////////////////////////////////////////
493        /**
494         * Process the events for the current step of the simulation
495         *
496         */
497       
498        static int cnt = 0;
499       
500        public void step() {
501               
502               
503                if(Globals.SOCIALNETWORK == 1){
504                        double sec = vnsim.socialNet.GlobalNetwork.nextReconfigurationTime*Globals.SECOND;
505                }
506                       
507                if (crtTime >  3.5 * Globals.HOUR){     //nu rulez mai mult de 3 ore juma
508                        doneFlag = true;
509                        System.exit(0);
510                        return;
511                }
512                if (withGUI) {
513                        synchronized (Globals.mutex) {
514                                if (Globals.flag == 1) {
515                                        try {
516                                                Globals.mutex.wait();
517                                        } catch (Exception e) {
518                                               
519                                        }
520                                }
521                                Globals.flag = 0;
522                        }
523                }
524
525                long t1 = System.currentTimeMillis();
526                if (crtTime % Globals.SECOND == 0)
527                {
528                        lastSimSecond = (double)(t1-prevRealSec)/1000;
529                        prevRealSec = t1;
530                        if (lastSimSecond < 1)
531                                try{
532                                        Thread.sleep(100);//(int)((1.0 - lastSimSecond)*1000));
533                                }catch(Exception e){
534                                       
535                                }
536                }       
537               
538                if (crtTime % Globals.MINUTE == 0){
539
540                        Globals.packets = 0;
541                        Globals.collided = 0;
542                        Globals.lost = 0;
543                       
544                        System.out.println((crtTime / Globals.MINUTE) + " sim min;\t" +
545                                        "simulation time: "+ (System.currentTimeMillis() - t0) +"\t" +
546                                        " cars: "+cars.size() + " created " + created);
547
548                        Globals.volume = 0;
549                        Globals.demand = 0;
550                       
551                        //Petroaca
552                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
553                        {
554                                DSRCStatistics.addStatistic(new DSRCStatisticComponent(0,Globals.DSRC_PACKETS_LOST_WEAK,Globals.DSRC_PACKETS_TOTAL,Globals.DSRC_PACKETS_LOST_CORRUPTED,Globals.DSRC_PACKETS_LOST_COLLISION,Globals.DSRC_PACKETS_LOST_TX,Globals.DSRC_PACKETS_LOST_RX,Globals.DSRC_PACKETS_LOST_PER,Globals.DSRC_PACKETS_RECEIVED_OK
555                                                ,0,0,Globals.CUMMULATIVE_PACKETS_FV,Globals.CUMMULATIVE_PACKETS_NFV,Globals.CUMMULATIVE_PACKETS_LAV,Globals.CUMMULATIVE_PACKETS_RAV,Globals.IRT_FV,Globals.IRT_NFV,Globals.IRT_LAV,Globals.IRT_RAV,0,0,0,0,this.cars.size(),Globals.EMERGENCY_RECEIVED,Globals.EMERGENCY_SENT));
556                               
557                               
558                                Globals.DSRC_PACKETS_LOST_WEAK=0;
559                                Globals.DSRC_PACKETS_LOST_COLLISION=0;
560                                Globals.DSRC_PACKETS_LOST_TX=0;
561                                Globals.DSRC_PACKETS_LOST_RX=0;
562                                Globals.DSRC_PACKETS_LOST_PER=0;
563                                Globals.DSRC_PACKETS_LOST_CORRUPTED=0;
564                                Globals.DSRC_PACKETS_RECEIVED_OK=0;
565                                Globals.DSRC_PACKETS_TOTAL=0;
566                                Globals.DSRC_PACKETS_SEND_FALIURE_RX=0;
567                                Globals.DSRC_PACKETS_SEND_FALIURE_NOISE=0;
568                                Globals.DSRC_SEND=0;
569                               
570                                //System.out.println((crtTime / Globals.MINUTE)+ " min\t"+"FV:"+Globals.CUMMULATIVE_PACKETS_FV+" NFV:"+Globals.CUMMULATIVE_PACKETS_NFV+" LAV:"+Globals.CUMMULATIVE_PACKETS_LAV+" RAV:"+Globals.CUMMULATIVE_PACKETS_RAV+" EMERGENCY_RECV:"+Globals.EMERGENCY_RECEIVED+" EMERGENCY_SENT:"+Globals.EMERGENCY_SENT);
571                               
572                                Globals.CUMMULATIVE_PACKETS_RAV=0;
573                                Globals.CUMMULATIVE_PACKETS_LAV=0;
574                                Globals.CUMMULATIVE_PACKETS_FV=0;
575                                Globals.CUMMULATIVE_PACKETS_NFV=0;
576                                Globals.IRT_FV=0;
577                                Globals.IRT_NFV=0;
578                                Globals.IRT_LAV=0;
579                                Globals.IRT_RAV=0;
580                                Globals.EMERGENCY_RECEIVED=0;
581                                Globals.EMERGENCY_SENT=0;
582                               
583                                /*System.out.println("END DSRC DATA------------------------------");*/
584                        }       
585                }               
586                if (crtTime % (5 * Globals.MINUTE) == 0){
587                        if (lastTime == -1)
588                                lastTime = t0;
589                        lastTime = t1;
590
591                        eventsTime = 0;
592                        codeTime = 0;
593                        cleanupTime = 0;
594                        mobilityTime = 0;
595                       
596                        Globals.pw.flush();
597                       
598                        Globals.demo.st.clearInfo();
599                        Globals.demo.st.addInfo("Avg Delay "+ dec1(totalControlDelay/(fincars*60))+" min");
600                        Globals.demo.st.addInfo("Max Delay "+dec1(maxControlDelay / 60)+" min");
601                        Globals.demo.st.addInfo("Fuel: " + dec1( ( totalEM.fc * 100) / (1000 * totalkm)) + " L/100 km");
602                        Globals.demo.st.addInfo("CO2: " + dec1((totalEM.co2 * 20 )/ 1000)+" kg/h");
603                        Globals.demo.st.addInfo("CO: " + dec1((totalEM.co * 20 )/ 1000)+" kg/h");
604                        Globals.demo.st.addInfo("HC: " + dec1((totalEM.hc * 20 )/ 1000)+" kg/h");
605                        Globals.demo.st.addInfo("NOx: " + dec1((totalEM.nox * 20 )/ 1000)+" kg/h");
606                       
607
608                        if (fincars>0) {
609                                Globals.pwxc.println( "min " + (crtTime / Globals.MINUTE) +
610                                                "  cars: " + fincars + 
611                                                "  total time: " + totalTime +
612                                                "  total km: " + totalkm +
613                                                "  time/car: " + totalTime / fincars +
614                                                "  L/100: "+ ( (totalEM.fc * 100) / ( 1000 * totalkm)) +
615                                                "  fc: " + (totalEM.fc / fincars) +
616                                                "  co2: " + (totalEM.co2 / fincars) +
617                                                "  co: " + (totalEM.co / fincars) +
618                                                "  hc: " + (totalEM.hc / fincars) +
619                                                "  nox: " + (totalEM.nox / fincars)
620                                                );
621                                Globals.pwxc.flush();
622                        }
623                }               
624               
625               
626                if (startedWithGUI) {
627                        Globals.demo.st.setCount(crtTime);
628                        Globals.demo.st.setCurrentTime(System.currentTimeMillis() - t0);
629                        Globals.demo.st.setSimulationTime((float) ((crtTime * 1000) / fps));
630                        //Globals.demo.st.setSemTime(mycnt);
631                        Globals.demo.st.setNrEvents(eventQueue.size());
632                        Globals.demo.st.setCarsNo(cars.size());                 
633                }
634               
635                long t2 = System.currentTimeMillis();
636               
637//              Petroaca - if DSRC simualtion play the events in emergency channel as well
638               
639                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && Globals.MULTI_CHANNEL)
640                {
641                        while (true) {
642                                if (eventQueueEmergency.size() == 0) {
643                                        doneFlagEmergency = true;
644                                        break;
645                                }
646                               
647                                Event e = (Event) eventQueueEmergency.get(0);
648                                if (e.getTime() == crtTime) {
649                                        playEventEmergency();
650                                        //cnt++;
651                                } else
652                                        break;
653                        }
654                }
655               
656                /**
657                 * Mihaela Teler
658                 * vreau sa aflu cate intersectii am
659                 * voi avea tot atatea threaduri
660                 */
661                Map map = Globals.map;
662                ArrayList<Intersection> intersectii = map.allIntersections;
663                int numThreads=intersectii.size();
664               
665                EventProcessingThread processingThreads[] = new EventProcessingThread[numThreads];
666               
667               
668                while (true) {
669                       
670                        if (eventQueue.size() == 0) {
671                                doneFlag = true;
672                                return;
673                        }
674                       
675                        // extrag un eveniment din coada !!!!! acum doar il extrag.. cand intru in playEvent il si scot cu remove(0)
676                        Event e = (Event) eventQueue.get(0);
677                        System.out.println("--- no of events in the queue:"+eventQueue.size() );
678                       
679                        /**
680                         * Mihaela Teler
681                         * vector de threaduri pt procesare evenimente in functie de locatie
682                         * procesez folosind threaduri doar evenimentele send si receive
683                         */
684                       
685               
686                        if((e instanceof SendEvent) || (e instanceof ReceiveEvent)){
687                               
688                                /**
689                                 * Mihaela Teler
690                                 * aflu locatia evenimentului
691                                 */                     
692                                Road r = null;
693                                Point p = null;
694                                if(e instanceof SendEvent){
695                                        SendEvent se=(SendEvent)e;
696                                        r = (Road) Globals.map.roads.get(se.sender.getRoadIdx());       //aflu strada pe care se afla senderul
697                                        p = (Point) r.points.get(se.sender.getPointIdx());                      //aflu punctul unde se afla senderul
698                                }
699                                if(e instanceof ReceiveEvent){
700                                        ReceiveEvent re=(ReceiveEvent)e;
701                                        r = (Road) Globals.map.roads.get(re.sender.getRoadIdx());
702                                        p = (Point) r.points.get(re.sender.getPointIdx());
703                                }
704                               
705                                //System.out.println("p:"+p);
706                               
707                                /**
708                                 * Mihaela Teler
709                                 * parcurg toate intersectiile si o gasesc pe cea mai apropiata
710                                 */
711                                double MIN_DIST=Double.MAX_VALUE;
712                                int indexClosestIntersection=0;
713                                double distanta;
714                                for(int i=0;i<intersectii.size();i++){ 
715                                        Intersection intersectie = intersectii.get(i);
716                                        if(r.getPoints().contains(intersectie.getMapPoint())){ //iau in calcul doar intersectiile aflate pe strada pe care sunt
717                                                distanta=GPSutil.distance(p, intersectie.getMapPoint());
718                                                if (distanta < MIN_DIST){
719                                                        MIN_DIST=distanta;
720                                                        indexClosestIntersection=i;                                             
721                                                }
722                                        }
723                                               
724                                }
725                                /**
726                                 * Mihaela Teler
727                                 * acum trebuie sa asignez un thread sa proceseze
728                                 */
729                               
730                                if(e instanceof SendEvent){
731                                        processingThreads[indexClosestIntersection] = new SendEventProcessingThread(e,crtTime);
732                                }
733                                else processingThreads[indexClosestIntersection] = new ReceiveEventProcessingThread(e,crtTime);
734                               
735                                // nu e bine cu apelul lui run pt ca practic nu se porneste un thread nou ci
736                                // se apeleaza metoda run ca orice alta metoda dintr-o clasa, executia este secventiala..
737                               
738                                if (e.getTime() == crtTime) {
739                                        System.out.println("Processing thread "+indexClosestIntersection+" from intersection "+intersectii.get(indexClosestIntersection));
740                                        //processingThreads[indexClosestIntersection].start();// cu start nu merge ... why????
741                                        processingThreads[indexClosestIntersection].run();
742                                        cnt++;
743                                }
744                                else
745                                        break;
746                        }
747                       
748                        else if (e.getTime() == crtTime) {
749                                playEvent();
750                                cnt++;
751                        } else
752                                break;
753                       
754                       
755                }
756               
757               
758                //increment simulation time
759                crtTime++;
760               
761                long t3 = System.currentTimeMillis();
762                if (crtTime % (Globals.executionFPS / Globals.FPS) == 0)
763                        if (!runtimeMobility)
764                                readScenarioPhase();
765                        else
766                                generateScenarioPhase();
767               
768                checkCreateNewCars();
769               
770                long t4 = System.currentTimeMillis();
771                eventsTime += t3 - t2;
772                mobilityTime += t4 - t3;
773
774                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
775                        if (crtTime % 100 == 0) {
776                                for (int i = 0; i < this.infrastructure.size(); i++) {
777                                       
778                                        ((InfrastructureNode) this.infrastructure.get(i)).updateDelays();
779                                }
780                        }
781                }
782                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
783                        for (int i = 0; i < this.infrastructure.size(); i++) {
784                                ((IntersectionNode) infrastructure.get(i)).step(crtTime);
785                        }
786                        server.step(crtTime);
787                }
788        }
789        //////////////////////////////////////////////end metoda step////////////////////////////////////
790
791        static Random random = new Random();
792
793        public static int lastCarID = 0;
794
795        /**
796         * Insert new cars at the map entry points according to the scheduled flow.
797         *
798         */
799        private void checkCreateNewCars(){
800
801                int percent;
802//              should create some new cars?
803                NewCarEvent first=Mobility.events.first();
804                while(first!=null && first.timestamp==crtTime) {
805                        //create this one
806                        EntryScenario es=Mobility.entryScenarios.get(first.index);
807
808                        int roadIndexSrc=es.entry.roadIdx;
809                        int pointIndexSrc=es.entry.ptIdx;
810
811                        int ID=lastCarID;
812                        lastCarID++;
813
814                        //which exit is the car going towards?
815                        double rand;
816                        rand=(random.nextDouble())*100;
817                        int i=0;
818                        int sum=0;
819                        while(i<es.entryExits.size()) {
820                                sum+=es.entryExits.elementAt(i).percentOfFlow;
821                                if(rand<sum) {
822                                        //this is the chosen exit
823                                        break;
824                                }
825                                i++;
826                        }
827                        EntryExitScenario ees=null;
828                        if(i==es.entryExits.size()) {
829                                //last exit chosen
830                                ees=es.entryExits.lastElement();
831                        } else 
832                                ees=es.entryExits.elementAt(i);
833
834                        int roadIndexDst=ees.exit.roadIdx;
835                        int pointIndexDst=ees.exit.ptIdx;
836
837                        //which route is the car choosing?
838                        rand=(random.nextDouble())*100;
839                        i=0;
840                        sum=0;
841                        while(i<ees.percentsEachRoute.size()) {
842                                sum+=ees.percentsEachRoute.elementAt(i);
843                                if(rand<sum) {
844                                        //this is the chosen route
845                                        break;
846                                }
847                                i++;
848                        }
849                        Route r=null;
850                        if(i==ees.percentsEachRoute.size()) {
851                                //last route chosen
852                                r=ees.routes.lastElement();
853                        } else 
854                                r=ees.routes.elementAt(i);
855
856                        for(i=0;i<Globals.map.roads.get(roadIndexSrc).laneNo;i++) {
857                                //one vehicle on each lane
858
859                                Personality personality;
860                                rand=(random.nextDouble())*100;
861                                if(rand<es.percentsDriverTypes.elementAt(0)) 
862                                {
863                                        personality=new CalmPersonality();
864                                } else if(rand<es.percentsDriverTypes.elementAt(0)+es.percentsDriverTypes.elementAt(1)) {
865                                        personality=new RegularPersonality();
866                                } else {
867                                        personality=new AggresivePersonality();
868                                }
869                               
870                                CarInstance car = null;
871                                if (simulationType == RoutingConstants.INITIALLY_PROVIDED_ROUTE || simulationType == RoutingConstants.ROUTING_SCFT) {
872                                       
873                                        car = Mobility.createNewCar(roadIndexSrc,
874                                                        pointIndexSrc, 0, i + 1, 0.0, personality, /*personality.getWantedSpeed(roadIndexSrc)*/ 0.0, ID,
875                                                        roadIndexDst, pointIndexDst, r.route);
876                                       
877                                        System.out.println("Finished creating new car "+car);
878                                       
879                                        double d =0;
880                                        if(car!=null)
881                                                d = car.getDistanceToCarInFront();
882                                        if (d < 10 && d!=0) {
883                                                // closer than 5 meters --> do not create
884                                                // System.out.println("Skipping creation...");
885                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);
886                                                continue;
887                                        }
888                                }
889
890                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
891                                        System.out.println("Dynamic; we are here");
892                                        percent = random.nextInt(100);
893                                        percent = (int) Math.abs((double) percent);
894                                        if (percent <= Globals.routePlanConstants.percentBestRoute) {
895                                                percent = 1;
896                                        } else {
897                                                percent = 0;
898                                        }
899                                        car = Mobility.createNewCar(roadIndexSrc, pointIndexSrc, 0,
900                                                        i + 1, 0.0, personality, 0.0, ID, roadIndexDst,
901                                                        pointIndexDst, r.route, percent);
902                                        if (car == null) {
903                                       
904                                                continue;
905                                        }
906                                        double d = car.getDistanceToCarInFront();
907                                        if (d < 10) {
908                                                // closer than 10 meters --> do not create
909                                               
910                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);                                         
911                                                continue;
912                                        }
913
914                                }
915                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
916
917                                        car = Mobility.createNewCarCommunicatingWithInfrastucture(
918                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
919                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
920                                                        r.route);
921                                        if (car == null) {
922                                               
923                                                continue;
924                                        }
925                                        double d = car.getDistanceToCarInFront();
926                                        if (d < 10) {
927                                                // closer than 10 meters --> do not create                                             
928                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
929                                                                .remove(car.ID);
930                                               
931
932                                                continue;
933                                        }
934
935                                }
936                               
937                                //create new ezcab client (entity)
938                               
939                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
940
941                                        car = Mobility.createNewCityCarCommunicatingWithInfrastucture(
942                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
943                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
944                                                        r.route);
945                                        if (car == null) {                                     
946                                                continue;
947                                        }
948                                        double d = car.getDistanceToCarInFront();
949                                        if (d < 10) {
950                                                // closer than 10 meters --> do not create                                             
951                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
952                                                                .remove(car.ID);
953                                               
954
955                                                continue;
956                                        }
957
958                                }
959
960                                ID = lastCarID;
961                                lastCarID++;
962                                this.addCar(car);
963                        }
964                        Mobility.events.removeFirst();
965                       
966                        try {
967                                EntryFlowVariation efv=Mobility.entryFlowVariations.get(first.index);
968                               
969                                if(efv.getFirstMom()<crtTime && efv.getFirstMom()!=-1) {
970                                        int newFlow=efv.getFirstValue();
971                                        int old=first.period;
972                                        first.period=(int)((double)(3600 * Globals.SECOND) / newFlow);
973                                        System.out.print("TIME="+crtTime+"; CHANGING PERIOD FOR ENTRY="+first.index+" FROM: "+old+" TO: "+first.period);
974                                        efv.removeFirst();
975                                }
976                        } catch (Exception ex) {
977                               
978                        }
979                        if(Globals.SOCIALNETWORK == 0 )
980                                Mobility.events.addEvent(new NewCarEvent(first.timestamp
981                                                + first.period, first.index, first.period));
982                        first = Mobility.events.first();
983                }
984        }
985
986////////////////////////////////////////// playEvent ////////////////////////////////////////////////////////////////   
987
988        static long messagesSize = 0;
989        static long carInfosSize = 0;
990        /**
991         * Execute the following event in the eventQueue
992         *
993         */
994        public static void playEvent() {
995               
996                //System.out.println(">> Thread:"+Thread.currentThread().getName());
997               
998                if (eventQueue.size() == 0) {
999                        doneFlag = true;
1000                        return;
1001                }
1002
1003                Event e = null;
1004                synchronized (eventQueue) {
1005                        e = eventQueue.remove(0);
1006                }
1007                //System.out.print(e.toString()+", ");
1008                //System.out.flush();
1009                               
1010                if (e instanceof GPSEvent) {    //////////// eveniment GPS
1011                       
1012                        Iterator<SimulatedCarInfo> it = cars.iterator();
1013                        while (it.hasNext()) {
1014                                SimulatedCarInfo r = it.next();
1015                                r.update();
1016                        }
1017                        GPSEvent newEvent = new GPSEvent(crtTime + fps);
1018                        schedEvent(newEvent);
1019                }
1020                if (e instanceof CleanupEvent) {        //////////// eveniment CLEANUP
1021
1022                        long t1 = System.currentTimeMillis();
1023                        long deleted = 0;
1024                        Iterator<SimulatedCarInfo> it = cars.iterator();
1025                        while (it.hasNext()) {
1026                                SimulatedCarInfo r = it.next();
1027
1028                                Iterator<CarInfo> j = r.trafficDB.iterator();
1029                                while (j.hasNext()) {
1030                                        CarInfo neighbor = j.next();
1031                                        if ( (crtTime - neighbor.getTimestamp() > Globals.NEIGHBOR_EXPIRES && neighbor.state != 3) ||
1032                                                        (neighbor.state == 3 && crtTime - neighbor.getTimestamp() > Globals.PROMISCUOUS_NEIGHBOR_EXPIRES)){
1033                                                j.remove();
1034                                        }
1035                                }
1036                                carInfosSize += r.trafficDB.size();
1037                        }
1038                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1039                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1040                                                .get(Globals.map.lightsIndices.get(j));
1041                               
1042                                synchronized(wtl.trafficDB){
1043                                        Iterator<IntersectionCarRecord> wtlit = wtl.trafficDB.iterator();
1044                                        while (wtlit.hasNext()) {
1045                                                IntersectionCarRecord icr = wtlit.next();
1046                                                if (!icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.HOUR 
1047                                                                && icr.getCar().state != 3){
1048                                                        icr.segment.cars.remove(icr);
1049                                                        wtlit.remove();
1050                                                        deleted++;
1051                                                }
1052                                                if (icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.TRAFFICLIGHT_NEIGHBOR_EXPIRES){
1053                                                        icr.segment.cars.remove(icr);
1054                                                        wtlit.remove();
1055                                                }
1056                                        }
1057                                }
1058                        }
1059                        long t2 = System.currentTimeMillis();
1060                        cleanupTime += t2 - t1;
1061                        if (!disableComm) {
1062                                CleanupEvent newCleanupEvent = new CleanupEvent(crtTime + fps);
1063                                schedEvent(newCleanupEvent);
1064                        }
1065                        messagesSize = 0;
1066                }
1067               
1068                if (e instanceof SendEvent) {   /////////////////////////////// eveniment SEND
1069                       
1070                        /**
1071                         * cod mutat in metoda run a lui SendEventProcessingThread - intre timp m-am razgandit.. am pornit threaduri in metoda step
1072                         */
1073                       
1074                        /*SendEventProcessingThread thread=new SendEventProcessingThread(e, crtTime, disableComm, messagesSize);
1075                        synchronized (eventQueue) {
1076                                if(!thread.isAlive()) {
1077                                        thread.start();
1078                                        System.out.println(".........................thread started");
1079                                }
1080                        }*/
1081                       
1082                       
1083                        SendEvent se = (SendEvent) e;
1084                        Communicator sender = se.getSender();
1085                       
1086                        long t1 = System.currentTimeMillis();   
1087                       
1088                        // senderul e un SimulatedCarInfo
1089                       
1090                        if (se.getMessage() == null){
1091                                byte[] message = sender.prepareMessage(se.getMessageType());
1092                                se.setMessage(message);
1093                                if (se.getMessage() == null){
1094                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1095                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1096                                                if (eventPeriod != -1)
1097                                                        schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1098                                        }
1099                                        return;
1100                                }
1101                                messagesSize += message.length;
1102                                long t2 = System.currentTimeMillis();
1103                                codeTime += t2 - t1;
1104
1105                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1106                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1107                                        if (eventPeriod != -1)
1108                                                schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1109                                }
1110                        }
1111                       
1112                        //Petroaca - the DSRC impl
1113                        if(Engine.simulationProtocol==Globals.PROTOCOL_80211)
1114                        {
1115                               
1116                                if (!sender.mediumAvailable(crtTime)) {
1117                                        e.setTime(crtTime + 1);
1118                                        schedEvent(e);
1119                                       
1120                                        return;
1121                                }
1122                               
1123                                sender.getRadio().setRadioTxMode();
1124                                simulateCommunication(se);
1125                       
1126                        }
1127                        else
1128                        {
1129                                if(sender instanceof CarRunningDSRC)
1130                                {
1131                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1132                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1133                                       
1134                                        macs.refreshFrameTime(crtTime);
1135                                        phys.refreshFrameTime(crtTime);
1136                                       
1137                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1138                                        {
1139                                                phys.sendToChannel(se.getMessage(),crtTime);
1140                                                macs.setChannelState(Globals.CCA_BUSY);
1141                                                simulateCommunication(se);
1142                                        }
1143                                        else
1144                                        {
1145                                       
1146                                                e.setTime(crtTime+1);
1147                                                schedEvent(e);
1148                                               
1149                                        }
1150                                        return;
1151                                } 
1152                                else
1153                                {
1154                                        if (!sender.mediumAvailable(crtTime)) {
1155                                                e.setTime(crtTime + 1);
1156                                                schedEvent(e);
1157                                               
1158                                                return;
1159                                        }
1160                                       
1161                                        sender.getRadio().setRadioTxMode();
1162                                        simulateCommunication(se);
1163                                }
1164                        }
1165                }
1166               
1167                if (e instanceof ReceiveEvent) {        //////////////////////// eveniment RECEIVE
1168                        ReceiveEvent re = (ReceiveEvent) e;
1169
1170                                long t1 = System.currentTimeMillis();
1171                               
1172                                //Petroaca - the DSRC impl
1173                                if(Engine.simulationProtocol==Globals.PROTOCOL_80211){
1174                                        RadioDev rxradio = re.receiver.getRadio();
1175                                        ReceiveEvent goodSignal = rxradio.receive(re.signals);
1176                                        re.receiver.removeReceiveEventForTime(re.getTime());
1177                               
1178                                        if (goodSignal != null){
1179                                                        re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1180                                                }
1181                                }
1182                                else
1183                                {
1184                                        if(re.receiver instanceof CarRunningDSRC)
1185                                        {
1186                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1187                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1188                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1189                                               
1190                                                if(Globals.DIFFERENTIAL_CW)
1191                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1192                                               
1193                                                macr.refreshFrameTime(crtTime);
1194                                                phyr.refreshFrameTime(crtTime);
1195                                                appr.refreshApplication(crtTime);
1196                                               
1197                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1198                                                re.receiver.removeReceiveEventForTime(re.getTime());
1199                                               
1200                                                double sinr=phyr.getSINR();
1201                                                if(best!=null)
1202                                                {
1203                                                        macr.setChannelState(Globals.CCA_BUSY); 
1204                                                       
1205                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1206                                                        {
1207                                                                appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1208                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1209                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1210                                                        }
1211                                                }
1212                                        }
1213                                        else
1214                                        {
1215                                                RadioDev rxradio = re.receiver.getRadio();
1216                                                ReceiveEvent goodSignal = rxradio.receive(re.signals);
1217                                                re.receiver.removeReceiveEventForTime(re.getTime());
1218                                       
1219                                                if (goodSignal != null){
1220                                                                re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1221                                                        }
1222                                        }
1223                                }       
1224                               
1225                                long t2 = System.currentTimeMillis();
1226                                codeTime += t2 - t1;
1227                        }
1228        }
1229
1230
1231        public void playEventEmergency()
1232        {
1233                if (eventQueueEmergency.size() == 0) {
1234                        doneFlagEmergency = true;
1235                        return;
1236                }
1237
1238                Event e = null;
1239                synchronized (eventQueueEmergency) {
1240                        e = eventQueueEmergency.remove(0);
1241                }
1242               
1243                if (e instanceof SendEvent) {
1244                        SendEvent se = (SendEvent) e;
1245                        Communicator sender = se.getSender();
1246                       
1247                        long t1 = System.currentTimeMillis();   
1248                       
1249                       
1250                        if (se.getMessage() == null){
1251                                byte[] message = sender.prepareMessage(se.getMessageType());
1252                                se.setMessage(message);
1253                                if (se.getMessage() == null){
1254        //                              System.out.println("null message"+se.sender + " "+se.sender.getClass());
1255                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1256                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1257                                                if (eventPeriod != -1)
1258                                                        schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1259                                        }
1260                                        return;
1261                                }
1262                                messagesSize += message.length;
1263                                long t2 = System.currentTimeMillis();
1264                                codeTime += t2 - t1;
1265
1266                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1267                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1268                                        if (eventPeriod != -1)
1269                                                schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1270                                }
1271                        }
1272                       
1273                        //Petroaca - the DSRC impl
1274                                if(sender instanceof CarRunningDSRC)
1275                                {
1276                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1277                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1278                                       
1279                                        macs.refreshFrameTime(crtTime);
1280                                        phys.refreshFrameTime(crtTime);
1281                                       
1282                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1283                                        {
1284                                                phys.sendToChannel(se.getMessage(),crtTime);
1285                                                macs.setChannelState(Globals.CCA_BUSY);
1286                                                simulateCommunicationEmergency(se);
1287                                        }
1288                                        else
1289                                        {
1290                                       
1291                                                e.setTime(crtTime+1);
1292                                                schedEventEmergency(e);
1293                                               
1294                                        }
1295                                        return;
1296                                }
1297                               
1298                                if(sender instanceof CarRunningDSRC)
1299                                {
1300                                        return;
1301                                }
1302                                else
1303                                {
1304                                        return;
1305                                }
1306                        }
1307                       
1308                if (e instanceof ReceiveEvent) {
1309                        ReceiveEvent re = (ReceiveEvent) e;
1310                       
1311                        long t1 = System.currentTimeMillis();
1312                       
1313                        //Petroaca - the DSRC impl
1314                               
1315                                        if(re.receiver instanceof CarRunningDSRC)
1316                                        {
1317                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1318                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1319                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1320                                                appr.refreshApplication(crtTime);
1321                                               
1322                                                if(Globals.DIFFERENTIAL_CW)
1323                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1324                                               
1325                                                macr.refreshFrameTime(crtTime);
1326                                                phyr.refreshFrameTime(crtTime);
1327                                               
1328                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1329                                                ((SimulatedCarInfo)re.receiver).removeReceiveEventEmergencyForTime(re.getTime());
1330                                               
1331                                                double sinr=phyr.getSINR();
1332                                                if(best!=null)
1333                                                {
1334                                                        macr.setChannelState(Globals.CCA_BUSY); 
1335                                                       
1336                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1337                                                        {
1338                                                                //appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1339                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1340                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1341                                                        }
1342                                                }
1343                                        }
1344                                        long t2 = System.currentTimeMillis();
1345                                        codeTime += t2 - t1;
1346                                }       
1347        }
1348       
1349        /**
1350         * Applications may schedule dynamically communication events using this method
1351         * to insert new events in the queue.
1352         *
1353         * @param e Event to schedule
1354         */
1355        public static void schedEvent(Event e) {
1356
1357                long t1 = System.currentTimeMillis();
1358
1359                if (e instanceof ReceiveEvent) {
1360                        ReceiveEvent re = (ReceiveEvent) e;
1361                        ReceiveEvent existing = re.receiver.getReceiveEventForTime(e.getTime());
1362                        if (existing == null){
1363                                re.receiver.addReceiveEventForTime(re);
1364                        }else{
1365                                existing.signals.add(re);
1366                                return;
1367                        }
1368                }
1369               
1370                int idx = Collections.binarySearch(eventQueue, e);
1371                synchronized (eventQueue) {
1372                        if (idx >= 0) {
1373                                // advance till the end of the sequence of equal events
1374                                if (eventQueue.get(idx).equals(e))
1375                                        idx++;
1376                                eventQueue.add(idx, e);
1377                        } else {
1378                                eventQueue.add(-(idx + 1), e);
1379                        }
1380                }
1381                long t2 = System.currentTimeMillis();
1382                schedTime += t2 - t1;
1383        }
1384
1385        //Petroaca - the message scheduler for the emergency channel
1386        public void schedEventEmergency(Event e)
1387        {
1388                long t1 = System.currentTimeMillis();
1389
1390                if (e instanceof ReceiveEvent) {
1391                        ReceiveEvent re = (ReceiveEvent) e;
1392                        ReceiveEvent existing = ((SimulatedCarInfo)re.receiver).getReceiveEventEmergencyForTime(e.getTime());
1393                        if (existing == null){
1394                                ((SimulatedCarInfo)re.receiver).addReceiveEventEmergencyForTime(re);
1395                        }else{
1396                                existing.signals.add(re);
1397                                return;
1398                        }
1399                }
1400               
1401                int idx = Collections.binarySearch(eventQueueEmergency, e);
1402                synchronized (eventQueueEmergency) {
1403                        if (idx >= 0) {
1404                                // advance till the end of the sequence of equal events
1405                                if (eventQueueEmergency.get(idx).equals(e))
1406                                        idx++;
1407                                eventQueueEmergency.add(idx, e);
1408                        } else {
1409                                eventQueueEmergency.add(-(idx + 1), e);
1410                        }
1411                }
1412                long t2 = System.currentTimeMillis();
1413                schedTime += t2 - t1;
1414        }
1415       
1416        /**
1417         * Generate the receive events corresponding to one send event, for the cars
1418         * in the wireless range of the sending car.
1419         *
1420         */
1421        public static void simulateCommunication(SendEvent e) {
1422               
1423                Road r1 = null;
1424                Point p1 = null;
1425                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1426                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1427               
1428                if (e instanceof UnicastSendEvent) {
1429                        long t1 = System.currentTimeMillis();
1430                        Iterator<SimulatedCarInfo> it = cars.iterator();
1431                        ReceiveEvent re = null;
1432                        while (it.hasNext()) {
1433                                SimulatedCarInfo r = it.next();
1434                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1435                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos().getRoadIdx());
1436                                        Point p2 = (Point) r2.points.get(r.getRealPos().getPointIdx());
1437
1438                                        // MODIFIED BY CRISTI!!!
1439                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r, e.getMessage());
1440
1441                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1442                                        re.setUnicast(true);
1443
1444                                        schedEvent(re);
1445                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1446                                        } else {
1447                                                System.out.println("EROARE! DISTANCE="+ GPSutil.distance(p1, p2));
1448                                        }
1449                                        // END MODIFIED!!!
1450                                        return;
1451                                }
1452                        }
1453                       
1454                       
1455                        re.setSender(e.getSender());
1456                       
1457                        schedEvent(re);
1458
1459                        long t2 = System.currentTimeMillis();
1460                        netTime += t2 - t1;
1461
1462                } else {
1463                       
1464                        long tmp = 0;
1465                        long t3 = System.currentTimeMillis();
1466                        long t4;
1467
1468//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e.getMessage());
1469                       
1470
1471                        int cnt3 = 0;
1472                        int pkcnt = 0;
1473                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1474
1475                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1476                        PeanoKey maxpk = null;
1477                       
1478                        double wifirange;
1479                        if (e.sender instanceof WirelessTrafficLight){
1480                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1481                                wifirange = EXTENDED_WIRELESS_RANGE;
1482                        }else{
1483                                wifirange = WIRELESS_RANGE;
1484                                maxpk = pk.getMaxpk();
1485                        }
1486                       
1487                        PeanoKey pkx = null;
1488                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1489                                pkcnt++;
1490                                // long tc1 = System.currentTimeMillis();
1491                                if (pkx.compareTo(maxpk) > 0)
1492                                        break;
1493                                // long tc2 = System.currentTimeMillis();
1494                                // comp += (tc2-tc1);
1495
1496                                if (pkx.getCars() != null) {
1497                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1498                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1499                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1500                                                cnt3 += pkx.getCars().size();
1501                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1502                                                while (it.hasNext()) {
1503                                                        SimulatedCarInfo r = it.next();
1504                                                        if (e.sender instanceof SimulatedCarInfo)
1505                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1506                                                                        continue;
1507                                                        r.setLastMediumTransmition(crtTime);
1508                                                       
1509                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1510                                                        re.setSender(e.getSender());
1511                                                        schedEvent(re);
1512                                                }
1513                                        }
1514                                }
1515                        }
1516                        PeanoKey minpk = null;
1517                        if (e.sender instanceof WirelessTrafficLight)
1518                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1519                        else
1520                                minpk = pk.getMinpk();
1521                       
1522                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1523
1524                        if (pkit.hasPrevious()){
1525                                pkx = pkit.previous();
1526                        }
1527                        for (; pkit.hasPrevious(); pkx = pkit.previous()) {
1528                                pkcnt++;
1529                                // long tc1 = System.currentTimeMillis();
1530                                if (pkx.compareTo(minpk) < 0) {
1531                                        break;
1532                                }
1533                                // long tc2 = System.currentTimeMillis();
1534                                // comp += (tc2-tc1);
1535
1536                                if (pkx.getCars() != null) {
1537                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1538                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1539                                        double distance = GPSutil.distance(p1, p2);
1540                                        if (distance < 5 * wifirange) {
1541                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1542                                                cnt3 += pkx.getCars().size();
1543                                                while (it.hasNext()) {
1544                                                        SimulatedCarInfo r = it.next();
1545                                                       
1546                                                        r.setLastMediumTransmition(crtTime);
1547                                               
1548                                                        if (e.sender instanceof SimulatedCarInfo)
1549                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1550                                                                        continue;
1551                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1552                                                        re.setSender(e.getSender());
1553                                                        schedEvent(re);
1554                                                }
1555                                        }
1556                                }
1557                        }
1558                       
1559                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1560                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1561                                                .get(Globals.map.lightsIndices.get(j));
1562                                long t1sem = System.currentTimeMillis();
1563
1564                                if (GPSutil.distance(p1, wtl.getMapPoint()) < 5 * WIRELESS_RANGE) {
1565                                        wtl.setLastMediumTransmition(crtTime);
1566                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, wtl, e.getMessage(), e.getMessageObject(), e.getMessageType());
1567                                        re.setSender(e.getSender());
1568                                        schedEvent(re);
1569                                }
1570                                long t2sem = System.currentTimeMillis();
1571                                semTime += (t2sem - t1sem);
1572                        }
1573                       
1574                        t4 = System.currentTimeMillis();
1575                        tmp += t4 - t3;
1576                        netTime += tmp;
1577                }
1578        }
1579
1580        //Petroaca - the communication simulation for the emergency channel
1581        public void simulateCommunicationEmergency(SendEvent e) {
1582
1583                Road r1 = null;
1584                Point p1 = null;
1585                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1586                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1587               
1588                if (e instanceof UnicastSendEvent) {
1589                        long t1 = System.currentTimeMillis();
1590                        Iterator<SimulatedCarInfo> it = cars.iterator();
1591                        ReceiveEvent re = null;
1592                        while (it.hasNext()) {
1593                                SimulatedCarInfo r = it.next();
1594                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1595                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos()
1596                                                        .getRoadIdx());
1597                                        Point p2 = (Point) r2.points.get(r.getRealPos()
1598                                                        .getPointIdx());
1599
1600                                        // MODIFIED BY CRISTI!!!
1601                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r,
1602                                        // e.getMessage());
1603
1604                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1605                                        re.setUnicast(true);
1606
1607                                        schedEventEmergency(re);
1608                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1609                                        } else {
1610                                                System.out.println("EROARE! DISTANCE="
1611                                                                + GPSutil.distance(p1, p2));
1612                                        }
1613                                        // END MODIFIED!!!
1614                                        return;
1615                                }
1616                        }
1617                       
1618                        re.setSender(e.getSender());
1619                        schedEventEmergency(re);
1620
1621                        long t2 = System.currentTimeMillis();
1622                        netTime += t2 - t1;
1623
1624                } else {
1625                       
1626                        long tmp = 0;
1627                        long t3 = System.currentTimeMillis();
1628                        long t4;
1629
1630//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e
1631//                                      .getMessage());
1632                       
1633
1634                        int cnt3 = 0;
1635                        int pkcnt = 0;
1636                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1637
1638                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys
1639                                        .listIterator(p1.getPeanoKeyIdx());
1640                        PeanoKey maxpk = null;
1641                       
1642                        double wifirange;
1643                        if (e.sender instanceof WirelessTrafficLight){
1644                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1645                                wifirange = EXTENDED_WIRELESS_RANGE;
1646                        }else{
1647                                wifirange = WIRELESS_RANGE;
1648                                maxpk = pk.getMaxpk();
1649                        }
1650                        PeanoKey pkx = null;
1651                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1652                                pkcnt++;
1653                                // long tc1 = System.currentTimeMillis();
1654                                if (pkx.compareTo(maxpk) > 0)
1655                                        break;
1656                                // long tc2 = System.currentTimeMillis();
1657                                // comp += (tc2-tc1);
1658
1659                                if (pkx.getCars() != null) {
1660                                        Road r2 = (Road) Globals.map.roads.get(pkx
1661                                                        .getRoadIndex());
1662                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1663                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1664                                                cnt3 += pkx.getCars().size();
1665                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1666                                                                .iterator();
1667                                                while (it.hasNext()) {
1668                                                        SimulatedCarInfo r = it.next();
1669                                                        if (e.sender instanceof SimulatedCarInfo)
1670                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1671                                                                        .getVehicleId())
1672                                                                        continue;
1673                                                        r.setLastMediumTransmition(crtTime);
1674                                                       
1675                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1676                                                        re.setSender(e.getSender());
1677                                                        schedEventEmergency(re);
1678                                                }
1679                                        }
1680                                }
1681                        }
1682                        PeanoKey minpk = null;
1683                        if (e.sender instanceof WirelessTrafficLight)
1684                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1685                        else
1686                                minpk = pk.getMinpk();
1687                       
1688                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1689
1690                        if (pkit.hasPrevious()){
1691                                pkx = pkit.previous();
1692                        }
1693                        for (; pkit.hasPrevious(); pkx = pkit
1694                                        .previous()) {
1695                                pkcnt++;
1696                                // long tc1 = System.currentTimeMillis();
1697                                if (pkx.compareTo(minpk) < 0) {
1698                                        break;
1699                                }
1700                                // long tc2 = System.currentTimeMillis();
1701                                // comp += (tc2-tc1);
1702
1703                                if (pkx.getCars() != null) {
1704                                        Road r2 = (Road) Globals.map.roads.get(pkx
1705                                                        .getRoadIndex());
1706                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1707                                        double distance = GPSutil.distance(p1, p2);
1708                                        if (distance < 5 * wifirange) {
1709                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1710                                                                .iterator();
1711                                                cnt3 += pkx.getCars().size();
1712                                                while (it.hasNext()) {
1713                                                        SimulatedCarInfo r = it.next();
1714                                                        r.setLastMediumTransmition(crtTime);
1715                                               
1716                                                        if (e.sender instanceof SimulatedCarInfo)
1717                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1718                                                                        .getVehicleId())
1719                                                                        continue;
1720                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1721                                                        re.setSender(e.getSender());
1722                                                        schedEventEmergency(re);
1723                                                }
1724                                        }
1725                                }
1726                        }
1727                       
1728                        t4 = System.currentTimeMillis();
1729                        tmp += t4 - t3;
1730                        netTime += tmp;
1731                }
1732        }
1733       
1734        /**
1735         * Adds a new car to the simulation.
1736         *
1737         * @param car The object that stores the physical behaviour of the vehicle to add
1738         */
1739        public void addCar(CarInstance car) 
1740        {
1741                if (car == null)
1742                        return;
1743               
1744                car.timestamp = crtTime;
1745                created ++;
1746                synchronized (cars) 
1747                {
1748                        SimulatedCarInfo dc = null;
1749                        if (crtTime == 0) {
1750//                              dc = new SimulatedCarInfo(car.ID, car.getLane(),
1751//                                              car.getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1752//                                              car.getDirection(), car.getOffset());
1753                                /*
1754                                dc = new CarRunningVITP(car.ID, car.getLane(), car.getSpeed(),
1755                                                car.getRoadIdx(), car.getPointIdx(),
1756                                                car.getDirection(), car.getOffset());
1757                                */
1758                                //EZcab car
1759                                if (applicationType == Globals.PROT_EZCAB){
1760                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1761                                                        car.getRoadIdx(), car.getPointIdx(),
1762                                                        car.getDirection(), car.getOffset());
1763                                        System.out.println("new ezcab car created");
1764                                }
1765                                else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1766                                        dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1767                                                        car.getRoadIdx(), car.getPointIdx(),
1768                                                        car.getDirection(), car.getOffset());
1769                                else
1770                                        dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1771                                                car.getRoadIdx(), car.getPointIdx(),
1772                                                car.getDirection(), car.getOffset());
1773                               
1774                                dc.setTimestamp(crtTime);
1775                                dc.setRealPos(car);
1776                                cars.add(dc);
1777                                dc.init();
1778                        } 
1779                        else 
1780                        {
1781                                int poz = cars.indexOf(new SimulatedCarInfo(car.ID));
1782                                if (poz == -1) 
1783                                {
1784                                        /*     
1785                                        dc = new CarRunningVITP(car.ID, car.getLane(), car
1786                                                        .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1787                                                        car.getDirection(), car.getOffset());
1788                                                        */
1789                                        //Ezcab
1790                                        if (applicationType == Globals.PROT_EZCAB){
1791                                                if(System.currentTimeMillis() % 2 == 0){
1792                                                        dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1793                                                                        car.getRoadIdx(), car.getPointIdx(),
1794                                                                        car.getDirection(), car.getOffset());
1795                                                       
1796//                                                      dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1797//                                                                      car.getRoadIdx(), car.getPointIdx(),
1798//                                                                      car.getDirection(), car.getOffset());
1799                                                        //System.out.println("new client created");
1800                                                }
1801                                                else {
1802                                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1803                                                                        car.getRoadIdx(), car.getPointIdx(),
1804                                                                        car.getDirection(), car.getOffset());
1805                                                       
1806//                                                      dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1807//                                                                      car.getRoadIdx(), car.getPointIdx(),
1808//                                                                      car.getDirection(), car.getOffset());
1809                                                        //System.out.println("new ezcab car created");
1810                                                }
1811                                        }
1812                                        else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1813                                                dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1814                                                                car.getRoadIdx(), car.getPointIdx(),
1815                                                                car.getDirection(), car.getOffset());
1816                                        else
1817                                                dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1818                                                        car.getRoadIdx(), car.getPointIdx(),
1819                                                        car.getDirection(), car.getOffset());
1820//                                      dc = new SimulatedCarInfo(car.ID, car.getLane(), car
1821//                                                      .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1822//                                                      car.getDirection(), car.getOffset());
1823                                       
1824                                        dc.setTimestamp(crtTime);
1825                                        dc.setRealPos(car);
1826                                        int t = 1 + random.nextInt(fps / 2 - 5);
1827                                        schedEvent(new SendEvent(crtTime + t, dc,SimulatedCarInfo.STANDARD_MESSAGE_ID));
1828                                        cars.add(dc);
1829                                        dc.init();                                     
1830                                } 
1831                                else 
1832                                {
1833                                        ((SimulatedCarInfo) cars.get(poz)).setRealPos(car);
1834                                }
1835                        }
1836                }
1837        }
1838
1839        /*
1840         * Read a scenario phase from a traces file. Update the vehicle's position
1841         * for the current step.
1842         *
1843         */
1844        public void readScenarioPhase() {
1845                int nrCars = 0;
1846                try {
1847                        int vehId, rdIdx, ptIdx;
1848                        byte dir, lane, speed;
1849                        double offset;
1850                        nrCars = dis.readInt();
1851                        // System.out.println(nrCars+" masini");
1852
1853                        synchronized (cars) 
1854                        {
1855                                for (int i = 0; i < nrCars; i++) 
1856                                {
1857                                        vehId   = dis.readInt();
1858                                        rdIdx   = dis.readInt();
1859                                        ptIdx   = dis.readInt();
1860                                        offset  = dis.readDouble();
1861                                        dir             = (byte) dis.readInt();
1862                                        lane    = (byte) dis.readInt();
1863                                        speed   = (byte) dis.readDouble();
1864
1865                                        SimulatedCarInfo dc = null;
1866                                        if (crtTime == 0) {
1867                                                /*     
1868                                                dc = new CarRunningVITP(vehId, lane, speed,
1869                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1870                                                */
1871                                                //create ezcab car
1872                                                if (applicationType == Globals.PROT_EZCAB){
1873                                                        dc = new EzcabCar(vehId, lane, speed,
1874                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1875                                                        System.out.println("new ezcab car");
1876                                                }
1877                                                else if (simulationType == RoutingConstants.ROUTING_SCFT)
1878                                                        dc = new CarRunningSCFT(vehId, lane, speed,
1879                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1880                                                else
1881                                                        dc = new CarRunningDSRC(vehId, lane, speed,
1882                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1883                                                // dc = new SimulatedCarInfo(vehId, lane, speed,
1884                                                // (short)rdIdx, (short)ptIdx, dir, offset);
1885                                                dc.setTimestamp(crtTime);
1886                                                dc.setRealPos(new CarInstance((CarInfo) dc));
1887                                                cars.add(dc);
1888                                                dc.init();
1889                                        } else {
1890                                                int poz = cars.indexOf(new SimulatedCarInfo(vehId));
1891                                                if (poz == -1) {
1892                                                        /*     
1893                                                        dc = new CarRunningVITP(vehId, lane, speed,
1894                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1895                                                        */
1896                                                        //create new ezcab car or client
1897                                                        if (applicationType == Globals.PROT_EZCAB){
1898                                                                if(System.currentTimeMillis() % 2 == 0){
1899                                                                        dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1900                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1901//                                                                      dc = new EzcabCar(vehId, lane, speed,
1902//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1903                                                                        //System.out.println("new ezcab client created");
1904                                                                }
1905                                                                else{
1906                                                                        dc = new EzcabCar(vehId, lane, speed,
1907                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1908//                                                                      dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1909//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1910                                                                        //System.out.println("new ezcab car created");
1911                                                                }
1912                                                        }
1913                                                        else if (simulationType == RoutingConstants.ROUTING_SCFT)
1914                                                                dc = new CarRunningSCFT(vehId, lane, speed,
1915                                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1916                                                        else
1917                                                                dc = new CarRunningDSRC(vehId, lane, speed,
1918                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1919                                                        // dc = new SimulatedCarInfo(vehId, lane, speed,
1920                                                        // (short)rdIdx, (short)ptIdx, dir, offset);
1921                                                        dc.setTimestamp(crtTime);
1922                                                        dc.setRealPos(new CarInstance((CarInfo) dc));
1923                                                        cars.add(dc);
1924                                                        dc.init();
1925                                                } else {
1926                                                        CarInstance ci = ((SimulatedCarInfo) cars.get(poz))
1927                                                                        .getRealPos();
1928                                                        ci.deleteCarToPointMapping();
1929                                                        ci.setSpeed((byte) speed);
1930                                                        ci.setRoadIdx((short) rdIdx);
1931                                                        ci.setPointIdx((short) ptIdx);
1932                                                        ci.setLane(lane);
1933                                                        ci.setDirection((byte) dir);
1934                                                        ci.setOffset(offset);
1935                                                        ci.setTimestamp(crtTime);
1936                                                        ci.updateCarToPointMapping();
1937                                                }
1938                                        }
1939                                }
1940                        }
1941                } catch (Exception e) {
1942                        System.err.println("Error reading scenario file");
1943                        e.printStackTrace();
1944                }
1945        }
1946
1947        public static boolean outputToFile = false;
1948
1949        public void generateScenarioPhase() {
1950               
1951                long t1sem = System.currentTimeMillis();
1952                if (crtTime % Globals.SECOND == 0){
1953                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1954                                IntersectionWithTrafficLights iwtl = (IntersectionWithTrafficLights) Globals.map.allIntersections
1955                                .get(Globals.map.lightsIndices.get(j));
1956                                iwtl.step(crtTime);
1957                        }
1958                }
1959                long t2sem = System.currentTimeMillis();
1960                semTime += (t2sem - t1sem);
1961
1962                int NCARS = 0;
1963
1964                for (int j = 0; j < Globals.map.roads.size(); j++) {
1965
1966                        //Petroaca - random car on road to send emergency message
1967                        Random r;
1968                        int randId=0;
1969                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
1970                        {
1971                                r=new Random();
1972                                randId=r.nextInt(Globals.map.roads.get(j).carsOnThisRoad.size()+1);
1973                               
1974                        }
1975                       
1976                        SortedCarVector newVector = new SortedCarVector();
1977                        for (int k = Globals.map.roads.get(j).carsOnThisRoad.size() - 1; k >= 0; k--) {
1978                                CarInstance car = Globals.map.roads.get(j).carsOnThisRoad
1979                                                .get(k);
1980                                if (car.finished) {
1981                                       
1982                                        totalControlDelay += car.totalControlDelay;
1983                                        fincars ++;
1984                                        if (maxControlDelay < car.totalControlDelay)
1985                                                maxControlDelay = car.totalControlDelay;
1986
1987                                        synchronized (cars) {
1988                                                if (car.startMonitor) {
1989                                                        crossedCars++;
1990                                                        totalEM.addEmissionsResults(car.em, 1);
1991                                                        totalkm += car.totalDistance - car.startMonitorDistance;
1992                                                        totalTime += (crtTime - car.startTime)/Globals.SECOND;
1993                                                }
1994                                                Globals.monitoredCars.remove(car.getSimulatedCarInfo());
1995                                                car.finish();
1996                                                car.deleteCarToPointMapping();
1997                                                cars.remove(car.getSimulatedCarInfo());
1998                                        }
1999                                        continue;
2000                                }
2001                                try {
2002                                        long t1 = System.currentTimeMillis();
2003
2004                                        synchronized (cars) {
2005                                                car.deleteCarToPointMapping();
2006                                                car.move();
2007
2008                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
2009                                                        QueryGeneration.generateQueryForCar(car);
2010                                                }
2011
2012                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
2013                                                        GuidanceRequest.generateRequestToInfrastructure(car);
2014                                                }
2015                                               
2016                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
2017                                                        CarToIntersectionComm.updateMetrics(car);
2018                                                }
2019                                               
2020//                                              Petroaca - emergency messages schedule
2021                                               
2022                                                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && car.ID==randId && crtTime%50==0)
2023                                                {
2024                                                        EmergencyRequest.generateEmergencyMessage(car);
2025                                                }
2026                                               
2027                                                car.setTimestamp(crtTime);
2028                                       
2029                                               
2030                                               
2031                                                if (car.endMonitor){
2032                                                        crossedCars ++;
2033                                                        totalEM.addEmissionsResults(car.em, 1);
2034                                                        totalkm += car.totalDistance - car.startMonitorDistance;
2035        //                                              System.out.println("Fuel: " + car.em.fc / 1000 +" "+ car.totalDistance + " "+car.em.fc * 100.0/ (10000 * car.totalDistance) + " "+(car.totalDistance * 3600.0)  / (double)(car.travelTime / Globals.SECOND));
2036                                                        car.endMonitor = false;
2037                                                        car.startMonitor = false;
2038                                                }
2039
2040                                                car.updateCarToPointMapping();
2041                                                 
2042                                        }
2043
2044                                        long t2 = System.currentTimeMillis();
2045                                        moveTime += t2 - t1;
2046                                } catch (Exception ex) {
2047                                        ex.printStackTrace();
2048                                }
2049                                // if it has changed road, place it in the vector of its new
2050                                // road
2051                                if (car.getRoadIdx() != j) {
2052                                        if (car.getRoadIdx() > j)
2053                                                NCARS--; // it will be moved again when that road
2054                                                                        // will be processed
2055                                        Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
2056                                                        .addCarInstance(car);
2057                                } else {
2058                                        // it's still on the same road
2059                                        newVector.addCarInstance(Globals.map.roads.get(j).carsOnThisRoad.get(k));
2060                                }
2061                                NCARS++;
2062                        }
2063
2064                        // loop through the new vector and set the indices
2065                        for (int k = 0; k < newVector.size(); k++) {
2066                                newVector.get(k).index = k;
2067                        }
2068                        Globals.map.roads.get(j).carsOnThisRoad = newVector;
2069                }
2070       
2071               
2072                if (!outputToFile)
2073                        return;
2074                // output text
2075                try {
2076                        pwText.print(NCARS + " ");
2077                        outBin.writeInt(NCARS);
2078                        for (int j = 0; j < Globals.map.roads.size(); j++) {
2079                                for (int k = 0; k < Globals.map.roads.get(j).carsOnThisRoad
2080                                                .size(); k++) {
2081                                        CarInstance ci = Globals.map.roads.get(j).carsOnThisRoad
2082                                                        .get(k);
2083                                        pwText.print(ci.ID + " " + ci.getRoadIdx() + " "
2084                                                        + ci.getPointIdx() + " " + ci.getOffset() + " "
2085                                                        + ci.getDirection() + " " + ci.getLane() + "   ");
2086                                        outBin.writeInt(ci.ID);
2087                                        outBin.writeInt(ci.getRoadIdx());
2088                                        outBin.writeInt(ci.getPointIdx());
2089                                        outBin.writeDouble(ci.getOffset());
2090                                        outBin.writeInt(ci.getDirection());
2091                                        outBin.writeInt(ci.getLane());
2092                                        outBin.writeDouble(ci.getSpeed());
2093                                }
2094                        }
2095                        pwText.println();
2096                } catch (IOException e) {
2097                        System.err.println("Error writing traces");
2098                        e.printStackTrace();
2099                        System.exit(0);
2100                }
2101        }
2102       
2103        public int getCrtTime(){
2104                return crtTime;
2105        }
2106       
2107       
2108       
2109       
2110        public SimulatedCarInfo getCarIdx(int rdIdx, int ptIdx) 
2111        {
2112                synchronized (cars) 
2113                {
2114                        Iterator<SimulatedCarInfo> it = cars.iterator();
2115                        while (it.hasNext()) {
2116                                SimulatedCarInfo r = it.next();
2117                                if (r.getRoadIdx() == rdIdx && r.getPointIdx() == ptIdx)
2118                                        return r;
2119                        }
2120                }
2121                return null;
2122        }
2123
2124        public SimulatedCarInfo getCarIdx(int idx) 
2125        {
2126                synchronized (cars) 
2127                {
2128                        Iterator<SimulatedCarInfo> it = cars.iterator();
2129                        while (it.hasNext()) {
2130                                SimulatedCarInfo r = it.next();
2131                                if (r.vehicleId == idx)
2132                                        return r;
2133                        }
2134                }
2135                return null;
2136        }
2137
2138        public static void main(String args[]) {
2139               
2140                // Globals.map = new Map("Intersectie.RT1","Intersectie.RT2");
2141
2142                int tests = 1;
2143                for (int i = 0; i < tests; i++){
2144                        try{
2145                                switch (i){
2146                                        case 0: Globals.pw.println("Adaptive xc  = 1, variations2");
2147                                                break;
2148                                        case 1:Globals.pw.println("Adaptive xc  = 0.95, variations2");
2149                                                break;
2150                                        case 2:break;
2151                                }
2152                               
2153//                              ObjectInputStream ois=new ObjectInputStream(new FileInputStream(".\\maps\\fsc\\Apaca.fsc"));
2154//                              Scenario sc=(Scenario)ois.readObject();
2155//                              Mobility.loadScenario(sc);
2156                       
2157                                Engine e = Globals.engine = new Engine(false, true);
2158                                e.init();
2159//                                              public void run(){
2160//                                                      Globals.demo = new Display();
2161//                                                      Globals.demo.setVisible(true);
2162//                                              }
2163//                                      });
2164//                              t.start();
2165//                              e.play();
2166                                switch (i){
2167                                        case 0:
2168                                                Globals.Xc = 0.95;
2169                                                break;
2170                                        case 1:break;
2171                                        case 2:break;
2172                                }
2173                               
2174                                if (i != tests - 1){
2175                                        Globals.pw.close();
2176                                        String pwname = "rezultate"+System.currentTimeMillis()+".txt";
2177                                        Globals.pw = new PrintWriter(new FileWriter(pwname));
2178                                }
2179                        } catch (Exception ex) {
2180                                ex.printStackTrace();
2181                                System.exit(0);
2182                        }               
2183               
2184                       
2185                }
2186               
2187/*              long t1 = System.currentTimeMillis();
2188                e.play(60);
2189                long t2 = System.currentTimeMillis();
2190
2191                System.out.println("SimTime: " + (t2 - t1));
2192                System.out.println("events: " + (double) (100 * e.eventsTime)
2193                                / (t2 - t1));
2194                System.out.println("mobility: " + (double) (100 * e.mobilityTime)
2195                                / (t2 - t1));
2196                System.out.println("move: " + (double) (100 * e.moveTime) / (t2 - t1));
2197                System.out.println("code: " + (double) (100 * e.codeTime) / (t2 - t1));
2198                System.out.println("net: " + (double) (100 * e.netTime) / (t2 - t1));
2199                System.out.println("cleanup: " + (double) (100 * e.cleanupTime)
2200                                / (t2 - t1));
2201                System.out
2202                                .println("sched: " + (double) (100 * e.schedTime) / (t2 - t1));
2203
2204//              System.out.println("pkavg " + pkavg + "\npkmax" + pkmax
2205//                              + "\ncomp time " + avgTime);
2206                //              e.play();
2207                //              e.step();
2208                //              e.step();
2209                //              e.step();
2210                //              e.step();
2211                //              e.step();
2212                System.exit(0);*/
2213        }
2214
2215       
2216/*      public void createDummyCars() {
2217                Road r = Globals.map.roads.get(1);
2218               
2219                //Stopping a car on a road
2220                int ID = lastCarID;
2221                lastCarID++;
2222                CarInstance car = Mobility.createNewCar(1, 46, 0, 1, 0.0,
2223                                new NotMovingPersonality(), 0.0, ID, 2, 64, null, 1);
2224                if (car == null) {
2225                        lastCarID--;
2226                        System.out.println("Could not create the first stopped car");
2227                } else {
2228                        System.out.println("Jammed car id=" + ID);
2229                        jammed = ID;
2230                }
2231
2232                this.addCar(car);
2233        }
2234*/
2235       
2236       
2237}
Note: See TracBrowser for help on using the repository browser.