View Javadoc
1   package org.opentrafficsim.demo.trafficcontrol;
2   
3   import java.awt.BorderLayout;
4   import java.awt.Dimension;
5   import java.net.URL;
6   import java.rmi.RemoteException;
7   import java.util.HashSet;
8   import java.util.Set;
9   
10  import javax.naming.NamingException;
11  import javax.swing.JPanel;
12  import javax.swing.JScrollPane;
13  
14  import org.djunits.unit.LengthUnit;
15  import org.djunits.value.vdouble.scalar.Duration;
16  import org.djunits.value.vdouble.scalar.Length;
17  import org.djunits.value.vdouble.scalar.Time;
18  import org.djutils.io.URLResource;
19  import org.opentrafficsim.core.compatibility.Compatible;
20  import org.opentrafficsim.core.dsol.AbstractOTSModel;
21  import org.opentrafficsim.core.dsol.OTSAnimator;
22  import org.opentrafficsim.core.dsol.OTSSimulatorInterface;
23  import org.opentrafficsim.core.gtu.RelativePosition;
24  import org.opentrafficsim.core.network.NetworkException;
25  import org.opentrafficsim.core.network.OTSNetwork;
26  import org.opentrafficsim.demo.trafficcontrol.TrafCODDemo2.TrafCODModel;
27  import org.opentrafficsim.draw.core.OTSDrawingException;
28  import org.opentrafficsim.draw.road.TrafficLightAnimation;
29  import org.opentrafficsim.road.network.factory.xml.XmlNetworkLaneParser;
30  import org.opentrafficsim.road.network.lane.CrossSectionLink;
31  import org.opentrafficsim.road.network.lane.Lane;
32  import org.opentrafficsim.road.network.lane.object.sensor.TrafficLightSensor;
33  import org.opentrafficsim.road.network.lane.object.trafficlight.SimpleTrafficLight;
34  import org.opentrafficsim.road.network.lane.object.trafficlight.TrafficLight;
35  import org.opentrafficsim.swing.gui.OTSAnimationPanel;
36  import org.opentrafficsim.swing.gui.OTSSimulationApplication;
37  import org.opentrafficsim.trafficcontrol.TrafficController;
38  import org.opentrafficsim.trafficcontrol.trafcod.TrafCOD;
39  
40  import nl.tudelft.simulation.dsol.SimRuntimeException;
41  import nl.tudelft.simulation.event.EventInterface;
42  import nl.tudelft.simulation.event.EventListenerInterface;
43  import nl.tudelft.simulation.event.EventType;
44  
45  /**
46   * <p>
47   * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
48   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
49   * <p>
50   * @version $Revision$, $LastChangedDate$, by $Author$, initial version Dec 06, 2016 <br>
51   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
52   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
53   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
54   */
55  public class TrafCODDemo2 extends OTSSimulationApplication<TrafCODModel>
56  {
57      /** */
58      private static final long serialVersionUID = 20161118L;
59  
60      /**
61       * Create a TrafcodAndTurbo demo.
62       * @param title String; the title of the Frame
63       * @param panel OTSAnimationPanel; the tabbed panel to display
64       * @param model TrafCODModel; the model
65       * @throws OTSDrawingException on animation error
66       */
67      public TrafCODDemo2(final String title, final OTSAnimationPanel panel, final TrafCODModel model) throws OTSDrawingException
68      {
69          super(model, panel);
70      }
71  
72      /**
73       * Main program.
74       * @param args String[]; the command line arguments (not used)
75       */
76      public static void main(final String[] args)
77      {
78          demo(true);
79      }
80  
81      /**
82       * Start the demo.
83       * @param exitOnClose boolean; when running stand-alone: true; when running as part of a demo: false
84       */
85      public static void demo(final boolean exitOnClose)
86      {
87          try
88          {
89              OTSAnimator simulator = new OTSAnimator();
90              final TrafCODModel trafcodModel = new TrafCODModel(simulator);
91              simulator.initialize(Time.ZERO, Duration.ZERO, Duration.createSI(3600.0), trafcodModel);
92              OTSAnimationPanel animationPanel = new OTSAnimationPanel(trafcodModel.getNetwork().getExtent(),
93                      new Dimension(800, 600), simulator, trafcodModel, DEFAULT_COLORER, trafcodModel.getNetwork());
94              TrafCODDemo2 app = new TrafCODDemo2("TrafCOD demo complex crossing", animationPanel, trafcodModel);
95              app.setExitOnClose(exitOnClose);
96          }
97          catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException exception)
98          {
99              exception.printStackTrace();
100         }
101     }
102 
103     /**
104      * Add tab with trafCOD status.
105      */
106     protected void addTabs()
107     {
108         JScrollPane scrollPane = new JScrollPane(getModel().getControllerDisplayPanel());
109         JPanel wrapper = new JPanel(new BorderLayout());
110         wrapper.add(scrollPane);
111         getAnimationPanel().getTabbedPane().addTab(getAnimationPanel().getTabbedPane().getTabCount() - 1,
112                 getModel().getTrafCOD().getId(), wrapper);
113     }
114 
115     /**
116      * The simulation model.
117      */
118     static class TrafCODModel extends AbstractOTSModel implements EventListenerInterface
119     {
120         /** */
121         private static final long serialVersionUID = 20161020L;
122 
123         /** The network. */
124         private OTSNetwork network;
125 
126         /** The TrafCOD controller. */
127         private TrafCOD trafCOD;
128 
129         /** TrafCOD controller display. */
130         private JPanel controllerDisplayPanel = new JPanel(new BorderLayout());
131 
132         /**
133          * @param simulator OTSSimulatorInterface; the simulator for this model
134          */
135         TrafCODModel(final OTSSimulatorInterface simulator)
136         {
137             super(simulator);
138         }
139 
140         /** {@inheritDoc} */
141         @Override
142         public void constructModel() throws SimRuntimeException
143         {
144             try
145             {
146                 URL url = URLResource.getResource("/TrafCODDemo2/Network.xml");
147                 XmlNetworkLaneParser nlp = new XmlNetworkLaneParser(getSimulator());
148                 this.network = nlp.build(url, true);
149                 String[] directions = { "E", "S", "W", "N" };
150                 // Add the traffic lights and the detectors
151                 Set<TrafficLight> trafficLights = new HashSet<>();
152                 Set<TrafficLightSensor> sensors = new HashSet<>();
153                 Length stopLineMargin = new Length(0.1, LengthUnit.METER);
154                 Length headDetectorLength = new Length(1, LengthUnit.METER);
155                 Length headDetectorMargin = stopLineMargin.plus(headDetectorLength).plus(new Length(3, LengthUnit.METER));
156                 Length longDetectorLength = new Length(30, LengthUnit.METER);
157                 Length longDetectorMargin = stopLineMargin.plus(longDetectorLength).plus(new Length(10, LengthUnit.METER));
158                 int stream = 1;
159                 for (String direction : directions)
160                 {
161                     for (int laneNumber = 3; laneNumber >= 1; laneNumber--)
162                     {
163                         Lane lane = (Lane) ((CrossSectionLink) this.network.getLink(direction, direction + "C"))
164                                 .getCrossSectionElement("FORWARD" + laneNumber);
165                         TrafficLight tl = new SimpleTrafficLight(String.format("TL%02d", stream), lane,
166                                 lane.getLength().minus(stopLineMargin), getSimulator());
167                         trafficLights.add(tl);
168 
169                         try
170                         {
171                             new TrafficLightAnimation(tl, this.simulator);
172                         }
173                         catch (RemoteException | NamingException exception)
174                         {
175                             throw new NetworkException(exception);
176                         }
177 
178                         sensors.add(new TrafficLightSensor(String.format("D%02d1", stream), lane,
179                                 lane.getLength().minus(headDetectorMargin), lane,
180                                 lane.getLength().minus(headDetectorMargin).plus(headDetectorLength), null,
181                                 RelativePosition.FRONT, RelativePosition.REAR, getSimulator(), Compatible.EVERYTHING));
182                         sensors.add(new TrafficLightSensor(String.format("D%02d2", stream), lane,
183                                 lane.getLength().minus(longDetectorMargin), lane,
184                                 lane.getLength().minus(longDetectorMargin).plus(longDetectorLength), null,
185                                 RelativePosition.FRONT, RelativePosition.REAR, getSimulator(), Compatible.EVERYTHING));
186                         stream++;
187                     }
188                 }
189                 String controllerName = "Not so simple TrafCOD controller";
190                 this.trafCOD = new TrafCOD(controllerName, URLResource.getResource("/TrafCODDemo2/Intersection12Dir.tfc"),
191                         trafficLights, sensors, getSimulator(), this.controllerDisplayPanel);
192                 this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING);
193                 this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING);
194                 this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED);
195                 this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_STATE_CHANGED);
196                 this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_VARIABLE_CREATED);
197                 this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED);
198                 // Subscribe the TrafCOD machine to trace command events that we emit
199                 addListener(this.trafCOD, TrafficController.TRAFFICCONTROL_SET_TRACING);
200                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TGX", 8, true});
201                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "XR1", 11, true});
202                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TD1", 11, true});
203                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TGX", 11, true});
204                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TL", 11, true});
205                 // System.out.println("demo: emitting a SET TRACING event for all variables related to stream 11");
206                 // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] { controllerName, "", 11, true });
207 
208                 // this.trafCOD.traceVariablesOfStream(TrafficController.NO_STREAM, true);
209                 // this.trafCOD.traceVariablesOfStream(11, true);
210                 // this.trafCOD.traceVariable("MRV", 11, true);
211             }
212             catch (Exception exception)
213             {
214                 exception.printStackTrace();
215             }
216         }
217 
218         /** {@inheritDoc} */
219         @Override
220         public final OTSNetwork getNetwork()
221         {
222             return this.network;
223         }
224 
225         /**
226          * @return trafCOD
227          */
228         public final TrafCOD getTrafCOD()
229         {
230             return this.trafCOD;
231         }
232 
233         /**
234          * @return controllerDisplayPanel
235          */
236         public final JPanel getControllerDisplayPanel()
237         {
238             return this.controllerDisplayPanel;
239         }
240 
241         /** {@inheritDoc} */
242         @Override
243         public void notify(final EventInterface event) throws RemoteException
244         {
245             EventType type = event.getType();
246             Object[] payload = (Object[]) event.getContent();
247             if (TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING.equals(type))
248             {
249                 // System.out.println("Evaluation starts at " + getSimulator().getSimulatorTime());
250                 return;
251             }
252             else if (TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED.equals(type))
253             {
254                 System.out.println("Conflict group changed from " + ((String) payload[1]) + " to " + ((String) payload[2]));
255             }
256             else if (TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED.equals(type))
257             {
258                 System.out.println(String.format("Variable changed %s <- %d   %s", payload[1], payload[4], payload[5]));
259             }
260             else if (TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING.equals(type))
261             {
262                 System.out.println("Warning " + payload[1]);
263             }
264             else
265             {
266                 System.out.print("TrafCODDemo received event of type " + event.getType() + ", payload [");
267                 String separator = "";
268                 for (Object o : payload)
269                 {
270                     System.out.print(separator + o);
271                     separator = ",";
272                 }
273                 System.out.println("]");
274             }
275         }
276 
277     }
278 
279 }