\ru\ifmo\alarm\controlled\Lights.java
|
package ru.ifmo.alarm.controlled;
import java.util.Timer;
import java.util.TimerTask;
import ru.ifmo.alarm.gui.AlarmFrame;
import com.evelopers.unimod.runtime.ControlledObject;
import com.evelopers.unimod.runtime.context.StateMachineContext;
public class Lights implements ControlledObject {
/**
* This flag is true if Lights are alight and false otherwise
*/
protected static boolean isOn = false; //lights are on. Static so that main frame can use it
/**
* This is a number of performed loops turning on/off lights
*/
private int loopsCounter = 0;
/**
* This is a number of required loops turning on/off lights
*/
private int loopsRequired = 0;
/**
* This is a timer controlling blinking period of the lights
*/
Timer timer;
/**
* Runs lights blinking
* @param loops number of blinking period
* @param period period time in milliseconds
*/
private void blink(int loops, long period) {
// TimerTask which schedules action of lights
TimerTask timerTask = new TimerTask() {
public void run() {
if (loopsCounter >= loopsRequired) {
if (isOn) {
// when fifnished, lights should be powered off
isOn = false;
AlarmFrame.alarmFrame.repaint();
}
timer.cancel();
return;
}
isOn = !isOn;
// repaint main window
AlarmFrame.alarmFrame.repaint();
loopsCounter++;
}
};
// cancel previous timer (if exists)
if (timer != null) {
timer.cancel();
}
timer = new Timer(false); //create new not daemon timer
loopsRequired = 2 * loops; //each period requires 2 runs: turning on and off
loopsCounter = 0; //reset loopsCounter
// blinking should be started with off lights
if (isOn) {
isOn = false;
AlarmFrame.alarmFrame.repaint();
}
timer.schedule(timerTask, 0, period); //start with 0 delay
}
/**
* Returns state of lights (turn on/off)
* @return true if lights are alight and false otherwise
*/
public static boolean isOn() {
return isOn;
}
/**
* @unimod.action.descr blink 1 time
* calling when alarm was turned on
*/
public void z1(StateMachineContext context) {
long ms = 500;
blink(1, ms);
}
/**
* @unimod.action.descr blink 2 times
* calling when alarm was turned off
*/
public void z2(StateMachineContext context) {
long ms = 400;
blink(2, ms);
}
/**
* @unimod.action.descr blink 3 times
* calling when car was easily hit
*/
public void z3(StateMachineContext context) {
long ms = 300;
blink(3, ms);
}
/**
* @unimod.action.descr start alarming
* full alarming mode
*/
public void z4(StateMachineContext context) {
long ms = 500;
blink(20000 / 500, ms); //blink for not more than 20sec with 500ms half-period
}
/**
* @unimod.action.descr stop blinking
*/
public void z5(StateMachineContext context) {
if (timer != null) {
timer.cancel();
}
}
}