Package srsim.simulator

Source Code of srsim.simulator.SimulationTracker

package srsim.simulator;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import srsim.persistence.IDataStore;
import srsim.persistence.SimulationRecord;

/**
* Simulation tracker class, keeping track of the simulation and storing context
* changes as simulation reckords using an IDataSore implementation. Records are
* stored asynchronuosly.
*
* @author phil
*
*/
public class SimulationTracker extends Thread implements ISimulationListener {

  private ISimulationController controller;
  private IDataStore dataStore;
  private Queue<SimulationRecord> recordQueue;
  private boolean tracking;

  public SimulationTracker(ISimulationController controller,
      IDataStore dataStore) {
    this.controller = controller;
    this.dataStore = dataStore;
    this.controller.addSimulationListener(this);
    tracking = false;
    recordQueue = new LinkedBlockingQueue<SimulationRecord>();
    setName("SRSIM SimulationTracker");
  }

  /**
   * Starts tracking
   */
  public void track() {
    tracking = true;
    start();
  }

  /**
   * Stops tracking
   *
   * @throws InterruptedException
   */
  public void shutDown() throws InterruptedException {
    tracking = false;
    synchronized (recordQueue) {
      recordQueue.notify();
    }
    join();
  }

  @Override
  public void run() {
    tracking = true;
    try {
      while (tracking) {
        synchronized (recordQueue) {
          if (!recordQueue.isEmpty()) {
            SimulationRecord record = recordQueue.poll();
            dataStore.persist(record);
          } else if (tracking) {
            recordQueue.wait();
          }
        }
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void handleContextChange(final ContextChangedEvent event)
      throws SimulationContextException {
    SimulationRecord record = new SimulationRecord();
    SimulationContext context = event.getContext();
    record.setRoomId(context.getRoom().getName());
    record.setBrightness(context.getBrightness());
    record.setEnergyConsumption(context.getEnergyConsumption());
    record.setTemperature(context.getTemperature());
    record.setTimeStamp(event.getTimeStamp());
    record.setLightColor(context.getLightColor());
    record.setMudicGenre(context.getMusicGenre());
    record.setMusicVolume(context.getMusicVolume());
    synchronized (recordQueue) {
      recordQueue.add(record);
      recordQueue.notify();
    }
  }

  @Override
  public void handleControllerAction(ControllerActionEvent event) {

  }

}
TOP

Related Classes of srsim.simulator.SimulationTracker

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.