Compare commits

..

No commits in common. "master" and "serialtesting" have entirely different histories.

22 changed files with 448 additions and 937 deletions

2
.gitignore vendored
View File

@ -1,2 +0,0 @@
/.classpath
/.project

View File

@ -1,10 +1,29 @@
package de.ctdo.crashtest;
import de.ctdo.crashtest.game.TheGame;
import de.ctdo.crashtest.gui.IGuiControl;
import de.ctdo.crashtest.gui.MainGui;
public class Steuerung {
private TheGame game;
private IGuiControl gui;
public static void main(String args[]) {
new TheGame(new MainGui());
new Steuerung();
}
public Steuerung() {
gui = new MainGui();
game = new TheGame(gui);
}
}

View File

@ -1,48 +1,42 @@
package de.ctdo.crashtest;
import de.ctdo.crashtest.domotics.BuntiClient;
import de.ctdo.crashtest.gui.GuiEventListener;
import de.ctdo.crashtest.gui.MainGui;
import de.ctdo.crashtest.domotics.IRelaisboard;
import de.ctdo.crashtest.domotics.Relaisboard;
import de.ctdo.crashtest.mpd.IMPDController;
import de.ctdo.crashtest.mpd.MPDController;
public class TestClass {
public TestClass() {
BuntiClient bunti = new BuntiClient("bunti.ctdo.de",8080);
public class TestClass {
int pause = 500;
try {
while(true) {
for(int i = 0; i< 3; i++) {
Thread.sleep(pause);
bunti.setLampel(true, false, true);
Thread.sleep(pause);
bunti.setLampel(false, true, true);
Thread.sleep(pause);
bunti.setLampel(false, false, true);
Thread.sleep(pause);
bunti.setLampel(false, false, false);
Thread.sleep(pause);
bunti.setLampel(true, true, true);
Thread.sleep(pause);
bunti.setLampel(false, false, true);
Thread.sleep(pause);
bunti.setLampel(true, true, true);
Thread.sleep(pause);
bunti.setLampel(false, false, false);
}
public static void main(String args[]) throws InterruptedException {
//Thread.sleep(2000);
}
}
catch (InterruptedException ignored) {}
IRelaisboard board = new Relaisboard("/dev/ttyUSB0");
board.open();
}
/*
board.setRelais(1,false);
//board.setRelais(1, true);
board.toggleRelais(1, 500);
Thread.sleep(1000);
board.toggleRelais(1, 500);
Thread.sleep(1000);
board.toggleRelais(1, 500);
//board.setRelais(1, false);
Thread.sleep(4000); */
board.blinkRelais(2, 500, 6); // hint Button
Thread.sleep(6000);
board.close();
public static void main(String args[]) {
new TestClass();
}
}

View File

@ -8,12 +8,11 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
public class BuntiClient implements IBuntiClient {
private final String baseAddress;
private String baseAddress;
private final HttpClient client = new DefaultHttpClient();
public BuntiClient(String server, int port) {
baseAddress = "http://" + server + ":" + port + "/";
@ -26,7 +25,6 @@ public class BuntiClient implements IBuntiClient {
@Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
@ -68,52 +66,6 @@ public class BuntiClient implements IBuntiClient {
new Thread(r).start();
}
@Override
public void setPar56(final int par, final int red, final int green, final int blue) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
StringBuilder jsonString = new StringBuilder();
jsonString.append("{ \"timeStamp\": 0, \"updates\": [ ");
jsonString.append(" {\"deviceId\": ");
jsonString.append(par);
jsonString.append(", \"options\": { \"red\": ");
jsonString.append(red);
jsonString.append(", \"green\": ");
jsonString.append(green);
jsonString.append(", \"blue\": ");
jsonString.append(blue);
jsonString.append(" } } ");
jsonString.append("] }");
StringEntity entity = new StringEntity( jsonString.toString(), "UTF-8");
post.setEntity(entity);
client.execute(post);
post.abort();
} catch (UnsupportedEncodingException e) {
Logger.sLog("bunti error: " + e.getMessage());
} catch (ClientProtocolException e) {
Logger.sLog("bunti error: " + e.getMessage());
} catch (IOException e) {
Logger.sLog("bunti error: " + e.getMessage());
}
}
};
new Thread(r).start();
}
@Override
public void setLampel(final boolean red, final boolean yellow, final boolean green) {
@ -126,13 +78,18 @@ public class BuntiClient implements IBuntiClient {
if( red ) value |= 0x04;
try {
byte buffer[] = ("io set port 2 " + Integer.toHexString(value) + '\n').getBytes();
Socket client = new Socket("lampel.ctdo.de", 2701);
client.setSoTimeout(800);
DatagramSocket udp = new DatagramSocket();
InetAddress ia = InetAddress.getByName("lampel.raum.ctdo.de");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ia, 2701);
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
udp.send(packet);
outToServer.writeBytes("io set port 2 " + Integer.toHexString(value) + '\n');
inFromServer.readLine();
client.close();
} catch (IOException e) {
Logger.sLog("lampel error: " + e.getMessage());
}
@ -141,6 +98,30 @@ public class BuntiClient implements IBuntiClient {
new Thread(r).start();
/* try {
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(
"{ \"timeStamp\": 0, \"updates\": [ {\"deviceId\": 4, \"options\": { \"red\": "+
red+", \"green\": "+green+", \"yellow\": "+yellow+" } } ] }" ,
"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println(response);
post.abort();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
}

View File

@ -1,45 +0,0 @@
package de.ctdo.crashtest.domotics;
import de.ctdo.crashtest.log.Logger;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class ExtraSoundControl implements IExtraSoundControl {
@Override
public void playJingle(final String name) {
System.out.println("ExtraSoundControl: playJingle name=" + name );
Runnable r = new Runnable() {
@Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://dampfradio.raum.ctdo.de/controller.php?command=jingle&mpd=mpd1&arg=" +name);
client.execute(get);
get.abort();
} catch (UnsupportedEncodingException e) {
Logger.sLog("ExtraSoundControl error: " + e.getMessage());
} catch (ClientProtocolException e) {
Logger.sLog("ExtraSoundControl error: " + e.getMessage());
} catch (IOException e) {
Logger.sLog("ExtraSoundControl error: " + e.getMessage());
}
}
};
new Thread(r).start();
}
}

View File

@ -1,8 +1,11 @@
package de.ctdo.crashtest.domotics;
/**
* @author: lucas
* @date: 01.06.12 14:25
*/
public interface IBuntiClient {
void setPar56(final int red, final int green, final int blue);
void setPar56(final int par, final int red, final int green, final int blue);
void setLampel(final boolean red, final boolean yellow, final boolean green);
}

View File

@ -1,5 +0,0 @@
package de.ctdo.crashtest.domotics;
public interface IExtraSoundControl {
void playJingle(String name);
}

View File

@ -1,10 +1,11 @@
package de.ctdo.crashtest.domotics;
public interface IRelaisboard {
void setRelais(final int relais, final boolean state);
void toggleRelais(final int relais, final int milliseconds);
void blinkRelais(final int relais, final int pause);
void blinkRelaisStop(final int relais);
void open();
void blinkRelais(final int relais, final int pause, final int count);
boolean open();
void close();
}

View File

@ -4,54 +4,47 @@ import de.ctdo.crashtest.log.Logger;
import gnu.io.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Enumeration;
public class Relaisboard implements IRelaisboard {
private SerialPort serialPort;
private OutputStream outputStream;
private Boolean serialPortGeoeffnet = false;
private String portName = "/dev/ttyUSB0";
private final Object mLock = new Object();
private final Map<Integer,Thread> threadMap = new ConcurrentHashMap<Integer, Thread>();
private final Map<Integer,Boolean> stopMap = new ConcurrentHashMap<Integer, Boolean>();
private Object mLock = new Object();
public Relaisboard(final String port) {
this.portName = port;
}
private void sendData(final int relais, final boolean state) {
synchronized (mLock) {
if(relais >= 0 && relais < 8 && outputStream != null) {
char charsOff[] = { 'a','b','c','d','e','f','g','h' };
char charsOn[] = { 'A','B','C','D','E','F','G','H' };
if(relais >= 0 && relais < 8 && outputStream != null) {
char charsOff[] = { 'a','b','c','d','e','f','g','h' };
char charsOn[] = { 'A','B','C','D','E','F','G','H' };
try {
if(state) {
outputStream.write(charsOn[relais]);
} else {
outputStream.write(charsOff[relais]);
}
System.out.println("Relaisboard: sendData " + relais + " = " + state);
outputStream.flush();
} catch (IOException e) {
Logger.sLog("Relaisboard error: Fehler beim Senden");
try {
if(state) {
outputStream.write(charsOn[relais]);
} else {
outputStream.write(charsOff[relais]);
}
outputStream.flush();
} catch (IOException e) {
Logger.sLog("Fehler beim Senden");
}
}
}
@Override
public void open() {
public boolean open() {
serialPortGeoeffnet = false;
Boolean foundPort = false;
if (serialPortGeoeffnet) {
if (serialPortGeoeffnet != false) {
Logger.sLog("Serialport bereits geöffnet");
return;
return false;
}
Enumeration enumComm = CommPortIdentifier.getPortIdentifiers();
@ -64,9 +57,9 @@ public class Relaisboard implements IRelaisboard {
break;
}
}
if (!foundPort) {
if (foundPort != true) {
Logger.sLog("Serialport nicht gefunden: " + portName);
return;
return false;
}
try {
@ -77,109 +70,99 @@ public class Relaisboard implements IRelaisboard {
outputStream = serialPort.getOutputStream();
serialPortGeoeffnet = true;
return true;
} catch (PortInUseException e) {
Logger.sLog("Relaisboard error: Port belegt " + portName);
Logger.sLog("Port belegt");
} catch (IOException e) {
Logger.sLog("Relaisboard error: Keinen Zugriff auf OutputStream");
Logger.sLog("Keinen Zugriff auf OutputStream");
} catch(UnsupportedCommOperationException e) {
Logger.sLog("Relaisboard error: Konnte Schnittstellen-Paramter nicht setzen");
Logger.sLog("Konnte Schnittstellen-Paramter nicht setzen");
}
return false;
}
@Override
public void close() {
if ( serialPortGeoeffnet ) {
serialPort.close();
serialPortGeoeffnet = false;
outputStream = null;
}
serialPortGeoeffnet = false;
outputStream = null;
}
@Override
public void setRelais(final int relais, final boolean state) {
if(!serialPortGeoeffnet) return;
stopRelaisThread(relais);
synchronized (mLock) {
Runnable r = new Runnable() {
@Override
public void run() {
sendData(relais, state);
}
};
Runnable r = new Runnable() {
@Override
public void run() {
sendData(relais, state);
}
};
new Thread(r).start();
new Thread(r).start();
}
}
@Override
public void toggleRelais(final int relais, final int milliseconds) {
if(!serialPortGeoeffnet) return;
stopRelaisThread(relais);
Runnable r = new Runnable() {
@Override
public void run() {
sendData(relais, true);
try {
Thread.sleep(milliseconds);
} catch (InterruptedException ignored) { }
sendData(relais, false);
}
};
new Thread(r).start();
}
@Override
public void blinkRelais(final int relais, final int pause) {
if(!serialPortGeoeffnet) return;
stopRelaisThread(relais);
Runnable r = new Runnable() {
@Override
public void run() {
while(true) {
synchronized (mLock) {
Runnable r = new Runnable() {
@Override
public void run() {
sendData(relais, true);
try {
Thread.sleep(pause);
} catch (InterruptedException ignored) { }
if(stopMap.get(relais)) return;
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendData(relais, false);
try {
Thread.sleep(pause);
} catch (InterruptedException ignored) { }
if(stopMap.get(relais)) return;
}
}
};
};
stopMap.put(relais, false);
Thread thread = new Thread(r);
threadMap.put(relais,thread);
thread.start();
new Thread(r).start();
}
}
@Override
public void blinkRelaisStop(final int relais) {
stopRelaisThread(relais);
}
public void blinkRelais(final int relais, final int pause, final int count) {
if(!serialPortGeoeffnet) return;
private void stopRelaisThread(final int relais) {
Thread thread = threadMap.get(relais);
synchronized (mLock) {
Runnable r = new Runnable() {
@Override
public void run() {
int i;
if(thread != null) {
stopMap.put(relais, true);
thread.interrupt();
threadMap.remove(relais);
for(i = 0; i< count; i++) {
sendData(relais, true);
try {
Thread.sleep(pause);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendData(relais, false);
try {
Thread.sleep(pause);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
new Thread(r).start();
}
}
}

View File

@ -4,12 +4,12 @@ public interface IStatemachine {
void addListener(StatemachineListener listener);
void reset();
Statemachine.state getCurrentState();
Statemachine.state getLastState();
void setNewState(Statemachine.state newState);
int getStateChangeCounter();
void handleInput(char input);
int getTimerSecondsLeft();
int getTimerSeconds();
int getTimerSecondsLast();
void startTimer(int seconds);
void stopTimer();
void pauseTimer(boolean pause);

View File

@ -1,5 +1,7 @@
package de.ctdo.crashtest.game;
import de.ctdo.crashtest.log.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
@ -16,28 +18,26 @@ public class Statemachine implements IStatemachine {
TABLE_GAME_FIVE,
TABLE_GAME_SIX,
TABLE_GAME_DONE,
TABLE_GAME_WRONG,
ROKET_STARTED,
ROKET_DONE,
NEUTRAL
ROKET_DONE
}
public static final char BLUE_BUTTON = 'E';
public static final char LIGHT_BARRIER = 'F';
public static final char TABLE_ONE = 'G';
public static final char TABLE_TWO = 'H';
public static final char TABLE_THREE = 'I';
public static final char ROKET_INPUT = 'B';
private final char RESET = '1';
private final char BLUE_BUTTON = 'E';
private final char LIGHT_BARRIER = 'F';
private final char TABLE_ONE = 'G';
private final char TABLE_TWO = 'H';
private final char TABLE_THREE = 'I';
private final char ROKET_INPUT = 'B';
private final List<StatemachineListener> statemachineListenerList;
private Timer timer;
private long lastHandleInput;
private int stateChangeCounter;
private state lastState;
private state currentState;
private int timertSecondsLeft;
private int timertSeconds;
private int timertSecondsLast;
public Statemachine() {
currentState = state.IDLE;
@ -54,11 +54,6 @@ public class Statemachine implements IStatemachine {
return currentState;
}
@Override
public state getLastState() {
return lastState;
}
@Override
public void setNewState(state newState) {
currentState = newState;
@ -86,8 +81,9 @@ public class Statemachine implements IStatemachine {
state newState = getNewState(input);
if( newState != currentState ) {
lastState = currentState;
stateChangeCounter++;
Logger.sLog("newState = " + newState);
currentState = newState;
onStateChanged();
}
@ -96,31 +92,27 @@ public class Statemachine implements IStatemachine {
}
@Override
public int getTimerSecondsLeft() {
return timertSecondsLeft / 10;
}
@Override
public int getTimerSeconds() {
return timertSeconds / 10;
public int getTimerSecondsLast() {
return timertSecondsLast / 10;
}
@Override
public void startTimer(int seconds) {
timertSecondsLeft = seconds*10;
timertSeconds = seconds*10;
Logger.sLog("starting timer");
timertSecondsLast = seconds*10;
scheduleTimer();
}
@Override
public void stopTimer() {
Logger.sLog("stopping timer");
if(timer != null) timer.cancel();
timertSecondsLeft = 0;
timertSeconds = 0;
timertSecondsLast = 0;
}
@Override
public void pauseTimer(boolean pause) {
Logger.sLog("pausing timer: " + pause);
if(pause) {
if(timer != null) timer.cancel();
} else {
@ -140,7 +132,7 @@ public class Statemachine implements IStatemachine {
private void onTimerTick() {
for(StatemachineListener listener: statemachineListenerList) {
listener.timerTick(timertSecondsLeft);
listener.timerTick(timertSecondsLast);
}
}
@ -152,78 +144,77 @@ public class Statemachine implements IStatemachine {
private state getNewState(char input) {
state retVal = currentState;
switch (currentState) {
case IDLE:
if(input == LIGHT_BARRIER) {
retVal = state.ENTERED_ROOM;
}
break;
case ENTERED_ROOM:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_ONE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_TWO;
} else if (input == TABLE_THREE) {
retVal = state.TABLE_GAME_WRONG;
}
break;
case TABLE_GAME_TWO:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_THREE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_WRONG;
}
break;
case TABLE_GAME_THREE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_FOUR;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_WRONG;
}
break;
case TABLE_GAME_FOUR:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_FIVE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_WRONG;
}
break;
case TABLE_GAME_FIVE:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_SIX;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_WRONG;
}
break;
case TABLE_GAME_SIX:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_DONE;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_WRONG;
}
break;
case TABLE_GAME_DONE:
if(input == BLUE_BUTTON) {
retVal = state.ROKET_STARTED;
}
break;
case TABLE_GAME_WRONG:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case ROKET_STARTED:
if(input == ROKET_INPUT) {
retVal = state.ROKET_DONE;
}
if(input == RESET) {
retVal = state.IDLE;
} else {
switch (currentState) {
case IDLE:
if(input == LIGHT_BARRIER) {
retVal = state.ENTERED_ROOM;
}
break;
case ENTERED_ROOM:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_ONE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_TWO;
}
break;
case TABLE_GAME_TWO:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_THREE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_THREE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_FOUR;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_FOUR:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_FIVE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_FIVE:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_SIX;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_SIX:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_DONE;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_DONE:
if(input == BLUE_BUTTON) {
retVal = state.ROKET_STARTED;
}
break;
case ROKET_STARTED:
if(input == ROKET_INPUT) {
retVal = state.ROKET_DONE;
}
}
}
return retVal;
}
private void scheduleTimer() {
if(timer != null) timer.cancel();
@ -232,15 +223,18 @@ public class Statemachine implements IStatemachine {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
timertSecondsLeft--;
timertSecondsLast--;
onTimerTick();
if(timertSecondsLeft <= 0) {
if(timertSecondsLast <= 0) {
if(timer != null) timer.cancel();
}
}
};
timer.scheduleAtFixedRate(timerTask, 100, 100);
}
}

View File

@ -6,43 +6,37 @@ import de.ctdo.crashtest.irc.*;
import de.ctdo.crashtest.mpd.IMPDController;
import de.ctdo.crashtest.mpd.MPDController;
import java.util.Random;
public class TheGame implements StatemachineListener, GuiEventListener, IRCEventListener {
private final IGuiControl guiControl;
private final IIrcClient ircClient;
private final IStatemachine machine;
private final IBuntiClient bunti;
private final IMPDController mpdController;
private final IRelaisboard relaisboard;
private final IExtraSoundControl extraSoundControl;
private int gamerRating = 3;
private Thread discoThread;
private boolean shouldStopDisco;
private boolean gemActivated = false;
private int gemCounter = 0;
private boolean startedHurrySound = false;
private char lastInput;
private boolean sproing;
private IGuiControl guiControl;
private IIrcClient ircClient;
private IStatemachine machine;
private IBuntiClient bunti;
private IMPDController mpdController;
private IRelaisboard relaisboard;
public TheGame(IGuiControl guiControl1) {
guiControl = guiControl1;
ircClient = new IrcClient("crashtest", "#crashtest","irc.ctdo.de");
bunti = new BuntiClient("bunti.ctdo.de", 8080);
mpdController = new MPDController("dampfradio.raum.ctdo.de");
relaisboard = new Relaisboard("/dev/ttyUSB0");
machine = new Statemachine();
extraSoundControl = new ExtraSoundControl();
public TheGame(IGuiControl guiControl) {
this.guiControl = guiControl;
this.ircClient = new IrcClient("crashtest", "#crashtest","irc.hackint.eu");
this.bunti = new BuntiClient("bunti.ctdo.de", 8080);
this.mpdController = new MPDController("dampfradio.raum.ctdo.de");
this.relaisboard = new Relaisboard("/dev/ttyUSB0");
this.machine = new Statemachine();
initGame();
}
private void initGame() {
guiControl.addListener(this);
ircClient.addListener(this);
machine.addListener(this);
machine.reset();
relaisboard.open();
resetDomotics();
relaisboard.toggleRelais(2, 2000);
}
/**
* Event listener for state change events from statemachine
* @param newState the new game state from statemachine
@ -50,242 +44,130 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
@Override
public void stateChanged(Statemachine.state newState) {
ircClient.say("New State: " + newState);
ircClient.say("New State: " + newState);
switch (newState) {
case NEUTRAL:
discoStop();
bunti.setPar56(255,255,255);
bunti.setLampel(false,false,false);
machine.stopTimer();
break;
case IDLE:
gamerRating = 3;
mpdController.clearPlaylist();
machine.stopTimer();
startedHurrySound = false;
resetDomotics();
discoStop();
guiControl.setExtra("");
guiControl.setWall("");
guiControl.showCountDown(false);
playRandomStartMix();
//mpdController.setVolume(50);
mpdController.setVolume(45);
mpdController.playSong("start", "mix");
bunti.setPar56(0,0,0);
bunti.setLampel(false,false,false);
guiControl.showCountDown(false);
break;
case ENTERED_ROOM:
relaisboard.setRelais(7, false); // disable light barrier over relais
mpdController.playSong("crashtest", "entered_room");
mpdController.setVolume(70);
mpdController.playSong("tidirium", "welcome");
bunti.setLampel(false,false,false);
bunti.setPar56(20,0,100);
guiControl.setWall("bitte die tuer schliessen. dann kann das spiel beginnen.");
guiControl.showCountDown(true);
machine.startTimer(60*8);
mpdController.setVolume(50);
break;
case TABLE_GAME_WRONG:
extraSoundControl.playJingle("block");
if(!startedHurrySound) {
mpdController.playSong("crashtest", "table_game_one");
}
bunti.setLampel(true,false,false);
sproing = true;
break;
case TABLE_GAME_ONE:
relaisboard.setRelais(6, true); // enable third green circle
guiControl.setWall("64K RAM SYSTEM 38911 BASIC BYTES FREE. **** COMMODORE 64 BASIC V2 ****");
extraSoundControl.playJingle("jump");
mpdController.setVolume(70);
mpdController.playSong("K2", "Der Berg Ruft");
if(machine.getLastState() != Statemachine.state.TABLE_GAME_WRONG) {
if(!startedHurrySound) {
mpdController.playSong("crashtest", "table_game_one");
}
}
bunti.setLampel(false, true, false);
bunti.setPar56(20,0,100);
bunti.setLampel(true,false,false);
bunti.setPar56(255,0,100);
guiControl.showCountDown(true);
break;
case TABLE_GAME_TWO:
//mpdController.playSong("crashtest", "table_game_two");
extraSoundControl.playJingle("jump");
bunti.setLampel(false,true,false);
bunti.setPar56(100,0,100);
bunti.setPar56(255,0,100);
guiControl.showCountDown(true);
break;
case TABLE_GAME_THREE:
//mpdController.playSong("crashtest", "table_game_three");
extraSoundControl.playJingle("jump");
bunti.setLampel(false,true,false);
bunti.setPar56(255,35,0);
guiControl.showCountDown(true);
break;
case TABLE_GAME_FOUR:
if(!startedHurrySound) {
mpdController.playSong("crashtest", "table_game_four");
}
mpdController.setVolume(60);
mpdController.playSong("Mo-Do","9 Eins Zwei Polizei");
extraSoundControl.playJingle("jump");
bunti.setLampel(false,true,false);
bunti.setPar56(200,100,0);
bunti.setPar56(255,55,0);
guiControl.showCountDown(true);
break;
case TABLE_GAME_FIVE:
//mpdController.playSong("crashtest", "table_game_five");
extraSoundControl.playJingle("jump");
bunti.setLampel(false,true,false);
bunti.setPar56(150,150,0);
bunti.setPar56(255,75,0);
guiControl.showCountDown(true);
break;
case TABLE_GAME_SIX:
//mpdController.playSong("crashtest", "table_game_six");
mpdController.setVolume(60);
mpdController.playSong("Zlatko & Jürgen","Großer Bruder");
extraSoundControl.playJingle("jump");
bunti.setLampel(false,true,false);
bunti.setPar56(100,200,0);
bunti.setPar56(255,100,0);
guiControl.showCountDown(true);
break;
case TABLE_GAME_DONE:
mpdController.playSong("crashtest", "table_game_done");
extraSoundControl.playJingle("jump");
bunti.setLampel(false,false,true);
bunti.setPar56(100,255,0);
bunti.setPar56(255,100,0);
guiControl.showCountDown(true);
machine.pauseTimer(true);
// spieler haben 8 Minuten, wenn sie es in weniger als 4 minuten schaffen
// gibts +1, in weniger als 2 minuten gibts +2
if(machine.getTimerSecondsLeft() >= 6*60 ) {
rate(2, "table game faster than 2 minutes");
} else if(machine.getTimerSecondsLeft() > 4*60) {
rate(1, "table game faster than 4 minutes");
}
if(machine.getStateChangeCounter() > 100) {
rate(-1, "more than 100 tries");
}
sayScore();
relaisboard.setRelais(6, false); // disable third green circle
relaisboard.blinkRelais(2, 700); // hint Button
relaisboard.blinkRelais(2, 500, 6); // hint Button
break;
case ROKET_STARTED:
mpdController.playSong("crashtest", "roket_started");
mpdController.addToPlayList("crashtest", "roket_started2");
mpdController.setVolume(50);
mpdController.playSong("The Underdog Project", "Summer Jam");
startedHurrySound = false;
bunti.setLampel(false,true,false);
bunti.setLampel(false,false,true);
bunti.setPar56(0, 255, 0);
relaisboard.toggleRelais(0, 300); // r0kets toogle
relaisboard.toggleRelais(3, 10000); // oven
relaisboard.blinkRelaisStop(2); // stop hint button lamp
relaisboard.setRelais(2, false);
ircClient.say("table game complete, r0kets now");
relaisboard.toggleRelais(0, 300);
guiControl.setWall("Pizza ist fertig!");
guiControl.showCountDown(true);
machine.startTimer(7*60);
break;
case ROKET_DONE:
mpdController.playSong("crashtest", "roket_done");
//mpdController.setVolume(60);
mpdController.setVolume(50);
mpdController.playSong("Coldplay", "Amsterdam");
bunti.setLampel(false,false,true);
bunti.setPar56(255, 255, 255);
guiControl.setWall("willkommen im chaostreff dortmund");
bunti.setLampel(true,true,true);
bunti.setPar56(255, 196, 0);
guiControl.showCountDown(true);
machine.pauseTimer(true);
// spieler haben 7 Minuten, wenn sie es in weniger als 4 minuten schaffen
// gibts +1, in weniger als 2 minuten gibts +2
if(machine.getTimerSecondsLeft() >= 5*60 ) {
rate(2, "r0kets faster than 2 minutes");
} else if(machine.getTimerSecondsLeft() > 3*60) {
rate(1, "r0kets faster than 4 minutes");
}
sayScore();
discoStart();
break;
}
}
/**
* Event listener for timer ticks from statemachine.
* @param tsecondsLeft the seconds left on the current game
*/
@Override
public void timerTick(int tsecondsLeft) {
if(gemCounter>0) gemCounter--;
guiControl.setCountDown(tsecondsLeft);
if(tsecondsLeft == 0) {
ircClient.say("timer expired");
Statemachine.state state = machine.getCurrentState();
if( state == Statemachine.state.TABLE_GAME_ONE || state == Statemachine.state.TABLE_GAME_TWO ||
state == Statemachine.state.TABLE_GAME_THREE || state == Statemachine.state.TABLE_GAME_FOUR ||
state == Statemachine.state.TABLE_GAME_FIVE || state == Statemachine.state.TABLE_GAME_SIX ||
state == Statemachine.state.TABLE_GAME_WRONG || state == Statemachine.state.ROKET_STARTED ) {
rate(-2, "game not done in time");
guiControl.setWall("die Zeit ist abgelaufen");
sayScore();
mpdController.playSong("crashtest","timeouted");
if(state == Statemachine.state.ROKET_STARTED) {
relaisboard.toggleRelais(0, 300); // r0kets toogle (so there will probably be switched off)
ircClient.say("if ready, use >reset");
} else {
ircClient.say("if ready, set state with >state TABLE_GAME_DONE");
}
/*
if(state != Statemachine.state.ROKET_STARTED) {
ircClient.say("switching to roket started");
machine.setNewState(Statemachine.state.ROKET_STARTED);
} */
}
} else {
if(tsecondsLeft % 600 == 0) {
sayScore();
}
if(tsecondsLeft <= 630 && !startedHurrySound) {
Statemachine.state state = machine.getCurrentState();
if( state != Statemachine.state.TABLE_GAME_DONE &&
state != Statemachine.state.ROKET_DONE ) {
startedHurrySound = true;
mpdController.playSong("crashtest", "hurry");
}
}
}
if(tsecondsLeft == 0) ircClient.say("timer expired");
}
/**
* Event listener for keyPress events from the GUI
* @param key the pressed key
@ -293,24 +175,8 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
@Override
public void keyPress(char key) {
machine.handleInput(key);
//guiControl.setExtra("btn: " + key);
Statemachine.state state = machine.getCurrentState();
if(state == Statemachine.state.ENTERED_ROOM) {
if(key == Statemachine.TABLE_TWO || key == Statemachine.TABLE_THREE) {
if(lastInput != key) {
extraSoundControl.playJingle("block");
}
}
} else if(state == Statemachine.state.TABLE_GAME_WRONG) {
if(key == Statemachine.TABLE_ONE || key == Statemachine.TABLE_TWO || key == Statemachine.TABLE_THREE) {
if(lastInput != key && !sproing) {
extraSoundControl.playJingle("block");
}
sproing = false;
}
}
lastInput = key;
}
/**
@ -318,17 +184,10 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
*/
@Override
public void windowClosing() {
discoStop();
resetDomotics();
relaisboard.close();
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) { }
machine.reset();
bunti.setPar56(0xff,0xff,0xff);
ircClient.say("bye");
System.exit(0);
relaisboard.close();
}
/**
@ -351,26 +210,11 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
guiControl.setWall(message.substring("wall".length()).trim());
} else if(message.startsWith("extra")) {
guiControl.setExtra(message.substring("extra".length()).trim());
} else if(message.startsWith("relais")) {
handleRelaisCommand(message);
} else if(message.startsWith("disco on")) {
discoStart();
} else if(message.startsWith("disco off")) {
discoStop();
} else if(message.startsWith("gem")) {
handleGemCommand();
} else {
ircClient.say("y u no use valid command?");
}
}
private void rate(int rating, String text) {
gamerRating += rating;
ircClient.say("rated: " + rating + " (" + gamerRating + ") " + text);
if(gamerRating > 5) gamerRating = 5;
if(gamerRating < 1) gamerRating = 1;
}
private void handleTimerCommand(final String message) {
String params = message.substring("timer".length()).trim().toLowerCase();
@ -394,6 +238,7 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
} else if(params.startsWith("stop")) {
machine.stopTimer();
guiControl.showCountDown(false);
ircClient.say("timer stopped");
} else if(params.startsWith("pause")) {
machine.pauseTimer(true);
} else if(params.startsWith("resume")) {
@ -402,16 +247,18 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
}
private void handleStateCommand(final String message) {
if(message.trim().equals("state")) {
if(message.equals("state")) {
ircClient.say(machine.getCurrentState().name());
} else {
String params = message.substring("state".length()).trim().toLowerCase();
Boolean ok = false;
for(Statemachine.state st: Statemachine.state.values()) {
if(st.name().toLowerCase().equals(params)) {
String stateName = st.name().toLowerCase();
if(stateName.equals(params)) {
ok = true;
machine.setNewState(st);
ircClient.say("consider it done, sir!");
break;
}
}
@ -420,52 +267,9 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
}
}
// Yes, it makes no sense, but I want have it anyway. For more Spass am Geraet!
private void handleGemCommand() {
if (!gemActivated) {
if(gemCounter > 1200) return;
java.util.Random random = new java.util.Random();
int scry = random.nextInt(100);
if (scry >= 99) {
ircClient.say("Perfect Gem Activated");
} else if (scry >= 90) {
ircClient.say("Moooooooo!");
} else {
ircClient.say("Gem Activated");
}
gemCounter+=100;
} else {
ircClient.say("Gem Deactivated");
}
gemActivated = !gemActivated;
}
private void handleRelaisCommand(final String message) {
String params = message.substring("relais".length()).trim().toLowerCase();
if(params.startsWith("lamp on")) {
relaisboard.setRelais(2, true);
} else if(params.startsWith("lamp off")) {
relaisboard.setRelais(2, false);
} else if(params.startsWith("oven on")) {
relaisboard.setRelais(3, true);
} else if(params.startsWith("oven off")) {
relaisboard.setRelais(3, false);
} else if(params.startsWith("rokets")) {
relaisboard.toggleRelais(0, 300);
} else if(params.startsWith("lamp blink")) {
relaisboard.blinkRelais(2, 700);
} else if(params.startsWith("lamp stop")) {
relaisboard.blinkRelaisStop(2);
}
}
private void handleHelpCommand(final String message) {
if(message.equals("help")) {
ircClient.say("commands: help, reset, state, timer, wall, extra, score, relais, disco, gem");
ircClient.say("commands: help, reset, state, timer, wall, extra, score");
} else if(message.contains("reset")) {
ircClient.say("resets the game to IDLE");
} else if(message.contains("state")) {
@ -498,120 +302,24 @@ public class TheGame implements StatemachineListener, GuiEventListener, IRCEvent
ircClient.say("set small extra message on the screen");
} else if(message.contains("score")) {
ircClient.say("i will tell you the current game score");
} else if(message.contains("relais")) {
ircClient.say("control the relais board");
ircClient.say("valid commands: lamp on, lamp off, lamp blink, lamp stop, oven on, oven off, rokets");
} else if(message.contains("disco")) {
ircClient.say("party! use: disco {on,off}");
} else if(message.contains("gem")) {
ircClient.say("The chat gem is working as intended.");
} else {
ircClient.say("dafuq?");
}
}
private void sayScore() {
StringBuilder sb = new StringBuilder();
sb.append("st.ch.: ");
sb.append(machine.getStateChangeCounter());
sb.append(" rating: ");
sb.append(gamerRating);
int secondsLeft = machine.getTimerSecondsLeft();
int seconds = machine.getTimerSeconds();
int secondsUsed = seconds - secondsLeft;
ircClient.say("stateChangeCounter: " + machine.getStateChangeCounter());
// ircClient.say("timerlast: " + machine.getTimerSecondsLast());
int seconds = machine.getTimerSecondsLast();
int mins = seconds / 60;
int minsUsed = secondsUsed / 60;
int minsLeft = secondsLeft / 60;
int secs = seconds % 60;
ircClient.say(" " + mins + ":" + secs + "");
sb.append(String.format(" time:%d:%02d u:%d:%02d l:%d:%02d",
mins, seconds % 60, minsUsed, secondsUsed % 60, minsLeft, secondsLeft % 60));
ircClient.say(sb.toString());
}
private void resetDomotics() {
relaisboard.setRelais(7, true); // enable light barrier over relais
relaisboard.setRelais(6, true); // enable third green circle
relaisboard.setRelais(2, false); // disable the lamp
relaisboard.setRelais(3, false); // disable the oven
bunti.setPar56(0, 0, 0);
bunti.setLampel(false, false, false);
}
private void discoStop() {
if(discoThread != null) {
shouldStopDisco = true;
discoThread.interrupt();
try {
discoThread.join(500);
} catch (InterruptedException ignored) { }
}
}
private void discoStart() {
discoStop();
Runnable r = new Runnable() {
@Override
public void run() {
try {
while(true) {
if(shouldStopDisco) return;
bunti.setPar56(0, 255, 0, 0);
bunti.setPar56(1, 0, 255, 0);
bunti.setPar56(2, 0, 255, 0);
bunti.setPar56(3, 255, 0, 0);
bunti.setLampel(true, false, false);
if(shouldStopDisco) return;
Thread.sleep(500);
bunti.setPar56(0, 0, 0, 255);
bunti.setPar56(1, 255, 255, 0);
bunti.setPar56(2, 255, 255, 0);
bunti.setPar56(3, 0, 0, 255);
bunti.setLampel(false, true, false);
if(shouldStopDisco) return;
Thread.sleep(500);
bunti.setPar56(0, 255, 128, 0);
bunti.setPar56(1, 0, 255, 255);
bunti.setPar56(2, 0, 255, 255);
bunti.setPar56(3, 255, 128, 0);
bunti.setLampel(false, false, true);
if(shouldStopDisco) return;
Thread.sleep(500);
bunti.setPar56(0, 0, 255, 255);
bunti.setPar56(1, 0, 255, 0);
bunti.setPar56(2, 0, 255, 0);
bunti.setPar56(3, 0, 255, 255);
bunti.setLampel(true, true, true);
if(shouldStopDisco) return;
Thread.sleep(500);
}
} catch (InterruptedException ignored) { }
}
};
discoThread = new Thread(r);
shouldStopDisco = false;
discoThread.start();
}
private void playRandomStartMix() {
Random r = new Random();
int num = r.nextInt(3)+1;
if(num == 1) {
mpdController.playSong("crashtest", "idle");
} else if(num == 2) {
mpdController.playSong("crashtest", "idle2");
} else if(num == 3) {
mpdController.playSong("crashtest", "idle3");
} else if(num == 4) {
mpdController.playSong("crashtest", "idle4");
}
mpdController.skipRandomStart();
}
}

View File

@ -1,6 +1,14 @@
package de.ctdo.crashtest.gui;
import java.awt.event.KeyEvent;
/**
* @author: lucas
* @date: 01.06.12 10:29
*/
public interface GuiEventListener {
void keyPress(final char key);
void windowClosing();
}

View File

@ -1,9 +1,17 @@
package de.ctdo.crashtest.gui;
/**
* @author: lucas
* @date: 01.06.12 10:13
*/
public interface IGuiControl {
void setWall(final String message);
void setExtra(final String text);
void setCountDown(final int tseconds);
void showCountDown(final Boolean show);
void addListener(final GuiEventListener listener);
}

View File

@ -3,7 +3,6 @@ package de.ctdo.crashtest.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
@ -12,20 +11,17 @@ public class MainGui extends JFrame implements IGuiControl {
private final JLabel countDown = new JLabel();
private final JLabel extraField = new JLabel();
private final JPanel lowerPanel = new JPanel();
private final List<GuiEventListener> listenerList = new ArrayList<GuiEventListener>();
public MainGui() {
initGui();
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setBounds(0,0, 1280, 1024);
setBounds(0,0, 1280, 1024);
setExtendedState(Frame.MAXIMIZED_BOTH);
setUndecorated(true);
setCursor(getToolkit().createCustomCursor( new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB),
new Point(0, 0), "null"));
textWall.setCursor(getToolkit().createCustomCursor( new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB),
new Point(0, 0), "null"));
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
@ -37,10 +33,10 @@ public class MainGui extends JFrame implements IGuiControl {
}
});
addWindowListener(new WindowAdapter() {
addWindowStateListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
for (GuiEventListener listener : listenerList) {
for(GuiEventListener listener: listenerList) {
listener.windowClosing();
}
}
@ -50,25 +46,33 @@ public class MainGui extends JFrame implements IGuiControl {
}
private void setCountDownText(final int tseconds) {
countDown.setText(String.format(" %d:%02d.%1d", tseconds / 600, tseconds % 600 / 10, tseconds % 9));
int mins = tseconds / 600;
int secs = tseconds % 600 / 10 ;
int tsecs = tseconds % 9;
countDown.setText(" " + mins + ":" + secs + "." + tsecs);
if(tseconds < 400) {
double percentile = ((tseconds-100.0)/300.0);
double red = 255.0 - percentile * 255.0;
double green = 255.0 - red;
double blue = percentile * 100.0;
// System.out.println("red= " + red + " green=" + green + " blue="+blue);
if(red > 255) red = 255;
if(red < 0) red = 0;
if(green > 255) green = 255;
if(green < 0) green = 0;
if(blue > 255) blue = 255;
if(blue < 0) blue = 0;
Color fColor = new Color((int)red,(int)green, 0);
Color fColor = new Color((int)red,(int)green, (int)blue);
countDown.setForeground(fColor);
}
else {
countDown.setForeground(new Color(42, 190, 0));
countDown.setForeground(new Color(0x00, 190, 100));
}
}
private void initGui() {
@ -83,7 +87,7 @@ public class MainGui extends JFrame implements IGuiControl {
Font wallFont = new Font("Arcade Interlaced", Font.PLAIN, 66);
Font lowerFont = new Font("Arcade Interlaced", Font.PLAIN, 80);
Color fontColor = new Color(42, 190, 0);
Color fontColor = new Color(0x00, 190, 100);
textWall.setFont(wallFont);
textWall.setForeground(fontColor);
@ -93,7 +97,6 @@ public class MainGui extends JFrame implements IGuiControl {
textWall.setWrapStyleWord(true);
textWall.setFocusable(false);
countDown.setFont(lowerFont);
countDown.setHorizontalAlignment(SwingConstants.LEFT);
countDown.setForeground(fontColor);
@ -125,8 +128,7 @@ public class MainGui extends JFrame implements IGuiControl {
final Runnable runnable = new Runnable() {
@Override
public void run() {
String txt = text.substring(0, Math.min(text.length(), 8));
extraField.setText(txt + " ");
extraField.setText(text + " ");
}
};
@ -162,4 +164,6 @@ public class MainGui extends JFrame implements IGuiControl {
listenerList.add(listener);
}
}

View File

@ -1,5 +1,9 @@
package de.ctdo.crashtest.irc;
/**
* @author: lucas
* @date: 01.06.12 10:05
*/
public interface IIrcClient {
void say(String message);
void addListener(IRCEventListener listenerIRC);

View File

@ -1,5 +1,9 @@
package de.ctdo.crashtest.irc;
/**
* @author: lucas
* @date: 01.06.12 11:49
*/
public interface IRCEventListener {
void handleMessage(final String message);

View File

@ -20,7 +20,7 @@ import java.util.List;
*/
public class IrcClient implements IIrcClient, jerklib.events.listeners.IRCEventListener, ILogger {
private final List<IRCEventListener> listenerListIRC = new ArrayList<IRCEventListener>();
private final Session ircsession;
private Session ircsession;
private final String channel;
public IrcClient(String nick, String channel, String server) {
@ -49,14 +49,8 @@ public class IrcClient implements IIrcClient, jerklib.events.listeners.IRCEventL
String message = cme.getMessage();
final String nick = ircsession.getNick();
if(message.startsWith(nick) || message.startsWith(">")) {
if(message.startsWith(nick)) {
message = message.substring(Math.max(nick.length(), message.indexOf(":")+1));
}
else {
message = message.substring(1);
}
if(message.contains(nick)) {
message = message.substring(Math.max(nick.length(), message.indexOf(":")+1));
message = message.trim();
for(IRCEventListener listenerIRC : listenerListIRC) {

View File

@ -1,5 +1,10 @@
package de.ctdo.crashtest.log;
/**
* @author: lucas
* @date: 01.06.12 16:46
*/
public interface ILogger {
void log(String message);
}

View File

@ -20,7 +20,7 @@ public class Logger {
return instance;
}
private void log(String message) {
public void log(String message) {
System.out.println("LOG: " + message);

View File

@ -1,9 +1,10 @@
package de.ctdo.crashtest.mpd;
/**
* @author: lucas
* @date: 01.06.12 10:36
*/
public interface IMPDController {
void playSong(final String artist, final String title);
void setVolume(final int volume);
void clearPlaylist();
void addToPlayList(final String artist, final String title);
void skipRandomStart();
}

View File

@ -12,10 +12,8 @@ import org.bff.javampd.exception.MPDPlaylistException;
import org.bff.javampd.objects.MPDSong;
import java.net.UnknownHostException;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A MPD abstraction to the org.bff.javampd library
@ -41,152 +39,68 @@ public class MPDController implements IMPDController {
*/
@Override
public void playSong(final String artist, final String title) {
System.out.println("playSong: " + artist + " - " + title);
if(mpd != null) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (mpd) {
addToPlayListIfNeeded(artist, title);
try {
doPlaySong(artist,title);
}
}
};
//new Thread(r).start();
r.run();
}
}
private void doPlaySong(final String artist, final String title) {
try {
MPDPlaylist playlist = mpd.getMPDPlaylist();
MPDPlayer player = mpd.getMPDPlayer();
int tries = 3;
while(tries>0) {
addToPlayListIfNeeded(artist, title);
for(MPDSong song: playlist.getSongList()) {
if(checkSong(song, artist, title)) {
System.out.println("MPD: stopping, playing, go...");
player.stop();
player.playId(song);
break;
}
}
// now check, if it is playing
MPDSong song = player.getCurrentSong();
if(checkSong(song, artist, title)) {
System.out.println("MPD: song is correctly playing");
return;
} else {
System.out.println("MPD: wrong track is playing");
}
System.out.println("MPD: next try");
tries--;
}
Logger.sLog("MPD error: track not in playlist or not found... cannot play");
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlayerException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
}
private boolean checkSong(final MPDSong song, final String artist, final String title) {
if(song != null) {
if(song.getArtist() != null && song.getTitle() != null) {
if(song.getArtist().getName().toLowerCase().contentEquals(artist.toLowerCase()) &&
song.getTitle().toLowerCase().contentEquals(title.toLowerCase())) {
return true;
}
} else {
System.out.println("MPD: song is nullb");
}
} else {
System.out.println("MPD: track title or artist is null " + artist + " - " + title);
}
return false;
}
/**
* Add a song to current mpd playlist
* @param artist Artist of the track to play
* @param title Title of the track to play
*/
@Override
public void addToPlayList(final String artist, final String title) {
if(mpd != null) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (mpd) {
MPDDatabase db = mpd.getMPDDatabase();
MPDPlaylist playlist = mpd.getMPDPlaylist();
try {
List<MPDSong> tracks = new ArrayList<MPDSong>(db.findArtist(artist));
for(MPDSong song: playlist.getSongList()) {
for(MPDSong song: tracks) {
if(song.getName() != null && song.getName().toLowerCase().contains(title.toLowerCase())) {
playlist.addSong(song);
if(song.getArtist() != null && song.getTitle() != null) {
if(song.getArtist().getName().toLowerCase().equals(artist.toLowerCase()) &&
song.getTitle().toLowerCase().equals(title.toLowerCase())) {
MPDPlayer player = mpd.getMPDPlayer();
player.stop();
player.playId(song);
break;
}
}
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDDatabaseException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlaylistException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlayerException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
}
};
//new Thread(r).start();
r.run();
synchronized (mpd) {
new Thread(r).start();
}
}
}
@Override
public void skipRandomStart() {
if(mpd != null) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (mpd) {
MPDPlayer player = mpd.getMPDPlayer();
private void addToPlayListIfNeeded(final String artist, final String title) {
MPDDatabase db = mpd.getMPDDatabase();
MPDPlaylist playlist = mpd.getMPDPlaylist();
try {
int length;
MPDSong song = player.getCurrentSong();
if(song!= null) {
length = song.getLength();
int skip = new Random().nextInt(length/2)+10;
player.seek(skip);
}
} catch (MPDConnectionException e) {
e.printStackTrace();
} catch (MPDPlayerException e) {
e.printStackTrace();
}
try {
List<MPDSong> tracks = new ArrayList<MPDSong>(db.findArtist(artist));
for(MPDSong song: tracks) {
if(song.getName() != null &&
song.getName().toLowerCase().contains(title.toLowerCase())) {
if(!playlist.getSongList().contains(song)) {
playlist.addSong(song);
}
break;
}
};
}
//new Thread(r).start();
r.run();
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDDatabaseException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlaylistException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
}
@ -197,85 +111,23 @@ public class MPDController implements IMPDController {
@Override
public void setVolume(final int volume) {
if(mpd != null) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (mpd) {
try {
mpd.getMPDPlayer().setVolume(volume);
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlayerException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
}
}
};
//new Thread(r).start();
r.run();
}
}
/**
* Clears the current mpd playlist
*/
@Override
public void clearPlaylist() {
if(mpd != null) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (mpd) {
try {
MPDPlaylist playlist = mpd.getMPDPlaylist();
playlist.clearPlaylist();
mpd.getMPDPlayer().setRandom(false);
mpd.getMPDPlayer().setXFade(1);
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlaylistException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlayerException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
try {
mpd.getMPDPlayer().setVolume(volume);
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlayerException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
}
};
//new Thread(r).start();
r.run();
}
}
private void addToPlayListIfNeeded(final String artist, final String title) {
MPDDatabase db = mpd.getMPDDatabase();
MPDPlaylist playlist = mpd.getMPDPlaylist();
int count;
for(count = 0; count < 3; count++) {
try {
List<MPDSong> tracks = new ArrayList<MPDSong>(db.findArtist(artist));
for(MPDSong song: tracks) {
if(song.getName() != null && song.getName().toLowerCase().contains(title.toLowerCase())) {
if(!playlist.getSongList().contains(song)) {
playlist.addSong(song);
}
break;
}
}
return;
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDDatabaseException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDPlaylistException e) {
Logger.sLog("MPD error: " + e.getMessage());
synchronized (mpd) {
new Thread(r).start();
}
}
}
}