>> encountered a non-Token object: " + token + " after " + result.toString());
throw new TrafficControlException("Not a token");
}
}
return result.toString();
}
/**
* States of the rule parser.
*
* @author Peter Knoppers
*/
enum ParserState
{
/** Looking for the left hand side of an assignment. */
FIND_LHS,
/** Looking for an assignment operator. */
FIND_ASSIGN,
/** Looking for the right hand side of an assignment. */
FIND_RHS,
/** Looking for an optional unary minus. */
MAY_UMINUS,
/** Looking for an expression. */
FIND_EXPR,
}
/**
* Types of TrafCOD tokens.
*
* @author Peter Knoppers
*/
enum Token
{
/** Equals rule. */
EQUALS_RULE,
/** Not equals rule. */
NEG_EQUALS_RULE,
/** Assignment rule. */
ASSIGNMENT,
/** Start rule. */
START_RULE,
/** End rule. */
END_RULE,
/** Timer initialize rule. */
INIT_TIMER,
/** Timer re-initialize rule. */
REINIT_TIMER,
/** Unary minus operator. */
UNARY_MINUS,
/** Less than or equal to (<=). */
LEEQ,
/** Not equal to (!=). */
NOTEQ,
/** Less than (<). */
LE,
/** Greater than or equal to (>=). */
GTEQ,
/** Greater than (>). */
GT,
/** Equals to (=). */
EQ,
/** True if following variable has just started. */
START,
/** True if following variable has just ended. */
END,
/** Variable follows. */
VARIABLE,
/** Variable that follows must be logically negated. */
NEG_VARIABLE,
/** Integer follows. */
CONSTANT,
/** Addition operator. */
PLUS,
/** Subtraction operator. */
MINUS,
/** Multiplication operator. */
TIMES,
/** Opening parenthesis. */
OPEN_PAREN,
/** Closing parenthesis. */
CLOSE_PAREN,
}
/**
* Parse one TrafCOD rule.
* @param rawRule String; the TrafCOD rule
* @param locationDescription String; description of the location (file, line) where the rule was found
* @return Object[]; array filled with the tokenized rule
* @throws TrafficControlException when the rule is not a valid TrafCOD rule
*/
private Object[] parse(final String rawRule, final String locationDescription) throws TrafficControlException
{
if (rawRule.length() == 0)
{
throw new TrafficControlException("empty rule at " + locationDescription);
}
ParserState state = ParserState.FIND_LHS;
String rule = rawRule.toUpperCase(Locale.US);
Token ruleType = Token.ASSIGNMENT;
int inPos = 0;
NameAndStream lhsNameAndStream = null;
List tokens = new ArrayList<>();
while (inPos < rule.length())
{
char character = rule.charAt(inPos);
if (Character.isWhitespace(character))
{
inPos++;
continue;
}
switch (state)
{
case FIND_LHS:
{
if ('S' == character)
{
ruleType = Token.START_RULE;
inPos++;
lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
inPos += lhsNameAndStream.getNumberOfChars();
}
else if ('E' == character)
{
ruleType = Token.END_RULE;
inPos++;
lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
inPos += lhsNameAndStream.getNumberOfChars();
}
else if ('I' == character && 'T' == rule.charAt(inPos + 1))
{
ruleType = Token.INIT_TIMER;
inPos++; // The 'T' is part of the name of the time; do not consume it
lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
inPos += lhsNameAndStream.getNumberOfChars();
}
else if ('R' == character && 'I' == rule.charAt(inPos + 1) && 'T' == rule.charAt(inPos + 2))
{
ruleType = Token.REINIT_TIMER;
inPos += 2; // The 'T' is part of the name of the timer; do not consume it
lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
inPos += lhsNameAndStream.getNumberOfChars();
}
else if ('T' == character && rule.indexOf('=') >= 0
&& (rule.indexOf('N') < 0 || rule.indexOf('N') > rule.indexOf('=')))
{
throw new TrafficControlException("Bad time initialization at " + locationDescription);
}
else
{
ruleType = Token.EQUALS_RULE;
lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
inPos += lhsNameAndStream.getNumberOfChars();
if (lhsNameAndStream.isNegated())
{
ruleType = Token.NEG_EQUALS_RULE;
}
}
state = ParserState.FIND_ASSIGN;
break;
}
case FIND_ASSIGN:
{
if ('.' == character && '=' == rule.charAt(inPos + 1))
{
if (Token.EQUALS_RULE == ruleType)
{
ruleType = Token.START_RULE;
}
else if (Token.NEG_EQUALS_RULE == ruleType)
{
ruleType = Token.END_RULE;
}
inPos += 2;
}
else if ('=' == character)
{
if (Token.START_RULE == ruleType || Token.END_RULE == ruleType || Token.INIT_TIMER == ruleType
|| Token.REINIT_TIMER == ruleType)
{
throw new TrafficControlException("Bad assignment at " + locationDescription);
}
inPos++;
}
tokens.add(ruleType);
EnumSet lhsFlags = EnumSet.noneOf(Flags.class);
if (Token.START_RULE == ruleType || Token.EQUALS_RULE == ruleType || Token.NEG_EQUALS_RULE == ruleType
|| Token.INIT_TIMER == ruleType || Token.REINIT_TIMER == ruleType)
{
lhsFlags.add(Flags.HAS_START_RULE);
}
if (Token.END_RULE == ruleType || Token.EQUALS_RULE == ruleType || Token.NEG_EQUALS_RULE == ruleType)
{
lhsFlags.add(Flags.HAS_END_RULE);
}
Variable lhsVariable = installVariable(lhsNameAndStream.getName(), lhsNameAndStream.getStream(), lhsFlags,
locationDescription);
tokens.add(lhsVariable);
state = ParserState.MAY_UMINUS;
break;
}
case MAY_UMINUS:
if ('-' == character)
{
tokens.add(Token.UNARY_MINUS);
inPos++;
}
state = ParserState.FIND_EXPR;
break;
case FIND_EXPR:
{
if (Character.isDigit(character))
{
int constValue = 0;
while (inPos < rule.length() && Character.isDigit(rule.charAt(inPos)))
{
int digit = rule.charAt(inPos) - '0';
if (constValue >= (Integer.MAX_VALUE - digit) / 10)
{
throw new TrafficControlException("Number too large at " + locationDescription);
}
constValue = 10 * constValue + digit;
inPos++;
}
tokens.add(Token.CONSTANT);
tokens.add(new Integer(constValue));
}
if (inPos >= rule.length())
{
return tokens.toArray();
}
character = rule.charAt(inPos);
switch (character)
{
case '+':
tokens.add(Token.PLUS);
inPos++;
break;
case '-':
tokens.add(Token.MINUS);
inPos++;
break;
case '.':
tokens.add(Token.TIMES);
inPos++;
break;
case ')':
tokens.add(Token.CLOSE_PAREN);
inPos++;
break;
case '<':
{
Character nextChar = rule.charAt(++inPos);
if ('=' == nextChar)
{
tokens.add(Token.LEEQ);
inPos++;
}
else if ('>' == nextChar)
{
tokens.add(Token.NOTEQ);
inPos++;
}
else
{
tokens.add(Token.LE);
}
break;
}
case '>':
{
Character nextChar = rule.charAt(++inPos);
if ('=' == nextChar)
{
tokens.add(Token.GTEQ);
inPos++;
}
else if ('<' == nextChar)
{
tokens.add(Token.NOTEQ);
inPos++;
}
else
{
tokens.add(Token.GT);
}
break;
}
case '=':
{
Character nextChar = rule.charAt(++inPos);
if ('<' == nextChar)
{
tokens.add(Token.LEEQ);
inPos++;
}
else if ('>' == nextChar)
{
tokens.add(Token.GTEQ);
inPos++;
}
else
{
tokens.add(Token.EQ);
}
break;
}
case '(':
{
inPos++;
tokens.add(Token.OPEN_PAREN);
state = ParserState.MAY_UMINUS;
break;
}
default:
{
if ('S' == character)
{
tokens.add(Token.START);
inPos++;
}
else if ('E' == character)
{
tokens.add(Token.END);
inPos++;
}
NameAndStream nas = new NameAndStream(rule.substring(inPos), locationDescription);
inPos += nas.getNumberOfChars();
if (nas.isNegated())
{
tokens.add(Token.NEG_VARIABLE);
}
else
{
tokens.add(Token.VARIABLE);
}
Variable variable = installVariable(nas.getName(), nas.getStream(), EnumSet.noneOf(Flags.class),
locationDescription);
variable.incrementReferenceCount();
tokens.add(variable);
}
}
break;
}
default:
throw new TrafficControlException("Error: bad switch; case " + state + " should not happen");
}
}
return tokens.toArray();
}
/**
* Check if a String begins with the text of a supplied String (ignoring case).
* @param sought String; the sought pattern (NOT a regular expression)
* @param supplied String; the String that might start with the sought string
* @return boolean; true if the supplied String begins with the sought String (case insensitive)
*/
private boolean stringBeginsWithIgnoreCase(final String sought, final String supplied)
{
if (sought.length() > supplied.length())
{
return false;
}
return (sought.equalsIgnoreCase(supplied.substring(0, sought.length())));
}
/**
* Generate the key for a variable name and stream for use in this.variables.
* @param name String; name of the variable
* @param stream short; stream of the variable
* @return String
*/
private String variableKey(final String name, final short stream)
{
if (name.startsWith("D"))
{
return String.format("D%02d%s", stream, name.substring(1));
}
return String.format("%s%02d", name.toUpperCase(Locale.US), stream);
}
/**
* Lookup or create a new Variable.
* @param name String; name of the variable
* @param stream short; stream number of the variable
* @param flags EnumSet<Flags>; some (possibly empty) combination of Flags.HAS_START_RULE and Flags.HAS_END_RULE; no
* other flags are allowed
* @param location String; description of the location in the TrafCOD file that triggered the call to this method
* @return Variable; the new (or already existing) variable
* @throws TrafficControlException if the variable already exists and already has (one of) the specified flag(s)
*/
private Variable installVariable(final String name, final short stream, final EnumSet flags, final String location)
throws TrafficControlException
{
EnumSet forbidden = EnumSet.complementOf(EnumSet.of(Flags.HAS_START_RULE, Flags.HAS_END_RULE));
EnumSet badFlags = EnumSet.copyOf(forbidden);
badFlags.retainAll(flags);
if (badFlags.size() > 0)
{
throw new TrafficControlException("installVariable was called with wrong flag(s): " + badFlags);
}
String key = variableKey(name, stream);
Variable variable = this.variables.get(key);
if (null == variable)
{
// Create and install a new variable
variable = new Variable(name, stream, this);
this.variables.put(key, variable);
this.variablesInDefinitionOrder.add(variable);
if (variable.isDetector())
{
this.detectors.put(key, variable);
}
}
if (flags.contains(Flags.HAS_START_RULE))
{
variable.setStartSource(location);
}
if (flags.contains(Flags.HAS_END_RULE))
{
variable.setEndSource(location);
}
return variable;
}
/**
* Retrieve the simulator.
* @return SimulatorInterface<Time, Duration, SimTimeDoubleUnit>
*/
public SimulatorInterface getSimulator()
{
return this.simulator;
}
/**
* Retrieve the structure number.
* @return int; the structureNumber
*/
public int getStructureNumber()
{
return this.structureNumber;
}
/** {@inheritDoc} */
@Override
public void updateDetector(final String detectorId, final boolean detectingGTU)
{
Variable detector = this.detectors.get(detectorId);
detector.setValue(detectingGTU ? 1 : 0, this.currentTime10,
new CausePrinter(
String.format("Detector %s becoming %s", detectorId, (detectingGTU ? "occupied" : "unoccupied"))),
this);
}
/**
* Switch tracing of all variables of a particular traffic stream, or all variables that do not have an associated traffic
* stream on or off.
* @param stream int; the traffic stream number, or TrafCOD.NO_STREAM
to affect all variables that do not have
* an associated traffic stream
* @param trace boolean; if true; switch on tracing; if false; switch off tracing
*/
public void traceVariablesOfStream(final int stream, final boolean trace)
{
for (Variable v : this.variablesInDefinitionOrder)
{
if (v.getStream() == stream)
{
if (trace)
{
v.setFlag(Flags.TRACED);
}
else
{
v.clearFlag(Flags.TRACED);
}
}
}
}
/**
* Switch tracing of one variable on or off.
* @param variableName String; name of the variable
* @param stream int; traffic stream of the variable, or TrafCOD.NO_STREAM
to select a variable that does not
* have an associated traffic stream
* @param trace boolean; if true; switch on tracing; if false; switch off tracing
*/
public void traceVariable(final String variableName, final int stream, final boolean trace)
{
for (Variable v : this.variablesInDefinitionOrder)
{
if (v.getStream() == stream && variableName.equals(v.getName()))
{
if (trace)
{
v.setFlag(Flags.TRACED);
}
else
{
v.clearFlag(Flags.TRACED);
}
}
}
}
/** {@inheritDoc} */
@Override
public void notify(final EventInterface event) throws RemoteException
{
System.out.println("TrafCOD: received an event");
if (event.getType().equals(TrafficController.TRAFFICCONTROL_SET_TRACING))
{
Object content = event.getContent();
if (!(content instanceof Object[]))
{
System.err.println("TrafCOD controller " + getId() + " received event with bad payload (" + content + ")");
return;
}
Object[] fields = (Object[]) event.getContent();
if (getId().equals(fields[0]))
{
if (fields.length < 4 || !(fields[1] instanceof String) || !(fields[2] instanceof Integer)
|| !(fields[3] instanceof Boolean))
{
System.err.println("TrafCOD controller " + getId() + " received event with bad payload (" + content + ")");
return;
}
String name = (String) fields[1];
int stream = (Integer) fields[2];
boolean trace = (Boolean) fields[3];
if (name.length() > 1)
{
Variable v = this.variables.get(variableKey(name, (short) stream));
if (null == v)
{
System.err.println("Received trace notification for nonexistent variable (name=\"" + name
+ "\", stream=" + stream + ")");
}
if (trace)
{
v.setFlag(Flags.TRACED);
}
else
{
v.clearFlag(Flags.TRACED);
}
}
else
{
for (Variable v : this.variablesInDefinitionOrder)
{
if (v.getStream() == stream)
{
if (trace)
{
v.setFlag(Flags.TRACED);
}
else
{
v.clearFlag(Flags.TRACED);
}
}
}
}
}
// else: event not destined for this controller
}
}
/**
* Fire an event on behalf of this TrafCOD engine (used for tracing variable changes).
* @param eventType TimedEventType; the type of the event
* @param payload Object[]; the payload of the event
*/
void fireTrafCODEvent(final TimedEventType eventType, final Object[] payload)
{
fireTimedEvent(eventType, payload, getSimulator().getSimulatorTime());
}
/** {@inheritDoc} */
@Override
public String getFullId()
{
return getId();
}
/** {@inheritDoc} */
@Override
public Container getDisplayContainer()
{
return this.displayContainer;
}
/** {@inheritDoc} */
@Override
public final InvisibleObjectInterface clone(final OTSSimulatorInterface newSimulator, final Network newNetwork)
throws NetworkException
{
try
{
// TODO figure out how to provide a display for the clone
TrafCOD result = new TrafCOD(getId(), this.trafCODRules, newSimulator, this.displayBackground, null);
result.fireTimedEvent(TRAFFICCONTROL_CONTROLLER_CREATED,
new Serializable[] {getId(), TrafficController.BEING_CLONED}, newSimulator.getSimulatorTime());
// Clone the variables
for (Variable v : this.variablesInDefinitionOrder)
{
Variable clonedVariable = result.installVariable(v.getName(), v.getStream(), EnumSet.noneOf(Flags.class), null);
clonedVariable.setStartSource(v.getStartSource());
clonedVariable.setEndSource(v.getEndSource());
if (clonedVariable.isDetector())
{
String detectorName = clonedVariable.toString(EnumSet.of(PrintFlags.ID));
int detectorNumber = clonedVariable.getStream() * 10 + detectorName.charAt(detectorName.length() - 1) - '0';
TrafficLightSensor clonedSensor = null;
for (ObjectInterface oi : newNetwork.getObjectMap().values())
{
if (oi instanceof TrafficLightSensor)
{
TrafficLightSensor tls = (TrafficLightSensor) oi;
if (tls.getId().endsWith(detectorName))
{
clonedSensor = tls;
}
}
}
if (null == clonedSensor)
{
throw new TrafficControlException("Cannot find detector " + detectorName + " with number "
+ detectorNumber + " among the provided sensors");
}
clonedVariable.subscribeToDetector(clonedSensor);
}
clonedVariable.cloneState(v, newNetwork); // also updates traffic lights
String key = variableKey(clonedVariable.getName(), clonedVariable.getStream());
result.variables.put(key, clonedVariable);
}
return result;
}
catch (TrafficControlException | SimRuntimeException tce)
{
throw new NetworkException(
"Internal error; caught an unexpected TrafficControlException or SimRunTimeException in clone");
}
}
/** {@inheritDoc} */
@Override
public Serializable getSourceId()
{
return null;
}
/** {@inheritDoc} */
@Override
public String toString()
{
return "TrafCOD [ie=" + getId() + "]";
}
}
/**
* Store a variable name, stream, isTimer, isNegated and number characters consumed information.
*/
class NameAndStream
{
/** The name. */
private final String name;
/** The stream number. */
private short stream = TrafficController.NO_STREAM;
/** Number characters parsed. */
private int numberOfChars = 0;
/** Was a letter N consumed while parsing the name?. */
private boolean negated = false;
/**
* Parse a TrafCOD identifier and extract all required information.
* @param text String; the TrafCOD identifier (may be followed by more text)
* @param locationDescription String; description of the location in the input file
* @throws TrafficControlException when text is not a valid TrafCOD variable name
*/
NameAndStream(final String text, final String locationDescription) throws TrafficControlException
{
int pos = 0;
while (pos < text.length() && Character.isWhitespace(text.charAt(pos)))
{
pos++;
}
while (pos < text.length())
{
char character = text.charAt(pos);
if (!Character.isLetterOrDigit(character))
{
break;
}
pos++;
}
this.numberOfChars = pos;
String trimmed = text.substring(0, pos).replaceAll(" ", "");
if (trimmed.length() == 0)
{
throw new TrafficControlException("missing variable at " + locationDescription);
}
if (trimmed.matches("^D([Nn]?\\d\\d\\d)|(\\d\\d\\d[Nn])"))
{
// Handle a detector
if (trimmed.charAt(1) == 'N' || trimmed.charAt(1) == 'n')
{
// Move the 'N' to the end
trimmed = "D" + trimmed.substring(2, 5) + "N" + trimmed.substring(5);
this.negated = true;
}
this.name = "D" + trimmed.charAt(3);
this.stream = (short) (10 * (trimmed.charAt(1) - '0') + trimmed.charAt(2) - '0');
return;
}
StringBuilder nameBuilder = new StringBuilder();
for (pos = 0; pos < trimmed.length(); pos++)
{
char nextChar = trimmed.charAt(pos);
if (pos < trimmed.length() - 1 && Character.isDigit(nextChar) && Character.isDigit(trimmed.charAt(pos + 1))
&& TrafficController.NO_STREAM == this.stream)
{
if (0 == pos || (1 == pos && trimmed.startsWith("N")))
{
throw new TrafficControlException("Bad variable name: " + trimmed + " at " + locationDescription);
}
if (trimmed.charAt(pos - 1) == 'N')
{
// Previous N was NOT part of the name
nameBuilder.deleteCharAt(nameBuilder.length() - 1);
// Move the 'N' after the digits
trimmed =
trimmed.substring(0, pos - 1) + trimmed.substring(pos, pos + 2) + trimmed.substring(pos + 2) + "N";
pos--;
}
this.stream = (short) (10 * (trimmed.charAt(pos) - '0') + trimmed.charAt(pos + 1) - '0');
pos++;
}
else
{
nameBuilder.append(nextChar);
}
}
if (trimmed.endsWith("N"))
{
nameBuilder.deleteCharAt(nameBuilder.length() - 1);
this.negated = true;
}
this.name = nameBuilder.toString();
}
/**
* Was a negation operator ('N') embedded in the name?
* @return boolean
*/
public boolean isNegated()
{
return this.negated;
}
/**
* Retrieve the stream number.
* @return short; the stream number
*/
public short getStream()
{
return this.stream;
}
/**
* Retrieve the name.
* @return String; the name (without the stream number)
*/
public String getName()
{
return this.name;
}
/**
* Retrieve the number of characters consumed from the input.
* @return int; the number of characters consumed from the input
*/
public int getNumberOfChars()
{
return this.numberOfChars;
}
/** {@inheritDoc} */
@Override
public String toString()
{
return "NameAndStream [name=" + this.name + ", stream=" + this.stream + ", numberOfChars=" + this.numberOfChars
+ ", negated=" + this.negated + "]";
}
}
/**
* A TrafCOD variable, timer, or detector.
*/
class Variable implements EventListenerInterface
{
/** ... */
private static final long serialVersionUID = 20200313L;
/** The TrafCOD engine. */
private final TrafCOD trafCOD;
/** Flags. */
private EnumSet flags = EnumSet.noneOf(Flags.class);
/** The current value. */
private int value;
/** Limit value (if this is a timer variable). */
private int timerMax10;
/** Output color (if this is an export variable). */
private TrafficLightColor color;
/** Name of this variable (without the traffic stream). */
private final String name;
/** Traffic stream number. */
private final short stream;
/** Number of rules that refer to this variable. */
private int refCount;
/** Time of last update in tenth of second. */
private int updateTime10;
/** Source of start rule. */
private String startSource;
/** Source of end rule. */
private String endSource;
/** The traffic light (only set if this Variable is an output(. */
private Set trafficLights;
/** Letters that are used to distinguish conflict groups in the MRx variables. */
private static String rowLetters = "ABCDXYZUVW";
/**
* Retrieve the number of rules that refer to this variable.
* @return int; the number of rules that refer to this variable
*/
public int getRefCount()
{
return this.refCount;
}
/**
* @param newNetwork OTSNetwork; the OTS Network in which the clone will exist
* @param newTrafCOD TrafCOD; the TrafCOD engine that will own the new Variable
* @return Variable; the clone of this variable in the new network
* @throws NetworkException when a traffic light or sensor is not present in newNetwork
* @throws TrafficControlException when the output for the cloned traffic light cannot be created
*/
final Variable clone(final OTSNetwork newNetwork, final TrafCOD newTrafCOD) throws NetworkException, TrafficControlException
{
Variable result = new Variable(getName(), getStream(), newTrafCOD);
result.flags = EnumSet.copyOf(this.flags);
result.value = this.value;
result.timerMax10 = this.timerMax10;
result.color = this.color;
result.refCount = this.refCount;
result.updateTime10 = this.updateTime10;
result.startSource = this.startSource;
result.endSource = this.endSource;
for (TrafficLight tl : this.trafficLights)
{
if (tl instanceof TrafficLightImage)
{
// Do not clone TrafficLightImage objects; these should (?) be created in the clone operation of TrafCOD.
continue;
}
ObjectInterface clonedTrafficLight = newNetwork.getObjectMap().get(tl.getId());
Throw.when(null == clonedTrafficLight, NetworkException.class,
"Cannot find clone of traffic light %s in newNetwork", tl.getId());
Throw.when(!(clonedTrafficLight instanceof TrafficLight), NetworkException.class,
"Object %s in newNetwork is not a TrafficLight", clonedTrafficLight);
result.addOutput((TrafficLight) clonedTrafficLight);
}
return result;
}
/**
* Retrieve the traffic lights controlled by this variable.
* @return Set<TrafficLight>; the traffic lights controlled by this variable, or null when this variable has no traffic
* lights
*/
public Set getTrafficLights()
{
return this.trafficLights;
}
/**
* Construct a new Variable.
* @param name String; name of the new variable (without the stream number)
* @param stream short; stream number to which the new Variable is associated
* @param trafCOD TrafCOD; the TrafCOD engine
*/
Variable(final String name, final short stream, final TrafCOD trafCOD)
{
this.name = name.toUpperCase(Locale.US);
this.stream = stream;
this.trafCOD = trafCOD;
if (this.name.startsWith("T"))
{
this.flags.add(Flags.IS_TIMER);
}
if (this.name.length() == 2 && this.name.startsWith("D") && Character.isDigit(this.name.charAt(1)))
{
this.flags.add(Flags.IS_DETECTOR);
}
if (TrafficController.NO_STREAM == stream && this.name.startsWith("MR") && this.name.length() == 3
&& rowLetters.indexOf(this.name.charAt(2)) >= 0)
{
this.flags.add(Flags.CONFLICT_GROUP);
}
}
/**
* Retrieve the name of this variable.
* @return String; the name (without the stream number) of this Variable
*/
public String getName()
{
return this.name;
}
/**
* Link a detector variable to a sensor.
* @param sensor TrafficLightSensor; the sensor
* @throws TrafficControlException when this variable is not a detector
*/
public void subscribeToDetector(final TrafficLightSensor sensor) throws TrafficControlException
{
if (!isDetector())
{
throw new TrafficControlException("Cannot subscribe a non-detector to a TrafficLightSensor");
}
sensor.addListener(this, NonDirectionalOccupancySensor.NON_DIRECTIONAL_OCCUPANCY_SENSOR_TRIGGER_ENTRY_EVENT);
sensor.addListener(this, NonDirectionalOccupancySensor.NON_DIRECTIONAL_OCCUPANCY_SENSOR_TRIGGER_EXIT_EVENT);
}
/**
* Initialize this variable if it has the INITED flag set.
*/
public void initialize()
{
if (this.flags.contains(Flags.INITED))
{
if (isTimer())
{
setValue(this.timerMax10, 0, new CausePrinter("Timer initialization rule"), this.trafCOD);
}
else
{
setValue(1, 0, new CausePrinter("Variable initialization rule"), this.trafCOD);
}
}
}
/**
* Decrement the value of a timer.
* @param timeStamp10 int; the current simulator time in tenths of a second
* @return boolean; true if the timer expired due to this call; false if the timer is still running, or expired before this
* call
* @throws TrafficControlException when this Variable is not a timer
*/
public boolean decrementTimer(final int timeStamp10) throws TrafficControlException
{
if (!isTimer())
{
throw new TrafficControlException("Variable " + this + " is not a timer");
}
if (this.value <= 0)
{
return false;
}
if (0 == --this.value)
{
this.flags.add(Flags.CHANGED);
this.flags.add(Flags.END);
this.value = 0;
this.updateTime10 = timeStamp10;
if (this.flags.contains(Flags.TRACED))
{
System.out.println("Timer " + toString() + " expired");
}
return true;
}
return false;
}
/**
* Retrieve the color for an output Variable.
* @return int; the color code for this Variable
* @throws TrafficControlException if this Variable is not an output
*/
public TrafficLightColor getColor() throws TrafficControlException
{
if (!this.flags.contains(Flags.IS_OUTPUT))
{
throw new TrafficControlException("Stream " + this.toString() + "is not an output");
}
return this.color;
}
/**
* Report whether a change in this variable must be published.
* @return boolean; true if this Variable is an output; false if this Variable is not an output
*/
public boolean isOutput()
{
return this.flags.contains(Flags.IS_OUTPUT);
}
/**
* Report of this Variable identifies the current conflict group.
* @return boolean; true if this Variable identifies the current conflict group; false if it does not.
*/
public boolean isConflictGroup()
{
return this.flags.contains(Flags.CONFLICT_GROUP);
}
/**
* Retrieve the rank of the conflict group that this Variable represents.
* @return int; the rank of the conflict group that this Variable represents
* @throws TrafficControlException if this Variable is not a conflict group identifier
*/
public int conflictGroupRank() throws TrafficControlException
{
if (!isConflictGroup())
{
throw new TrafficControlException("Variable " + this + " is not a conflict group identifier");
}
return rowLetters.indexOf(this.name.charAt(2));
}
/**
* Report if this Variable is a detector.
* @return boolean; true if this Variable is a detector; false if this Variable is not a detector
*/
public boolean isDetector()
{
return this.flags.contains(Flags.IS_DETECTOR);
}
/**
* @param newValue int; the new value of this Variable
* @param timeStamp10 int; the time stamp of this update
* @param cause CausePrinter; rule, timer, or detector that caused the change
* @param trafCODController TrafCOD; the TrafCOD controller
* @return boolean; true if the value of this variable changed
*/
public boolean setValue(final int newValue, final int timeStamp10, final CausePrinter cause,
final TrafCOD trafCODController)
{
boolean result = false;
if (this.value != newValue)
{
this.updateTime10 = timeStamp10;
setFlag(Flags.CHANGED);
if (0 == newValue)
{
setFlag(Flags.END);
result = true;
}
else if (!isTimer() || 0 == this.value)
{
setFlag(Flags.START);
result = true;
}
if (isOutput() && newValue != 0)
{
for (TrafficLight trafficLight : this.trafficLights)
{
trafficLight.setTrafficLightColor(this.color);
}
}
}
if (this.flags.contains(Flags.TRACED))
{
// System.out.println("Variable " + this.name + this.stream + " changes from " + this.value + " to " + newValue
// + " due to " + cause.toString());
trafCODController.fireTrafCODEvent(TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED,
new Object[] {trafCODController.getId(), toString(EnumSet.of(PrintFlags.ID)), this.stream, this.value,
newValue, cause.toString()});
}
this.value = newValue;
return result;
}
/**
* Copy the state of this variable from another variable. Only used when cloning the TrafCOD engine.
* @param fromVariable Variable; the variable whose state is copied
* @param newNetwork Network; the Network that contains the new traffic control engine
* @throws NetworkException when the clone of a traffic light of fromVariable does not exist in newNetwork
*/
public void cloneState(final Variable fromVariable, final Network newNetwork) throws NetworkException
{
this.value = fromVariable.value;
this.flags = EnumSet.copyOf(fromVariable.flags);
this.updateTime10 = fromVariable.updateTime10;
if (fromVariable.isOutput())
{
for (TrafficLight tl : fromVariable.trafficLights)
{
ObjectInterface clonedTrafficLight = newNetwork.getObjectMap().get(tl.getId());
if (null != clonedTrafficLight)
{
throw new NetworkException("newNetwork does not contain a clone of traffic light " + tl.getId());
}
if (clonedTrafficLight instanceof TrafficLight)
{
throw new NetworkException(
"newNetwork contains an object with name " + tl.getId() + " but this object is not a TrafficLight");
}
this.trafficLights.add((TrafficLight) clonedTrafficLight);
}
}
if (isOutput())
{
for (TrafficLight trafficLight : this.trafficLights)
{
trafficLight.setTrafficLightColor(this.color);
}
}
}
/**
* Retrieve the start value of this timer in units of 0.1 seconds (1 second is represented by the value 10).
* @return int; the timerMax10 value
* @throws TrafficControlException when this class is not a Timer
*/
public int getTimerMax() throws TrafficControlException
{
if (!this.isTimer())
{
throw new TrafficControlException("This is not a timer");
}
return this.timerMax10;
}
/**
* Retrieve the current value of this Variable.
* @return int; the value of this Variable
*/
public int getValue()
{
return this.value;
}
/**
* Set one flag.
* @param flag Flags; Flags
*/
public void setFlag(final Flags flag)
{
this.flags.add(flag);
}
/**
* Clear one flag.
* @param flag Flags; the flag to clear
*/
public void clearFlag(final Flags flag)
{
this.flags.remove(flag);
}
/**
* Report whether this Variable is a timer.
* @return boolean; true if this Variable is a timer; false if this variable is not a timer
*/
public boolean isTimer()
{
return this.flags.contains(Flags.IS_TIMER);
}
/**
* Clear the CHANGED flag of this Variable.
*/
public void clearChangedFlag()
{
this.flags.remove(Flags.CHANGED);
}
/**
* Increment the reference counter of this variable. The reference counter counts the number of rules where this variable
* occurs on the right hand side of the assignment operator.
*/
public void incrementReferenceCount()
{
this.refCount++;
}
/**
* Return a safe copy of the flags.
* @return EnumSet<Flags>
*/
public EnumSet getFlags()
{
return EnumSet.copyOf(this.flags);
}
/**
* Make this variable an output variable and set the color value.
* @param colorValue int; the output value (as used in the TrafCOD file)
* @throws TrafficControlException when the colorValue is invalid, or this method is called more than once for this variable
*/
public void setOutput(final int colorValue) throws TrafficControlException
{
if (null != this.color)
{
throw new TrafficControlException("setOutput has already been called for " + this);
}
if (null == this.trafficLights)
{
this.trafficLights = new LinkedHashSet<>();
}
// Convert the TrafCOD color value to the corresponding TrafficLightColor
TrafficLightColor newColor;
switch (colorValue)
{
case 'R':
newColor = TrafficLightColor.RED;
break;
case 'G':
newColor = TrafficLightColor.GREEN;
break;
case 'Y':
newColor = TrafficLightColor.YELLOW;
break;
default:
throw new TrafficControlException("Bad color value: " + colorValue);
}
this.color = newColor;
this.flags.add(Flags.IS_OUTPUT);
}
/**
* Add a traffic light to this variable.
* @param trafficLight TrafficLight; the traffic light to add
* @throws TrafficControlException when this variable is not an output
*/
public void addOutput(final TrafficLight trafficLight) throws TrafficControlException
{
if (!this.isOutput())
{
throw new TrafficControlException("Cannot add an output to an non-output variable");
}
this.trafficLights.add(trafficLight);
}
/**
* Set the maximum time of this timer.
* @param value10 int; the maximum time in 0.1 s
* @throws TrafficControlException when this Variable is not a timer
*/
public void setTimerMax(final int value10) throws TrafficControlException
{
if (!this.flags.contains(Flags.IS_TIMER))
{
throw new TrafficControlException(
"Cannot set maximum timer value of " + this.toString() + " because this is not a timer");
}
this.timerMax10 = value10;
}
/**
* Describe the rule that starts this variable.
* @return String
*/
public String getStartSource()
{
return this.startSource;
}
/**
* Set the description of the rule that starts this variable.
* @param startSource String; description of the rule that starts this variable
* @throws TrafficControlException when a start source has already been set
*/
public void setStartSource(final String startSource) throws TrafficControlException
{
if (null != this.startSource)
{
throw new TrafficControlException("Conflicting rules: " + this.startSource + " vs " + startSource);
}
this.startSource = startSource;
this.flags.add(Flags.HAS_START_RULE);
}
/**
* Describe the rule that ends this variable.
* @return String
*/
public String getEndSource()
{
return this.endSource;
}
/**
* Set the description of the rule that ends this variable.
* @param endSource String; description of the rule that ends this variable
* @throws TrafficControlException when an end source has already been set
*/
public void setEndSource(final String endSource) throws TrafficControlException
{
if (null != this.endSource)
{
throw new TrafficControlException("Conflicting rules: " + this.startSource + " vs " + endSource);
}
this.endSource = endSource;
this.flags.add(Flags.HAS_END_RULE);
}
/**
* Retrieve the stream to which this variable belongs.
* @return short; the stream to which this variable belongs
*/
public short getStream()
{
return this.stream;
}
/** {@inheritDoc} */
@Override
public String toString()
{
return "Variable [" + toString(EnumSet.of(PrintFlags.ID, PrintFlags.VALUE, PrintFlags.FLAGS)) + "]";
}
/**
* Convert selected fields to a String.
* @param printFlags EnumSet<PrintFlags>; the set of fields to convert
* @return String
*/
public String toString(final EnumSet printFlags)
{
StringBuilder result = new StringBuilder();
if (printFlags.contains(PrintFlags.ID))
{
if (this.flags.contains(Flags.IS_DETECTOR))
{
result.append("D");
}
else if (isTimer() && printFlags.contains(PrintFlags.INITTIMER))
{
result.append("I");
result.append(this.name);
}
else if (isTimer() && printFlags.contains(PrintFlags.REINITTIMER))
{
result.append("RI");
result.append(this.name);
}
else
{
result.append(this.name);
}
if (this.stream > 0)
{
// Insert the stream BEFORE the first digit in the name (if any); otherwise append
int pos;
for (pos = 0; pos < result.length(); pos++)
{
if (Character.isDigit(result.charAt(pos)))
{
break;
}
}
result.insert(pos, String.format("%02d", this.stream));
}
if (this.flags.contains(Flags.IS_DETECTOR))
{
result.append(this.name.substring(1));
}
if (printFlags.contains(PrintFlags.NEGATED))
{
result.append("N");
}
}
int printValue = Integer.MIN_VALUE; // That value should stand out if not changed by the code below this line.
if (printFlags.contains(PrintFlags.VALUE))
{
if (printFlags.contains(PrintFlags.NEGATED))
{
printValue = 0 == this.value ? 1 : 0;
}
else
{
printValue = this.value;
}
if (printFlags.contains(PrintFlags.S))
{
if (this.flags.contains(Flags.START))
{
printValue = 1;
}
else
{
printValue = 0;
}
}
if (printFlags.contains(PrintFlags.E))
{
if (this.flags.contains(Flags.END))
{
printValue = 1;
}
else
{
printValue = 0;
}
}
}
if (printFlags.contains(PrintFlags.VALUE) || printFlags.contains(PrintFlags.S) || printFlags.contains(PrintFlags.E)
|| printFlags.contains(PrintFlags.FLAGS))
{
result.append("<");
if (printFlags.contains(PrintFlags.VALUE) || printFlags.contains(PrintFlags.S) || printFlags.contains(PrintFlags.E))
{
result.append(printValue);
}
if (printFlags.contains(PrintFlags.FLAGS))
{
if (this.flags.contains(Flags.START))
{
result.append("S");
}
if (this.flags.contains(Flags.END))
{
result.append("E");
}
}
result.append(">");
}
if (printFlags.contains(PrintFlags.MODIFY_TIME))
{
result.append(String.format(" (%d.%d)", this.updateTime10 / 10, this.updateTime10 % 10));
}
return result.toString();
}
/** {@inheritDoc} */
@Override
public void notify(final EventInterface event) throws RemoteException
{
if (event.getType().equals(NonDirectionalOccupancySensor.NON_DIRECTIONAL_OCCUPANCY_SENSOR_TRIGGER_ENTRY_EVENT))
{
setValue(1, this.updateTime10, new CausePrinter("Detector became occupied"), this.trafCOD);
}
else if (event.getType().equals(NonDirectionalOccupancySensor.NON_DIRECTIONAL_OCCUPANCY_SENSOR_TRIGGER_EXIT_EVENT))
{
setValue(0, this.updateTime10, new CausePrinter("Detector became unoccupied"), this.trafCOD);
}
}
}
/**
* Class that can print a text version describing why a variable changed. Any work that has to be done (such as a call to
* TrafCOD.printRule
) is deferred until the toString
method is called.
*/
class CausePrinter
{
/** Object that describes the cause of the variable change. */
private final Object cause;
/**
* Construct a new CausePrinter object.
* @param cause Object; this should be either a String, or a Object[] that contains a tokenized TrafCOD rule.
*/
CausePrinter(final Object cause)
{
this.cause = cause;
}
@Override
public String toString()
{
if (this.cause instanceof String)
{
return (String) this.cause;
}
else if (this.cause instanceof Object[])
{
try
{
return TrafCOD.printRule((Object[]) this.cause, true);
}
catch (TrafficControlException exception)
{
exception.printStackTrace();
return ("printRule failed");
}
}
return this.cause.toString();
}
}
/**
* Flags for toString method of a Variable.
*/
enum PrintFlags
{
/** The name and stream of the Variable. */
ID,
/** The value of the Variable. */
VALUE,
/** Print "I" before the name (indicates that a timer is initialized). */
INITTIMER,
/** Print "RI" before the name (indicates that a timer is re-initialized). */
REINITTIMER,
/** Print value as "1" if just set, else print "0". */
S,
/** Print value as "1" if just reset, else print "0". */
E,
/** Print the negated Variable. */
NEGATED,
/** Print the flags of the Variable. */
FLAGS,
/** Print the time of last modification of the Variable. */
MODIFY_TIME,
}
/**
* Flags of a TrafCOD variable.
*/
enum Flags
{
/** Variable becomes active. */
START,
/** Variable becomes inactive. */
END,
/** Timer has just expired. */
TIMEREXPIRED,
/** Variable has just changed value. */
CHANGED,
/** Variable is a timer. */
IS_TIMER,
/** Variable is a detector. */
IS_DETECTOR,
/** Variable has a start rule. */
HAS_START_RULE,
/** Variable has an end rule. */
HAS_END_RULE,
/** Variable is an output. */
IS_OUTPUT,
/** Variable must be initialized to 1 at start of control program. */
INITED,
/** Variable is traced; all changes must be printed. */
TRACED,
/** Variable identifies the currently active conflict group. */
CONFLICT_GROUP,
}