org.openmuc.jeebus.ship.state.smepin.AskInit Maven / Gradle / Ivy
/*
* Copyright 2024 Fraunhofer ISE
*
* This file is part of jEEBus.SHIP
* For more information visit http://www.openmuc.org
*
* jEEBus.SHIP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* jEEBus.SHIP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with jEEBus.SHIP. If not, see http://www.gnu.org/licenses/.
*/
package org.openmuc.jeebus.ship.state.smepin;
import org.openmuc.jeebus.ship.message.smepin.PinMsg;
import org.openmuc.jeebus.ship.state.StateCallBack;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class AskInit extends Ask {
private ScheduledExecutorService executor
= Executors.newSingleThreadScheduledExecutor();
// flag needed because cancelling executor does not terminate execution of the runnable
private boolean cancelClose;
public AskInit(StateCallBack stateCB, PinCallBacks pinCallBacks) {
super(stateCB, pinCallBacks);
executor.schedule(this::closeConnIfNotCancelled, 10, TimeUnit.SECONDS);
}
private void closeConnIfNotCancelled() {
if (!cancelClose) {
stateCB.closeConnection();
}
}
@Override
protected void procedure() {
String msgStr = new String(
stateCB.peekReceivedMsg(),
StandardCharsets.UTF_8
);
if (msgStr.contains("\"pinState\":")) {
next();
}
else {
log.warn("Received message is not a PinState message");
}
}
@Override
public void setNextSubState() {
// cancel scheduled closing of connection
cancelClose = true;
executor.shutdownNow();
// parse the initial message to initiate next sub-state
PinMsg initialMsg = receiveMsg();
if (initialMsg == null) {
return;
}
changeStateCB.nextSubState(new AskProcess(this, initialMsg));
}
@Override
public String toString() {
return "ASK_INIT";
}
public void setCancelClose(boolean cancelClose) {
this.cancelClose = cancelClose;
}
}