package kaka.cakelight;
+import kaka.cakelight.mode.Mode;
+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
public class Console extends Thread {
+ private boolean running;
private CakeLight cakelight;
private Configuration config;
private Map<String, Command> commands = new HashMap<>();
private Console(CakeLight cakelight, Configuration config) {
this.cakelight = cakelight;
this.config = config;
- register(new HelpCommand());
+ register(Commands.help());
register(Commands.quit());
+ register(Commands.push());
+ register(Commands.pop());
register(Commands.video());
register(Commands.color());
register(Commands.brightness());
return config;
}
- private class HelpCommand implements Command {
- @Override
- public String[] getNames() {
- return new String[] {"?", "h", "help"};
- }
+ List<Command> getCommands() {
+ return commandList;
+ }
- @Override
- public void activate(Console console, String[] args) {
- for (Command c : commandList) {
- System.out.println(String.join("|", c.getNames()));
- }
- }
+ void quit() {
+ cakelight.turnOff();
+ running = false;
}
private void register(Command cmd) {
@Override
public void run() {
- while (true) {
- System.out.print("> ");
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
+ running = true;
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
+ while (running) {
+ System.out.print("> ");
String input = reader.readLine();
handleInput(input);
- } catch (IOException e) {
- System.out.println("Error reading from command line");
- break;
}
- }
+ } catch (IOException e) {
+ System.out.println("Error reading from command line");
+ }
}
void handleInput(String input) {
+ Object obj = internalHandleInput(input);
+ if (obj instanceof Mode) {
+ cakelight.setMode((Mode) obj);
+ }
+ }
+
+ Object internalHandleInput(String input) {
String[] splitInput = input.split("\\s+", 2);
String name = splitInput[0];
String[] args = splitInput.length == 2
Command cmd = commands.get(name);
if (cmd != null) {
- cmd.activate(this, args);
+ return cmd.activate(this, args);
} else {
out("no command named '" + name + "'");
}
+ return null;
}
void out(String text) {
public interface Command {
String[] getNames();
- void activate(Console console, String[] args);
+ Object activate(Console console, String[] args);
}
}