View Javadoc
1   package org.opentrafficsim.demo.trafficcontrol;
2   
3   import java.awt.BorderLayout;
4   import java.awt.Container;
5   import java.io.IOException;
6   import java.net.URL;
7   import java.nio.charset.StandardCharsets;
8   import java.rmi.RemoteException;
9   import java.util.Optional;
10  import java.util.Scanner;
11  
12  import javax.swing.JPanel;
13  import javax.swing.JScrollPane;
14  
15  import org.djutils.event.Event;
16  import org.djutils.event.EventListener;
17  import org.djutils.event.EventType;
18  import org.djutils.immutablecollections.ImmutableMap;
19  import org.opentrafficsim.base.logger.Logger;
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.object.NonLocatedObject;
24  import org.opentrafficsim.demo.DefaultsFactory;
25  import org.opentrafficsim.demo.trafficcontrol.TrafCodDemo2.TrafCodModel;
26  import org.opentrafficsim.road.network.factory.xml.OtsXmlModel;
27  import org.opentrafficsim.swing.gui.OtsAnimationPanel;
28  import org.opentrafficsim.swing.gui.OtsSimulationApplication;
29  import org.opentrafficsim.trafficcontrol.TrafficController;
30  import org.opentrafficsim.trafficcontrol.trafcod.TrafCod;
31  
32  import nl.tudelft.simulation.dsol.SimRuntimeException;
33  import nl.tudelft.simulation.dsol.swing.gui.TabbedContentPane;
34  import nl.tudelft.simulation.language.DsolException;
35  
36  /**
37   * <p>
38   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
39   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
40   * </p>
41   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
42   * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
43   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
44   */
45  public class TrafCodDemo2 extends OtsSimulationApplication<TrafCodModel>
46  {
47      /** */
48      private static final long serialVersionUID = 20161118L;
49  
50      /**
51       * Create a Trafcod demo.
52       * @param title the title of the Frame
53       * @param panel the tabbed panel to display
54       * @param model the model
55       */
56      public TrafCodDemo2(final String title, final OtsAnimationPanel panel, final TrafCodModel model)
57      {
58          super(model, panel, DefaultsFactory.GTU_TYPE_MARKERS.toMap());
59      }
60  
61      /**
62       * Main program.
63       * @param args the command line arguments (not used)
64       * @throws IOException ...
65       */
66      public static void main(final String[] args) throws IOException
67      {
68          demo(true);
69      }
70  
71      /**
72       * Open an URL, read it and store the contents in a string. Adapted from
73       * https://stackoverflow.com/questions/4328711/read-url-to-string-in-few-lines-of-java-code
74       * @param url the URL
75       * @return String
76       * @throws IOException when reading the file fails
77       */
78      public static String readStringFromURL(final URL url) throws IOException
79      {
80          try (Scanner scanner = new Scanner(url.openStream(), StandardCharsets.UTF_8.toString()))
81          {
82              scanner.useDelimiter("\\A");
83              return scanner.hasNext() ? scanner.next() : "";
84          }
85      }
86  
87      /**
88       * Start the demo.
89       * @param exitOnClose when running stand-alone: true; when running as part of a demo: false
90       * @throws IOException when reading the file fails
91       */
92      public static void demo(final boolean exitOnClose) throws IOException
93      {
94          try
95          {
96              OtsAnimator simulator = new OtsAnimator("TrafCODDemo2");
97              final TrafCodModel trafcodModel = new TrafCodModel(simulator, "TrafCODModel", "TrafCOD demonstration Model");
98              OtsAnimationPanel animationPanel = new OtsAnimationPanel(trafcodModel.getNetwork().getExtent(), simulator,
99                      trafcodModel, DEFAULT_GTU_COLORERS, trafcodModel.getNetwork());
100             TrafCodDemo2 app = new TrafCodDemo2("TrafCOD demo complex crossing", animationPanel, trafcodModel);
101             app.setExitOnClose(exitOnClose);
102             animationPanel.enableSimulationControlButtons();
103         }
104         catch (SimRuntimeException | RemoteException | DsolException exception)
105         {
106             exception.printStackTrace();
107         }
108     }
109 
110     /**
111      * Add tabs with trafCOD status display.
112      */
113     @Override
114     protected final void addTabs()
115     {
116         OtsAnimationPanel animationPanel = getAnimationPanel();
117         if (null == animationPanel)
118         {
119             return;
120         }
121         ImmutableMap<String, NonLocatedObject> nonLocatedObjectMap = getModel().getNetwork().getNonLocatedObjectMap();
122         for (NonLocatedObject ioi : nonLocatedObjectMap.values())
123         {
124             if (ioi instanceof TrafCod)
125             {
126                 TrafCod trafCOD = (TrafCod) ioi;
127                 Optional<Container> controllerDisplayPanel = trafCOD.getDisplayContainer();
128                 if (controllerDisplayPanel.isPresent())
129                 {
130                     JPanel wrapper = new JPanel(new BorderLayout());
131                     wrapper.add(new JScrollPane(controllerDisplayPanel.get()));
132                     TabbedContentPane tabbedPane = animationPanel.getTabbedPane();
133                     tabbedPane.addTab(tabbedPane.getTabCount() - 1, trafCOD.getId(), wrapper);
134                 }
135                 // trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING);
136                 trafCOD.addListener(getModel(), TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING);
137                 trafCOD.addListener(getModel(), TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED);
138                 trafCOD.addListener(getModel(), TrafficController.TRAFFICCONTROL_STATE_CHANGED);
139                 trafCOD.addListener(getModel(), TrafficController.TRAFFICCONTROL_VARIABLE_CREATED);
140                 trafCOD.addListener(getModel(), TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED);
141 
142             }
143         }
144     }
145 
146     /**
147      * The simulation model.
148      */
149     public static class TrafCodModel extends OtsXmlModel implements EventListener
150     {
151         /**
152          * Constructor.
153          * @param simulator the simulator
154          * @param shortName name of the model
155          * @param description description of the model
156          */
157         public TrafCodModel(final OtsSimulatorInterface simulator, final String shortName, final String description)
158         {
159             super(simulator, shortName, description, AbstractOtsModel.defaultInitialStreams(),
160                     "/resources/TrafCODDemo2/TrafCODDemo2.xml");
161         }
162 
163         @Override
164         public void notify(final Event event)
165         {
166             EventType type = event.getType();
167             Object[] payload = (Object[]) event.getContent();
168             if (TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING.equals(type))
169             {
170                 Logger.ots().info("Evaluation starts at " + getSimulator().getSimulatorTime());
171                 return;
172             }
173             else if (TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED.equals(type))
174             {
175                 Logger.ots().info("Conflict group changed from {} to {}", (String) payload[1], (String) payload[2]);
176             }
177             else if (TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED.equals(type))
178             {
179                 Logger.ots().info("Variable changed %s <- %d   %s", payload[1], payload[4], payload[5]);
180             }
181             else if (TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING.equals(type))
182             {
183                 Logger.ots().info("Warning " + payload[1]);
184             }
185             else
186             {
187                 StringBuilder stringBuilder = new StringBuilder();
188                 stringBuilder.append("TrafCODDemo received event of type " + event.getType() + ", payload [");
189                 String separator = "";
190                 for (Object o : payload)
191                 {
192                     stringBuilder.append(separator + o);
193                     separator = ",";
194                 }
195                 stringBuilder.append("]");
196                 Logger.ots().info(stringBuilder.toString());
197             }
198         }
199 
200         @Override
201         public String toString()
202         {
203             return "TrafCODModel [network=" + getNetwork().getId() + "]";
204         }
205 
206     }
207 
208 }