- Timestamp:
- 10/30/2017 02:07:58 PM (9 years ago)
- File:
-
- 1 copied
-
trunk/test/atmsdriver/TrafficModelEventDriver.java (copied) (copied from trunk/src/tmcsim/client/ATMSBatchDriver.java) (12 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/test/atmsdriver/TrafficModelEventDriver.java
r184 r192 1 package tmcsim.client;2 3 import atmsdriver.ConsoleTrafficDriver;1 package atmsdriver; 2 3 import tmcsim.client.*; 4 4 import atmsdriver.model.Highways; 5 5 import atmsdriver.model.TrafficEvent; … … 9 9 import java.io.FileInputStream; 10 10 import java.io.FileNotFoundException; 11 import java.rmi.Naming;12 11 import java.rmi.RemoteException; 13 12 import java.rmi.server.UnicastRemoteObject; … … 36 35 /** 37 36 * Skeleton for ATMS Driver that reads a "batch" file of highway status update 38 * commands. It operates as a client of the CAD server, using RMI to poll the 39 * server every second for the current simulation clock time. It uses the 40 * simulation clock time to fire update commands at the desired time. Note: Sim 41 * Mgr must be running before starting this application. TODO: We probably want 42 * to be able to "override" a command, to force clearing an incident. 43 * 37 * commands. A console display of the highway network is output 38 * for each event. 44 39 * @author jdalbey 45 40 */ 46 public class ATMSBatchDriver extends UnicastRemoteObject implements41 public class TrafficModelEventDriver extends UnicastRemoteObject implements 47 42 CADClientInterface 48 43 { 49 50 private static final String CONFIG_FILE_NAME = "cad_client_config.properties";51 private final static int ONE_SECOND = 1000;52 private static final int FEPSIM_INTERVAL = 30000;53 44 private final static SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 54 45 /** … … 64 55 65 56 /** 66 * Enumeration containing properties name values. See CADClient class67 * description for more information.68 *69 * @author Matthew Cechini70 * @see CADClient71 */72 private static enum PROPERTIES73 {74 CAD_SIM_HOST("CADSimulatorHost"), CAD_SIM_PORT("CADSimulatorSocketPort"), CAD_RMI_PORT(75 "CADRmiPort"), CLIENT_CAD_POS("CADPosition"), CLIENT_USER_ID(76 "CADUserID"), KEYBOARD_TYPE("KeyboardType"), DISPLAY_TYPE(77 "DisplayType");78 public String name;79 80 private PROPERTIES(String n)81 {82 name = n;83 }84 }85 /**86 * CADClientSocket Object to handle socket communication between the Client87 * and CAD Simulator.88 */89 private CADClientSocket theClientSocket;90 91 /**92 * Properties object for the CADClient class.93 */94 private Properties cadClientProp;95 /**96 * RMI interface for communication with the remote Coordinator.97 */98 private static CoordinatorInterface theCoorInt;99 /**100 * reference to itself to be used for disconnecting from CADSimulator101 */102 private CADClientInterface client = this;103 104 /**105 57 * Highways in traffic network 106 58 */ … … 115 67 */ 116 68 private Map<String, List<TrafficEvent>> incidents; 117 118 /**119 * Instance of ConsoleTrafficDriver that contains the highway model120 */121 private ConsoleTrafficDriver console;122 123 /**124 * GUI for this driver125 */126 private ATMSBatchViewer theView;127 69 128 70 /** … … 133 75 * file containing configuration data. 134 76 */ 135 public ATMSBatchDriver(String propertiesFile) throws SimulationException, 136 RemoteException 137 { 138 if (!verifyProperties(propertiesFile)) 139 { 140 System.exit(0); 141 } 77 public TrafficModelEventDriver() throws RemoteException 78 { 142 79 // Initialize the highway model 143 80 incidents = new HashMap<String, List<TrafficEvent>>(); … … 147 84 "localhost", 8080); 148 85 149 connect(cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name).trim(),150 cadClientProp.getProperty(PROPERTIES.CAD_RMI_PORT.name).trim());151 152 86 // READ THE BATCH FILE OF COMMANDS and put in a queue 153 87 readBatchFile(); 154 // Launch the display 155 theView = new ATMSBatchViewer(this, new ArrayList<String>(incidents.keySet())); 156 theView.setVisible(true); 157 theView.update("0:00", "1:11", eventQueue); 158 159 // Create a timer that fetches the simulation time every second. 160 Timer timer = new Timer(ONE_SECOND, new ActionListener() 161 { 162 // Every second, see if an event should be launched 163 public void actionPerformed(ActionEvent e) 164 { 165 String currentClock = ""; 166 String currentATMStime = ""; 167 Date simClock = new Date(); 168 // Obtain the simulation time from the CAD server 169 try 170 { 171 long simtime = theCoorInt.getCurrentSimulationTime(); 172 currentClock = formatInterval(simtime); 173 // For Debugging, show the ATMS time 174 // long ATMStime = theCoorInt.getATMStime(); 175 // Date atmsdate = new Date(ATMStime); 176 // currentATMStime = formatter.format(atmsdate); 177 try 178 { 179 simClock = formatter.parse(currentClock); 180 } 181 catch (ParseException ex) 182 { 183 Logger.getLogger(ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex); 184 System.out.println("Invalid simulation clock time found in ATMSDriverClient"); 185 System.exit(-1); 186 } 187 //System.out.println("Current clock: " + currentClock); 188 } 189 catch (RemoteException ex) 190 { 191 System.out.println("Remote Exception reading sim or ATMS clock time"); 192 Logger.getLogger(ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex); 193 } 194 // If we have any events left to process 195 if (!eventQueue.isEmpty()) 196 { 197 // Get the time to launch the next event 198 TrafficEvent nextEvent = eventQueue.peek(); 199 Date eventTime = nextEvent.eventDate; 200 //System.out.println("Next event will be launched at: " + formatter.format(eventTime)); 201 // Check the queue of events to see if the first 202 // item should be launched. IF so, 203 // issue that command and remove it from queue. 204 if (eventTime.before(simClock) || eventTime.equals(simClock)) 205 { 206 System.out.println("LAUNCHING EVENT: " + nextEvent.toString()); 207 // apply colorization to highways 208 highways.applyColorToHighwayStretch(nextEvent.routeNumber, nextEvent.dir, 209 nextEvent.postmile, nextEvent.range, nextEvent.color); 210 // Remove this event from the queue, we're done with it. 211 eventQueue.remove(); 212 } 213 214 theView.update(currentClock, currentATMStime, eventQueue); 215 } 216 } 217 }); 218 timer.start(); 219 220 // Start the FEP thread (to update ATMS every 30 sec). (See class def below) 221 Thread wtfep = new WriteToFEPThread(); 222 wtfep.start(); 223 224 ensureProperShutdown(); 88 89 // If we have any events left to process 90 while (!eventQueue.isEmpty()) 91 { 92 // Get the time to launch the next event 93 TrafficEvent nextEvent = eventQueue.peek(); 94 System.out.println("LAUNCHING EVENT: " + nextEvent.toString()); 95 // apply colorization to highways 96 highways.applyColorToHighwayStretch(nextEvent.routeNumber, nextEvent.dir, 97 nextEvent.postmile, nextEvent.range, nextEvent.color); 98 System.out.println(highways.toString()); 99 // Remove this event from the queue, we're done with it. 100 eventQueue.remove(); 101 102 } 103 225 104 } 226 105 … … 262 141 catch (ParseException ex) 263 142 { 264 Logger.getLogger( ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex);143 Logger.getLogger(TrafficModelEventDriver.class.getName()).log(Level.SEVERE, null, ex); 265 144 System.out.println("Wrong format data in batch event file: " + line + " \nskipping."); 266 145 System.out.println("Skipping badly formatted event."); … … 271 150 catch (FileNotFoundException ex) 272 151 { 273 Logger.getLogger( ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex);152 Logger.getLogger(TrafficModelEventDriver.class.getName()).log(Level.SEVERE, null, ex); 274 153 } 275 154 System.out.println("Events file read, " + eventQueue.size() + " events queued."); 276 155 // Put the events in chronological order 277 156 Collections.sort(eventQueue); 278 }279 280 /**281 * Clear an incident. For each event associated with an incident, turn the282 * dots in its range Green and remove it from the event queue.283 *284 * @param incidentNumber incident to be cleared.285 */286 public void clearIncident(String incidentNumber)287 {288 boolean ok = incidents.containsKey(incidentNumber);289 if (!ok)290 {291 System.out.println("Sorry, that incident number isn't found.");292 return;293 }294 System.out.println("Clearing incident " + incidentNumber);295 List<TrafficEvent> events = incidents.get(incidentNumber);296 // Process each event associated with this incident297 for (TrafficEvent event : events)298 {299 System.out.println("Event: " + event + " cleared.");300 eventQueue.remove(event);301 302 // apply colorization to highways, forcing to green, indicating cleared303 highways.applyColorToHighwayStretch(event.routeNumber, event.dir,304 event.postmile, event.range, DOTCOLOR.GREEN);305 306 }307 // Now refresh the view with the updated queue of events308 theView.update("0:00", "0:00", eventQueue);309 }310 311 /**312 * Connect to the Coordinator's RMI object, and register this object for313 * callback with the Coordinator.314 *315 * @param hostname Host name of the CAD Simulator.316 * @param portNumber Port number of the CAD Simulator RMI communication.317 * @throws SimulationException if there is an error creating the RMI318 * connection.319 */320 protected void connect(String hostname, String portNumber)321 throws SimulationException322 {323 324 String coorIntURL = "";325 326 try327 {328 coorIntURL = "rmi://" + hostname + ":" + portNumber329 + "/coordinator";330 theCoorInt = (CoordinatorInterface) Naming.lookup(coorIntURL);331 theCoorInt.registerForCallback(this);332 }333 catch (Exception e)334 {335 throw new SimulationException(SimulationException.CAD_SIM_CONNECT,336 e);337 338 }339 }340 341 /**342 * This method verifies that the CAD Simulator Host and Port values are not343 * null. Also, if a CAD Position or User ID do not exist in the properties344 * file, the user is prompted to enter values. These values are written to345 * the properties file. If the user cancels the process of entering these346 * values, the verification fails.347 *348 * @param propertiesFile File path (absolute or relative) to the properties349 * file containing configuration data.350 * @return True if the properties file is valid, false if not.351 * @throws SimulationException if there is an exception in verifying the352 * properties file, or if the user cancels input.353 */354 private boolean verifyProperties(String propertiesFile)355 throws SimulationException356 {357 358 // Load the properties file.359 try360 {361 cadClientProp = new Properties();362 cadClientProp.load(new FileInputStream(propertiesFile));363 }364 catch (Exception e)365 {366 cadClientLogger.logp(Level.SEVERE, "SimulationManager",367 "Constructor", "Exception in reading properties file.", e);368 369 throw new SimulationException(SimulationException.INITIALIZE_ERROR,370 e);371 }372 373 // Ensure that the properties file does not have null values for the374 // CAD Simulator's connection information.375 if (cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name) == null376 || cadClientProp.getProperty(PROPERTIES.CAD_SIM_PORT.name) == null)377 {378 cadClientLogger.logp(Level.SEVERE, "SimulationManager",379 "Constructor", "Null value in properties file.");380 throw new SimulationException(SimulationException.INITIALIZE_ERROR);381 }382 383 return true;384 157 } 385 158 … … 397 170 return String.format("%02d:%02d:%02d", hr, min, sec); 398 171 } 399 400 public void ensureProperShutdown()401 {402 Runtime.getRuntime().addShutdownHook(new Thread()403 {404 public void run()405 {406 try407 {408 theCoorInt.unregisterForCallback(client);409 }410 catch (RemoteException e)411 {412 e.printStackTrace();413 }414 }415 });416 }417 418 172 /** 419 173 * Construct the CADClient with the properties file path, either from the … … 432 186 { 433 187 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 434 new ATMSBatchDriver(System.getProperty("CONFIG_DIR") + System.getProperty("file.separator") + CONFIG_FILE_NAME);188 new TrafficModelEventDriver(); 435 189 436 190 } … … 448 202 } 449 203 450 class WriteToFEPThread extends Thread451 {452 453 public void run()454 {455 System.out.println("WriteToFEP Thread starting.");456 // Run indefinitely457 while (true)458 {459 try460 {461 // Write the highway network status to the FEP Simulator462 highways.writeToFEP();463 }464 catch (SimulationException ex)465 {466 // Ask user if they want to proceed without FEP Sim connection467 int reply = JOptionPane.showConfirmDialog(null, "Failed to connect to FEP Sim, proceed anyway?", "Network Failure", JOptionPane.YES_NO_OPTION);468 if (reply == JOptionPane.NO_OPTION)469 {470 System.exit(0);471 }472 System.out.println("Skipping writeToFEP...");473 }474 475 // Wait for FEP Sim to process the data we just sent476 try477 {478 Thread.sleep(FEPSIM_INTERVAL);479 }480 catch (InterruptedException ie)481 {482 ie.printStackTrace();483 }484 }485 486 }487 }488 204 }
Note: See TracChangeset
for help on using the changeset viewer.
