Skip to content
Snippets Groups Projects
Commit 0af3771a authored by Elisa Giglio's avatar Elisa Giglio
Browse files

Merge remote-tracking branch 'refs/remotes/origin/master'

update
parents 97164abe 70459fdb
No related branches found
No related tags found
No related merge requests found
Showing
with 28530 additions and 50 deletions
.DS_Store
bin/
\ No newline at end of file
bin/
antifurto/
bin/
res/
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
This diff is collapsed.
{"scenario-attivo":"franca---2022-07-16"}
{"scenario-attivo":"ginetto---2022-07-03"}
{"tempo":"20-05-20","luce":"OUT0","cmd":1}
{"tempo":"19-42-20","luce":"OUT0","cmd":1}
{"tempo":"20-05-21","luce":"OUT1","cmd":1}
......
{"tempo":"14-58-16","luce":"OUT2","cmd":0}
{"tempo":"14-51-34","luce":"OUT2","cmd":0}
{"tempo":"19-51-34","luce":"OUT2","cmd":0}
......@@ -122,9 +122,9 @@ public class Automa {
if(status == this.antifurto)
return;
if(status)
setCollaterals(2);
setCollaterals(2,true);
else
setCollaterals(0);
setCollaterals(0,true);
}
private synchronized void setCollaterals(int stato) throws JSONException, IOException {
......
......@@ -29,31 +29,39 @@ public class Esecutore extends Thread {
private UserChangeSync ucs;
private boolean shouldFindNewScenario = true;
private final String ESEC_CONF = Scenari.CONF_FOLDER+"esecutore.json";
boolean chosenByUser = false;
public Esecutore(Automa automa, Scenari scenari) throws IOException, JSONException {
this.automa = automa;
this.scenari = scenari;
this.ucs = new UserChangeSync(this);
setup();
}
public UserChangeSync getUCS() {
return ucs;
}
private void setup() throws IOException, JSONException {
private void setup() throws IOException, JSONException, MqttException {
// imposto lo scenario attivo
JSONObject json = new JSONObject(Helper.leggiFile(ESEC_CONF));
String scenarioAttivo = json.getString("scenario-attivo");
this.scenarioAttivo = getScenarioFile(scenarioAttivo);//FIXME se null e disabilitato da utente…
if(!scenarioAttivo.equals("none")){
setScenarioAttivo(getScenarioFile(scenarioAttivo));
} else {
//se null e' disabilitato dall' utente
this.scenarioAttivo = null;
chosenByUser = true;
isDonePublishing = true;
}
}
public void run() {
// qui ci va la business logic
try {
setup();
while (true) {
if(shouldFindNewScenario) {
// if(shouldFindNewScenario) {
if(automa.getAntifurto() && shouldFindNewScenario){
LocalTime ora = LocalTime.now();
boolean unreadStatus = automa.unreadStatus;
if ((unreadStatus && automa.getAntifurto())// se leggo lo stato per la prima volta e l'antifurto e' attivo -> ciclo
......@@ -64,7 +72,8 @@ public class Esecutore extends Thread {
if(!ucs.getBoolean()) {
if(scenarioAttivo == null && !isDonePublishing)
fr = randomFileScenari();
else fr = new FileReader(scenarioAttivo);
else if(scenarioAttivo != null)
fr = new FileReader(scenarioAttivo);
} else {
try {
while(ucs.getBoolean()) {
......@@ -84,9 +93,10 @@ public class Esecutore extends Thread {
}
LocalTime tempoCmd = LocalTime.now();
boolean startedPublishing = false;
boolean fileTooOld = false;
while (line != null && (!isDonePublishing || ora.isBefore(tempoCmd)) && !ucs.getBoolean()) {
ora = LocalTime.now();
// Helper.print("linea da eseguire: " + line);
Helper.print("linea da eseguire: " + line);
JSONObject jline = new JSONObject(line);
String[] time = jline.getString("tempo").split("-");
if (time.length != 3) {
......@@ -100,7 +110,7 @@ public class Esecutore extends Thread {
long waitingTime = Helper.timeDifference(tempoAttuale, tempoCmd) * 1000;
if (waitingTime > 0) {
if (waitingTime > 1000) {
Helper.print("will sleep for "+(waitingTime/1000));
Helper.print("will sleep for "+(waitingTime/1000)+" seconds");
Thread.sleep(waitingTime);
}
......@@ -109,7 +119,7 @@ public class Esecutore extends Thread {
String cmd = jline.getString("cmd");
scenari.sendMqttMessage(Scenari.getMqttTree("to/","gpio/" + nomeLuce),
"{cmd:" + cmd + "}");
}
} else fileTooOld = true;
} catch (InterruptedException | MqttException e) {
e.printStackTrace();
}
......@@ -126,11 +136,11 @@ public class Esecutore extends Thread {
br.close();
fr.close();
retryNum++;
isDonePublishing = (startedPublishing && retryNum < filesNum);// if i havent published, I should retry
isDonePublishing = (fileTooOld && chosenByUser) || (startedPublishing && retryNum < filesNum);// if i havent published, I should retry
scenarioAttivo = isDonePublishing ? null : scenarioAttivo;
}
}
} catch (IOException | JSONException e) {
} catch (IOException | JSONException | MqttException e) {
e.printStackTrace();
}
}
......@@ -148,7 +158,8 @@ public class Esecutore extends Thread {
this.allScenariFiles = filesList;
}
private synchronized FileReader randomFileScenari() throws IOException, JSONException {
private synchronized FileReader randomFileScenari() throws IOException, JSONException, MqttException {
chosenByUser = false;
updateAvailableScenari();
filesNum = allScenariFiles.size();
if (filesNum == 0)
......@@ -170,16 +181,31 @@ public class Esecutore extends Thread {
return new FileReader(chosenFile);
}
synchronized void setScenarioAttivo(File f) throws IOException, JSONException {
synchronized void setScenarioAttivo(File f) throws IOException, JSONException, MqttException {
Helper.print("sto cambiando lo scenario attivo");
JSONObject k = new JSONObject();
k.put("scenario-attivo", getScenarioNome(f));
String oldScenario = getScenarioAttivo();
String newScenario = getScenarioNome(f);
k.put("scenario-attivo", newScenario);
Helper.scriviFile(k.toString(), ESEC_CONF);
scenarioAttivo = f;
filesRead.add(f);
if(oldScenario == null || (!chosenByUser && !oldScenario.equals("none") && !newScenario.equals("none"))){
sendAutoActivation();
}
}
public void sendAutoActivation() throws MqttException, JSONException{
JSONObject k = new JSONObject();
String scenario = getScenarioAttivo();
if(scenario == null)
return;
k.put("scenario-attivo", scenario.split("---")[0]);
scenari.sendMqttMessage(Scenari.getMqttTree("from", "scenari/attivazioneautomatica"), k.toString());
}
public String getScenarioAttivo() {
return isDonePublishing || scenarioAttivo == null ? null : getScenarioNome(scenarioAttivo);
return (isDonePublishing || scenarioAttivo == null) ? null : getScenarioNome(scenarioAttivo);
}
public String getDataScenarioAttivo() {
......@@ -247,4 +273,12 @@ public class Esecutore extends Thread {
return scen;
}
public void releaseUserChoice(boolean isAntifurtoActive) throws MqttException, JSONException {
chosenByUser = false;
isDonePublishing = false;
setLoopCondition(isAntifurtoActive);
if(isAntifurtoActive)
sendAutoActivation();
}
}
......@@ -81,7 +81,7 @@ public class SubscribeCallback implements MqttCallback{
if(topic.startsWith("from/")){
if(topic.equals(Scenari.getMqttTree("from/","gpio/"+scenari.getLearnTrigger()))) {
Helper.print("trigger per learn");
if(/*automa.getAntifurto() ||*/ !msgJson.has("event"))//se l'antifurto e' attivo, non posso attivare gli scenari
if(!msgJson.has("event"))//se l'antifurto e' attivo, non posso attivare gli scenari
return;
int newStatus = msgJson.getInt("event");
if(newStatus != 1)
......@@ -92,7 +92,7 @@ public class SubscribeCallback implements MqttCallback{
}
if(topic.equals(Scenari.getMqttTree("from/","gpio/"+scenari.getAttivaScenari()))) {
Helper.print("trigger per antifurto");
if(/*automa.getLearn() ||*/ !msgJson.has("event"))//se l'apprendimento e' attivo, non posso attivare l'antifurto
if(!msgJson.has("event"))//se l'apprendimento e' attivo, non posso attivare l'antifurto
return;
int newStatus = msgJson.getInt("event");
if(newStatus != 1)
......@@ -212,9 +212,12 @@ public class SubscribeCallback implements MqttCallback{
automa.setStato(new JSONObject().put(cosa,cmd).toString());
final int newStatoAutoma = automa.getStato();
Helper.print("nuovo stato\t"+automa.getStato());
esec.setLoopCondition(automa.getAntifurto());
if(Helper.compareText(cosa, "learn")) {
final boolean val = Helper.compareText(cmd, "on");
handleLearn(val);
} else {
esec.releaseUserChoice(newStatoAutoma == 2);
}
if(newStatoAutoma == oldStatoAutoma)
return;
......@@ -265,6 +268,7 @@ public class SubscribeCallback implements MqttCallback{
private void handleLearn(boolean shouldLearn) throws JSONException, IOException, MqttException{
Helper.print("handleLearn "+shouldLearn+" ; "+automa.getLearn());
final Boolean passedThroughZero = automa.setStato(new JSONObject().put("learn",shouldLearn ? "on" : "off").toString());
esec.setLoopCondition(automa.getAntifurto());
if(passedThroughZero != null && !passedThroughZero){
// devo assicurarmi di modificare lo stato della luce che gestisce l'antifurto
String luce = scenari.getLuceAntifurto();
......@@ -380,6 +384,7 @@ public class SubscribeCallback implements MqttCallback{
private void setAntifurtoStatus(boolean activateAntifurto) throws MqttException, JSONException, IOException {
automa.setAntifurtoStatus(activateAntifurto);
esec.setLoopCondition(automa.getAntifurto());
sendRequested(Scenari.getMqttTree("from/","scenari/description"),false);
}
}
......@@ -3,23 +3,24 @@ package utility;
import java.io.File;
import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONException;
import org.json.JSONObject;
public class UserChangeSync {
private boolean userWantsToChange = false;
private Esecutore esec;
public UserChangeSync(Esecutore esec) {
this.esec = esec;
}
public synchronized boolean getBoolean() {
return userWantsToChange;
}
public synchronized String requestToChange(JSONObject scenario) throws IOException, JSONException {
public synchronized String requestToChange(JSONObject scenario) throws IOException, JSONException, MqttException {
userWantsToChange = true;
esec.setLoopCondition(true);
esec.updateAvailableScenari();
......@@ -44,6 +45,7 @@ public class UserChangeSync {
esec.setScenarioAttivo(scen);
}
userWantsToChange = false;
esec.chosenByUser = true;
notifyAll();
return scenNome;
}
......
......@@ -29,7 +29,7 @@ public class Home implements HttpHandler {
String requestMethod = exchange.getRequestMethod();
if (Helper.compareText(requestMethod, "GET")) {
String response = getLocalPage(URI.create("/home/"));
String response = getHomePage();
List<String> strlist = new ArrayList<>();
strlist.add("text/html");
exchange.getResponseHeaders().put("content-type", strlist);
......@@ -41,8 +41,8 @@ public class Home implements HttpHandler {
Helper.methodNotAllowed(exchange);
}
}
private static String getLocalPage(URI pageid) {
private static String getHomePage() {
String line;
// String pageIDString = pageid.toString();
String page = Server.CLIENT_PATH+"/index.html";// + pageIDString.substring(0, pageIDString.length() - 1) + ".txt";// entro nella cartella
......@@ -61,7 +61,7 @@ public class Home implements HttpHandler {
boolean isComment = false;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim();
if(line.startsWith("<!--") && line.endsWith("-->")) {
continue;
}
......@@ -73,7 +73,7 @@ public class Home implements HttpHandler {
isComment = false;
continue;
}
if(!isComment && line.length()>0)
answer.append(line).append("\n");
}
......@@ -93,7 +93,7 @@ public class Home implements HttpHandler {
}
return answer.toString();
}
private static String getExtension(String file) {
int i = file.length() - 1;
while (i > 0 && file.charAt(i) != '.' && file.charAt(i) != '/')
......
......@@ -23,6 +23,7 @@ public class Resources implements HttpHandler {
if (Helper.compareText(requestMethod, "GET")) {
String response = getLocalPage(requestURI.toASCIIString());
if(response.equals("fail")){
//nel caso in cui non ci sia il file (perche non stato scaricato), allora creo un file fittizzio per non far crashare tutto il resto
String[] requestedPath = requestURI.toASCIIString().split("/");
// get the last element of requestedPath and remove .js
String[] requestedPage = requestedPath[requestedPath.length-1].split("\\.");
......@@ -33,9 +34,9 @@ public class Resources implements HttpHandler {
}
List<String> strlist = new ArrayList<>();
switch (requestURI.toASCIIString().substring(1, 4)) {
case "js/" -> strlist.add("text/javascript");
case "css" -> strlist.add("text/css");
default -> strlist.add("text");
case "js/" : strlist.add("text/javascript"); break;
case "css" : strlist.add("text/css"); break;
default : strlist.add("text"); break;
}
exchange.getResponseHeaders().put("content-type", strlist);
exchange.sendResponseHeaders(200, response.getBytes().length);
......
......@@ -75,22 +75,11 @@ public class Server {
});
//API del server
server.createContext("/api/luci/",new Luci());//post, get [put, delete] {luogo e stato di tutte luci}
server.createContext("/api/luci/stato/",new Luci());//put {aggiorna lo stato di una luce}
server.createContext("/api/scenari/",new Scenari());//get {nome e data di tutti gli scenari}
server.createContext("/api/scenari/attiva/",new Scenari());//put {attiva/disattiva}
server.createContext("/api/scenari/registra/",new Scenari());//put {registra/termina}
server.createContext("/api/scenari/salva/",new Scenari());//get {conferma salvataggio, altrimenti cancella dopo timer; ritorna i valori dello scenario}
server.createContext("/api/antifurto/",new Antifurto());//get {stato, allarme, attenzione, soglia, sensori}
server.createContext("/api/antifurto/stato/",new Antifurto());//get, put {se l'antifurto e' attivo + aggiornamento}
server.createContext("/api/antifurto/allarme/",new Antifurto());//get, put {se l'allarme sta suonando + aggiornamento}
server.createContext("/api/antifurto/attenzione/",new Antifurto());//put {valore della progress bar}
server.createContext("/api/antifurto/soglia/",new Antifurto());//put {valore scelto dall'utente per la soglia}
server.createContext("/js/",new Resources());
server.createContext("/css/",new Resources());
server.createContext("/res/",new ImageRes());
server.createContext("/",new Home());
// server.setExecutor(Executors.newFixedThreadPool(11));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
......
......@@ -14,4 +14,15 @@
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1660300125941</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
No preview for this file type
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment