SpinController

This commit is contained in:
Imbus 2024-11-03 16:17:47 +01:00
parent f3a839e4d0
commit af173df69d

View file

@ -2,41 +2,71 @@ package wash.control;
import actor.ActorThread; import actor.ActorThread;
import wash.io.WashingIO; import wash.io.WashingIO;
import wash.io.WashingIO.Spin; import wash.control.WashingMessage.Order;
public class SpinController extends ActorThread<WashingMessage> { public final class SpinController extends ActorThread<WashingMessage> {
private WashingIO io;
// TODO: add attributes private Spin spin = new Spin();
private WashingMessage m;
public SpinController(WashingIO io) { public SpinController(WashingIO io) {
// TODO this.io = io;
}
protected void sendAck() {
m.sendAck(this);
} }
@Override @Override
public void run() { public void run() {
spin.start();
// this is to demonstrate how to control the barrel spin: listener(); // Drop into a recursive listener method
// io.setSpinMode(Spin.IDLE);
try {
// ... TODO ...
while (true) {
// wait for up to a (simulated) minute for a WashingMessage
WashingMessage m = receiveWithTimeout(60000 / Settings.SPEEDUP);
// if m is null, it means a minute passed and no message was received
if (m != null) {
System.out.println("got " + m);
} }
// ... TODO ... /** Recursive listener method */
public void listener() {
m = poll(60000 / Settings.SPEEDUP).orElse(new WashingMessage(this, Order.NOOP));
switch (m.order()) {
case Order.SPIN_OFF -> spin.setMode(WashingIO.Spin.IDLE);
case Order.SPIN_FAST -> spin.setMode(WashingIO.Spin.FAST);
case Order.SPIN_SLOW -> spin.setMode(WashingIO.Spin.LEFT);
default -> {
listener();
} }
} catch (InterruptedException unexpected) { }
// we don't expect this thread to be interrupted,
// so throw an error if it happens anyway listener();
throw new Error(unexpected); }
private final class Spin extends Thread {
private WashingIO.Spin spinMode;
boolean changed = false;
public Spin() {
spinMode = WashingIO.Spin.IDLE;
}
public synchronized void setMode(WashingIO.Spin m) {
spinMode = m;
changed = true;
}
private void loop() {
io.setSpinMode(spinMode);
if (changed) {
sendAck();
changed = false;
}
usleep(60000 / Settings.SPEEDUP);
loop();
}
@Override
public void run() {
loop();
} }
} }
} }