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