diff --git a/LuciMicro/luci.bash b/LuciMicro/luci.bash
new file mode 100755
index 0000000000000000000000000000000000000000..625fd31c29e13423a3fced01c9fbf89081f03b5c
--- /dev/null
+++ b/LuciMicro/luci.bash
@@ -0,0 +1,5 @@
+#!/bin/bash
+javac -cp .:./org.eclipse.paho.client.mqttv3_1.2.5.jar:./org.json-1.0.0.v201011060100.jar -d bin src/code/*
+echo 'luci compiled'
+cd bin
+java -classpath .:../org.eclipse.paho.client.mqttv3_1.2.5.jar:../org.json-1.0.0.v201011060100.jar code.Luci $1
diff --git a/ScenariMicroservizio/bin/scenari/Scenari.class b/ScenariMicroservizio/bin/scenari/Scenari.class
index 19cc3af67c7a7146ece2a4b89ef27afa128e53ae..712f02fd94ece50c821c1bb2aeadac97c860f8cd 100644
Binary files a/ScenariMicroservizio/bin/scenari/Scenari.class and b/ScenariMicroservizio/bin/scenari/Scenari.class differ
diff --git a/ScenariMicroservizio/bin/utility/Esecutore.class b/ScenariMicroservizio/bin/utility/Esecutore.class
index e113907854367d1d2c6b9599f6e7920bf70180d4..283c5c2213647326b1ca135c28b5b6a341ec96f1 100644
Binary files a/ScenariMicroservizio/bin/utility/Esecutore.class and b/ScenariMicroservizio/bin/utility/Esecutore.class differ
diff --git a/ScenariMicroservizio/bin/utility/Helper.class b/ScenariMicroservizio/bin/utility/Helper.class
index 72d972ff44812fcb69cd2332b1350586312b3047..a5bc15c073b2415b76df3803363b73a27065ba09 100644
Binary files a/ScenariMicroservizio/bin/utility/Helper.class and b/ScenariMicroservizio/bin/utility/Helper.class differ
diff --git a/ScenariMicroservizio/bin/utility/SubscribeCallback.class b/ScenariMicroservizio/bin/utility/SubscribeCallback.class
index fc5d519dff5a61e890c7305187d8011d8650d5fb..e909ae0148640f74c55dc6ef43334a22c2194534 100644
Binary files a/ScenariMicroservizio/bin/utility/SubscribeCallback.class and b/ScenariMicroservizio/bin/utility/SubscribeCallback.class differ
diff --git a/ScenariMicroservizio/bin/utility/UserChangeSync.class b/ScenariMicroservizio/bin/utility/UserChangeSync.class
index db1ad420730705e7193ecdfcdff8859f43eec9f5..2e59d90c5c55f2ebff350bf2c2a64b4a6c67ac4b 100644
Binary files a/ScenariMicroservizio/bin/utility/UserChangeSync.class and b/ScenariMicroservizio/bin/utility/UserChangeSync.class differ
diff --git a/ScenariMicroservizio/res/CONF/esecutore.json b/ScenariMicroservizio/res/CONF/esecutore.json
index 5e9c284f7f52ac174ba521bb6f67b96117552a8f..034e5534672746dd5a7ba19638fa98f8ca8dff6d 100644
--- a/ScenariMicroservizio/res/CONF/esecutore.json
+++ b/ScenariMicroservizio/res/CONF/esecutore.json
@@ -1 +1 @@
-{"scenario-attivo":"none"}
+{"scenario-attivo":"giovanni---2022-06-29"}
diff --git a/ScenariMicroservizio/res/CONF/zona.json b/ScenariMicroservizio/res/CONF/zona.json
index 2ae855038b185fe18b0b0a4015d596b6df422fc6..cd0efc7a600b625bd9deeb001efd3ca2070a9c0f 100644
--- a/ScenariMicroservizio/res/CONF/zona.json
+++ b/ScenariMicroservizio/res/CONF/zona.json
@@ -1,4 +1,2 @@
-{
-    "learn-trigger": "IN4",
-    "attiva-scenari": "IN5"
-}
\ No newline at end of file
+{"attiva-scenari":"IN0",
+"learn-trigger":"IN4"}
diff --git a/ScenariMicroservizio/res/scenari.json b/ScenariMicroservizio/res/scenari.json
index 4c63bb54fd3fc17eb8f960aefbdb3fcef12b2d87..9678726eb4a97792ba2e7228353064858401a29b 100644
--- a/ScenariMicroservizio/res/scenari.json
+++ b/ScenariMicroservizio/res/scenari.json
@@ -8,10 +8,10 @@
 {"stato":1,
 "learn-off":0,
 "learn-on":1,
-"antifurto-on":1,
+"antifurto-on":2,
 "antifurto-off":1},
 {"stato":2,
 "learn-off":2,
-"learn-on":2,
+"learn-on":1,
 "antifurto-on":2,
 "antifurto-off":0}]}
diff --git a/ScenariMicroservizio/scenari.bash b/ScenariMicroservizio/scenari.bash
index d6af8dd0a8fec7968b997e5d149f6442cfe7f861..53341651327a654cc8a7c36340152e779f3c4549 100755
--- a/ScenariMicroservizio/scenari.bash
+++ b/ScenariMicroservizio/scenari.bash
@@ -2,5 +2,4 @@
 javac -cp .:./org.eclipse.paho.client.mqttv3_1.2.5.jar:./org.json-1.0.0.v201011060100.jar -d bin src/utility/* src/scenari/*
 echo 'scenari compiled'
 cd bin
-java -classpath .:../org.eclipse.paho.client.mqttv3_1.2.5.jar:../org.json-1.0.0.v201011060100.jar scenari.Scenari
-
+java -classpath .:../org.eclipse.paho.client.mqttv3_1.2.5.jar:../org.json-1.0.0.v201011060100.jar scenari.Scenari $1
diff --git a/ScenariMicroservizio/src/scenari/Scenari.java b/ScenariMicroservizio/src/scenari/Scenari.java
index 4c1b1bd87bea46050751d356ce28efb3ae007386..dad2f414ce41793d2dc8a73fbf68feedbed92cbd 100644
--- a/ScenariMicroservizio/src/scenari/Scenari.java
+++ b/ScenariMicroservizio/src/scenari/Scenari.java
@@ -34,83 +34,97 @@ public class Scenari {
 	public static final String CONF_FOLDER = RES_FOLDER+"CONF/";
 	private final String FILE_CONF = CONF_FOLDER+"conf.json";
 	private final String FILE_ZONA = CONF_FOLDER+"zona.json";
-	
+
 	public MqttClient mqttClient;
-	
+
 	public Scenari(Automa automa) throws JSONException, IOException, MqttException {
 		this.automa = automa;
-		
+
 		JSONObject config = new JSONObject(Helper.leggiFile(FILE_CONF));
 		brokerUrl = config.getString("protocol") + "://" + config.getString("broker") + ":" + config.getInt("port");
 		mqttDomain = config.getString("mqttDomain");
 		mqttSubdomain = config.getString("mqttSubdomain");
 		makeMqttTree();
-		
+
 		topicsSub = new ArrayList<String>();
 		topicsSub.add("to/all"); //mandare la mia descrizione json
 		topicsSub.add(getMqttTree("rpc/","scenari")); //mandare lo stato attuale
-		
+
 		// inutile aggiungere i topic, perche subbo gia' tutto gpio/#
 		config = new JSONObject(Helper.leggiFile(FILE_ZONA));
 		learnTrigger = config.getString("learn-trigger");
 		attivaScenari = config.getString("attiva-scenari");
-		
+
 		topicsSub.add(getMqttTree("from/","gpio/#"));
-		topicsSub.add(getMqttTree("to/","scenari"));//{"evento":0,"nome":nome_scenario} per attivare/disattivare uno scenario; risposta su from/tree/scenari/attiva con {"nome":nome_scenario}
-		topicsSub.add(getMqttTree("to/","scenari/salva"));//per rinominare lo scenario piu recente
-		
+		topicsSub.add(getMqttTree("to/","scenari/#"));//{"evento":0,"nome":nome_scenario} per attivare/disattivare uno scenario; risposta su from/tree/scenari/attiva con {"nome":nome_scenario}
+		// topicsSub.add(getMqttTree("to/","scenari/salva"));//per rinominare lo scenario piu recente
+
 		this.mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
 		//memory persistence serve per non avere errori in console
 		// https://github.com/eclipse/paho.mqtt.java/issues/794
 	}
-	
-	public void startClient(Esecutore esec/*, Publisher publisher*/) throws MqttException {
+
+	public void startClient(Esecutore esec) throws MqttException {
 		MqttConnectOptions options = new MqttConnectOptions();
 		options.setUserName("gruppo2");
 		options.setPassword("funziona".toCharArray());
 		options.setCleanSession(false);
-		mqttClient.setCallback(new SubscribeCallback(this/*, publisher*/, learnTrigger, attivaScenari, esec, automa));
-		
+		mqttClient.setCallback(new SubscribeCallback(this, esec, automa));
+
 		mqttClient.connect(options);
-		
-		for(String t: topicsSub) 
+
+		for(String t: topicsSub)
 			mqttClient.subscribe(t);
 	}
-	
+
 	public void sendMqttMessage(String topic, String msg) throws MqttException {
 		final MqttTopic msgTopic = mqttClient.getTopic(topic);
 		msgTopic.publish(new MqttMessage(msg.getBytes()));
 	}
-	
+
 	private void makeMqttTree() {
 		if(mqttTree != null)
 			return;
 		mqttTree = mqttDomain + "/" + mqttSubdomain + "/";
 	}
-	
+
 	public static String getMqttTree(String prefix,String suffix) {
 		return (prefix.endsWith("/") ? prefix : prefix+"/") + mqttTree + (suffix.startsWith("/") ? suffix.substring(1) : suffix);
 	}
-	
+
 	public static void main(String args[]) throws JSONException, IOException, MqttException {
 		if(args.length > 0)
 			Scenari.shouldPrint = true;
 		Helper.print("scenari started");
 		startSystem();
 	}
-	
-	
+
+
 	private static void startSystem() throws JSONException, IOException, MqttException {
 		Automa automa = new Automa();
 		Scenari scenari = new Scenari(automa);
 		Esecutore esec = new Esecutore(automa,scenari);
-		
+
 		scenari.startClient(esec);
 		esec.start();
 	}
 
-	
-	
-	
+	public String getLearnTrigger() {
+		return learnTrigger;
+	}
+
+	public String getAttivaScenari() {
+		return attivaScenari;
+	}
 
+	public void setAttivaScenari(String attivaScenari) throws JSONException, IOException{
+		if(!attivaScenari.matches("(IN|in)[0-7]"))
+			throw new IllegalArgumentException("attivaScenari non corretto");
+		// write attivaScenari to the file zona
+		JSONObject config = new JSONObject();
+		config = new JSONObject(Helper.leggiFile(FILE_ZONA));
+		config.put("attiva-scenari", attivaScenari);
+		Helper.scriviFile(config, FILE_ZONA);
+		this.attivaScenari = attivaScenari;
+	}
 }
diff --git a/ScenariMicroservizio/src/utility/Helper.java b/ScenariMicroservizio/src/utility/Helper.java
index 5694e675ce66e4d25b63786858ec7dd4e10521f7..742d4e264be1d851282eba602ad1b52b3549ff00 100644
--- a/ScenariMicroservizio/src/utility/Helper.java
+++ b/ScenariMicroservizio/src/utility/Helper.java
@@ -15,11 +15,11 @@ import org.json.JSONObject;
 import scenari.Scenari;
 
 public class Helper {
-	
+
 	public static boolean compareText(String a, String b){
 		return a.compareToIgnoreCase(b) == 0;
 	}
-	
+
 	public static boolean checkJSON(String body) {
 		if(!body.startsWith("{") || !body.endsWith("}"))
 			return false;
@@ -30,7 +30,7 @@ public class Helper {
 			return false;
 		}
 	}
-	
+
 	public static String leggiFile(String path) throws IOException {
 		String line;
 		StringBuffer answer = new StringBuffer();
@@ -50,7 +50,7 @@ public class Helper {
 		}
 		return answer.toString();
 	}
-	
+
 	public synchronized static void scriviFile(String text, String path) throws IOException {
 		BufferedWriter b = new BufferedWriter(new FileWriter(path));
 		String[] lines = text.split("\n");
@@ -64,7 +64,7 @@ public class Helper {
 	public synchronized static void scriviFile(JSONObject job, String path) throws IOException {
 		scriviFile(convertiJSON(job),path);
 	}
-	
+
 	private static String convertiJSON(JSONObject job) throws IOException {
 		String[] strings = job.toString().split(",");
 		StringBuffer text = new StringBuffer();
@@ -76,7 +76,7 @@ public class Helper {
 			} else text.append(s);
 		return text.toString();
 	}
-	
+
 	public static void appendiFile(String text, String path) throws IOException {
 		String fileContents = leggiFile(path);
 		StringBuffer s = new StringBuffer();
@@ -85,21 +85,21 @@ public class Helper {
 		s.append(text);
 		scriviFile(s.toString(),path);
 	}
-	
+
 	public static void appendiFile(JSONObject job, String path, boolean splitLines) throws IOException {
 		appendiFile(splitLines ? convertiJSON(job) : job.toString() ,path);
 	}
-	
+
 	public static void appendiFile(JSONObject job, String path) throws IOException {
 		appendiFile(job,path,true);
 	}
-	
+
 	public static long timeDifference(Temporal older, Temporal newer) {
 		return Duration.between(older, newer).toSeconds();
 	}
 
 	public static void print(String toPrint){
 		if(Scenari.shouldPrint)
-			System.out.println(toPrint);
+			System.out.println("[Scenari]  "+toPrint);
 	}
 }
diff --git a/ScenariMicroservizio/src/utility/SubscribeCallback.java b/ScenariMicroservizio/src/utility/SubscribeCallback.java
index 43f3092dd99f00bb0c81a261965e752711596059..826913b396ab4e78e41ffc82cae2c93b56c44413 100644
--- a/ScenariMicroservizio/src/utility/SubscribeCallback.java
+++ b/ScenariMicroservizio/src/utility/SubscribeCallback.java
@@ -19,18 +19,14 @@ import scenari.Automa;
 import scenari.Scenari;
 
 public class SubscribeCallback implements MqttCallback{
-	
+
 	private Scenari scenari;
 //	private Publisher publisher;
-	private String learnTrigger;
-	private String attivaScenari;
 	private Esecutore esec;
 	private Automa automa;
-	
-	public SubscribeCallback(Scenari scenari, String learnTrigger, String attivaScenari, Esecutore esec, Automa automa) {
+
+	public SubscribeCallback(Scenari scenari, Esecutore esec, Automa automa) {
 		this.scenari = scenari;
-		this.learnTrigger = learnTrigger;
-		this.attivaScenari = attivaScenari;
 		this.esec = esec;
 		this.automa = automa;
 	}
@@ -41,11 +37,11 @@ public class SubscribeCallback implements MqttCallback{
 		final Date d = new Date();
 		Date d2 = new Date();
 		long time = Math.abs(d2.getTime()-d.getTime());
-		
+
 		while (time<600000) {
 			try {
 				Helper.print("retrying...");
-				
+
 				Scenari.main(null);
 				return;
 			} catch (MqttException | JSONException | IOException e) {
@@ -61,13 +57,13 @@ public class SubscribeCallback implements MqttCallback{
 		}
 	}
 
-	
+
 	@Override
 	public void deliveryComplete(IMqttDeliveryToken arg0) {
 		// Nessuna operazione
 		Helper.print("inviato");
 	}
-	
+
 
 	@Override
 	public void messageArrived(String topic, MqttMessage message) throws MqttException, JSONException, IOException {
@@ -83,27 +79,27 @@ public class SubscribeCallback implements MqttCallback{
 			sendRequested(Scenari.getMqttTree("from/","scenari"),true);
 			return;
 		}
-		
+
 		JSONObject msgJson = new JSONObject(message.toString());
 //		gli event sono 0 o 1; i trigger quando sono attivati/premuti inviano un 1, che e' l'unico elemento che mi interessa
-		if(topic.equals(Scenari.getMqttTree("from/","gpio/"+learnTrigger))) {
+		if(topic.equals(Scenari.getMqttTree("from/","gpio/"+scenari.getLearnTrigger()))) {
 			Helper.print("trigger per learn\t"+!automa.getAntifurto());
 			if(automa.getAntifurto())//se l'antifurto e' attivo, non posso attivare gli scenari
 				return;
 			int newStatus = msgJson.getInt("event");
 			if(newStatus != 1)
 				return;
-			handleEvent(newStatus,learnTrigger);
+			handleEvent(newStatus,scenari.getLearnTrigger());
 			return;
 		}
-		if(topic.equals(Scenari.getMqttTree("from/","gpio/"+attivaScenari))) {
+		if(topic.equals(Scenari.getMqttTree("from/","gpio/"+scenari.getAttivaScenari()))) {
 			Helper.print("trigger per antifurto\t"+!automa.getLearn());
 			if(automa.getLearn())//se l'apprendimento e' attivo, non posso attivare l'antifurto
 				return;
 			int newStatus = msgJson.getInt("event");
 			if(newStatus != 1)
 				return;
-			handleEvent(newStatus,attivaScenari);
+			handleEvent(newStatus,scenari.getAttivaScenari());
 			return;
 		}
 		if(topic.startsWith(Scenari.getMqttTree("from/","gpio/IN"))) {
@@ -140,18 +136,32 @@ public class SubscribeCallback implements MqttCallback{
 		}
 		if(topic.equals(Scenari.getMqttTree("to/","scenari/salva"))) {
 			Helper.print("rinomino l'ultimo scenario salvato");
-			if(automa.ultimoStato != 1 || !message.toString().contains("nome"))//se non sono appena stato nello stato di registrazione, non serve andare avanti
+			if(!message.toString().contains("nome"))//se non sono appena stato nello stato di registrazione, non serve andare avanti
 				return;
 			renameLastScenario(msgJson);
 			return;
 		}
-		
+		if(topic.equals(Scenari.getMqttTree("to","scenari/sensoreAntifurto"))){
+			Helper.print("messaggio per cambiare il sensore che imposta l'antifurto");//serve se l'antifurto cambia sensore
+			if(!message.toString().contains("attiva-scenari"))
+				return;
+			changeSensor(msgJson);
+			return;
+		}
+
 		Helper.print("Impossibile");
 	}
-	
+
+	private void changeSensor(JSONObject msgJson) throws JSONException, IOException {
+		String newSensor = msgJson.getString("attiva-scenari");
+		scenari.setAttivaScenari(newSensor);
+		Helper.print("sensore cambiato in "+newSensor);
+	}
+
 	private void handleEvent(int newStatus,String which) throws JSONException, MqttException, IOException{
-		String cosa = which == learnTrigger ? "learn" : "antifurto";
+		String cosa = which == scenari.getLearnTrigger() ? "learn" : "antifurto";
 		String cmd = automa.findPossibleCommand(cosa);
+		Helper.print("Cosa: "+cosa+"\tCmd: "+cmd);
 		if(cmd == null)
 			return;
 		Helper.print("handling event: "+cosa+"\t"+cmd);
@@ -161,12 +171,12 @@ public class SubscribeCallback implements MqttCallback{
 			boolean val = Helper.compareText(cmd, "on");
 			handleLearn(val);
 			sendRequested(Scenari.getMqttTree("from/","scenari/learn"),false);
-		} else 
+		} else
 			sendRequested(Scenari.getMqttTree("from/","scenari/antifurto"),false);
 	}
-	
+
 	private String scenarioName = null;
-	
+
 	private void handleLearn(boolean shouldLearn) throws JSONException, IOException{
 		Helper.print("handleLearn "+shouldLearn+" ; "+automa.getLearn());
 		automa.setStato("{\"learn\":"+ (shouldLearn ? "\"on\"" : "\"off\"")+"}");
@@ -180,7 +190,7 @@ public class SubscribeCallback implements MqttCallback{
 //			TODO tell antifurto to turn off if shouldLearn == true
 		}
 	}
-	
+
 	private void handleLearnData(String luce, int val) throws MqttException, IOException, JSONException {
 		JSONObject j = new JSONObject();
 //		tempo passato dallo scorso comando
@@ -192,7 +202,7 @@ public class SubscribeCallback implements MqttCallback{
 		j.put("cmd", val);
 		Helper.appendiFile(j, esec.DB_FOLDER+scenarioName,false);
 	}
-	
+
 	private void changeActiveScenario(JSONObject scenario) throws IOException, JSONException, MqttException {
 		String nuovoScenario = esec.getUCS().requestToChange(scenario);
 		Helper.print(nuovoScenario);
@@ -200,7 +210,7 @@ public class SubscribeCallback implements MqttCallback{
 		j.put("nome", nuovoScenario);
 		scenari.sendMqttMessage(Scenari.getMqttTree("from/","/scenari/attiva"), j.toString());
 	}
-	
+
 	private void sendRequested(String topic,boolean moreInfo) throws MqttException, JSONException, IOException {
 		JSONObject j = new JSONObject();
 		j.put("stato", automa.getStato());
@@ -208,8 +218,8 @@ public class SubscribeCallback implements MqttCallback{
 			j.put("learn", automa.getLearn());
 			boolean antifurto = automa.getAntifurto();
 			j.put("antifurto", antifurto);
-			j.put("learn-trigger", learnTrigger);
-			j.put("attiva-scenari", attivaScenari);
+			j.put("learn-trigger", scenari.getLearnTrigger());
+			j.put("attiva-scenari", scenari.getAttivaScenari());
 //			invio tutti gli scenari
 			{
 				ArrayList<File> allScenariFile = esec.getAllScenariAvailable();
@@ -263,15 +273,15 @@ public class SubscribeCallback implements MqttCallback{
 		LocalDateTime now = LocalDateTime.now();
 		String date = now.getYear()+"-"+(now.getMonthValue() < 10 ? "0"+now.getMonthValue() : now.getMonthValue())+"-"+(now.getDayOfMonth() < 10 ? "0"+now.getDayOfMonth() : now.getDayOfMonth());
 		rename.append(esec.removeExtension(nuovoNome)).append("---").append(date).append(".json");
-		
+
 		boolean renamed = max.renameTo(new File(rename.toString()));
-		
+
 		JSONObject j = new JSONObject();
 		String nuovoNomeSenzaEstensione = esec.removeData(esec.removeExtension(renamed ? nuovoNome : nome));
 		j.put("nome", nuovoNomeSenzaEstensione);
 		j.put("data", date);
 		scenari.sendMqttMessage(Scenari.getMqttTree("from/","scenario/salva"), j.toString());
 	}
-	
+
 
 }
diff --git a/WebServer/server.bash b/WebServer/server.bash
index ecff166104bb978b7c606f43559db19377c747d3..62b8300a700d6e60764ef37751a8b7ee05c82bec 100755
--- a/WebServer/server.bash
+++ b/WebServer/server.bash
@@ -2,4 +2,4 @@
 javac -cp .:./org.json-1.0.0.v201011060100.jar -d bin src/code/*
 echo 'server compiled'
 cd bin
-java -classpath .:../org.json-1.0.0.v201011060100.jar code.Server
+java -classpath .:../org.json-1.0.0.v201011060100.jar code.Server $1
diff --git a/antifurto/antifurto.bash b/antifurto/antifurto.bash
new file mode 100755
index 0000000000000000000000000000000000000000..a6cdbcbae643eed2a17e7d3e47bf426c09f253c7
--- /dev/null
+++ b/antifurto/antifurto.bash
@@ -0,0 +1,9 @@
+#!/bin/bash
+javac -cp .:./org.eclipse.paho.client.mqttv3_1.2.5.jar:./org.json-1.0.0.v201011060100.jar -d bin src/code/*
+echo 'antifurto compiled'
+cd bin
+java -classpath .:../org.eclipse.paho.client.mqttv3_1.2.5.jar:../org.json-1.0.0.v201011060100.jar code.Antifurto $1
+
+
+
+#/usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
\ No newline at end of file
diff --git a/antifurto/bin/bin/install.bash b/antifurto/bin/bin/install.bash
new file mode 100755
index 0000000000000000000000000000000000000000..5b474c2c4537e30ea0d6ebe4431f2d84420dd07d
--- /dev/null
+++ b/antifurto/bin/bin/install.bash
@@ -0,0 +1,2 @@
+#!/bin/bash
+if [ ! -d "/home/debian/hat_home" ]; then mkdir /home/debian/hat_home; fi
diff --git a/antifurto/bin/bin/start.bash b/antifurto/bin/bin/start.bash
new file mode 100755
index 0000000000000000000000000000000000000000..139636330902298aa2bebbcdc6b2f6027bc2736c
--- /dev/null
+++ b/antifurto/bin/bin/start.bash
@@ -0,0 +1,6 @@
+#!/bin/bash
+status="OFF"
+running=$(/usr/bin/pgrep antifurto)
+if [ -f "/home/debian/CONFIG/antifurto/STATUS" ]; then status=$(cat /home/debian/CONFIG/antifurto/STATUS); fi
+if [ ! -z "$running" ]; then status="OFF"; fi
+if [ $status == "ON" ]; then (/home/debian/CONFIG/antifurto/bin/antifurto /home/debian/CONFIG/antifurto &>/dev/null&); fi 
diff --git a/antifurto/bin/bin/stop.bash b/antifurto/bin/bin/stop.bash
new file mode 100755
index 0000000000000000000000000000000000000000..c7fc4610f10ea3118206c3f0cbbc0bcadde78d90
--- /dev/null
+++ b/antifurto/bin/bin/stop.bash
@@ -0,0 +1,5 @@
+#!/bin/bash
+status="NONE"
+if [ -f "/home/debian/CONFIG/antifurto/STATUS" ]; then status=$(cat /home/debian/CONFIG/antifurto/STATUS); fi
+if [ $status == "OFF" ]; then /home/debian/bin/stopag antifurto; fi
+
diff --git a/antifurto/bin/bridge.conf b/antifurto/bin/bridge.conf
new file mode 100644
index 0000000000000000000000000000000000000000..cf74ca90b0293f5305a45727cccd33a392211d2e
--- /dev/null
+++ b/antifurto/bin/bridge.conf
@@ -0,0 +1,15 @@
+connection bridge-pissir-20030784
+address luci.local:1883
+bridge_cafile /etc/mosquitto/ca_certificates/ca_certificate.pem
+
+tls_version tlsv1.2
+try_private false
+remote_username gruppo2
+remote_password funziona
+
+topic to/all in 2
+topic rpc/gruppo2/luci/antifurto in 2
+topic from/gruppo2/luci/gpio/+ both 2
+
+topic from/gruppo2/luci/antifurto/description out 1
+topic from/gruppo2/luci/antifurto out 1
diff --git a/antifurto/bin/code/Antifurto.class b/antifurto/bin/code/Antifurto.class
new file mode 100644
index 0000000000000000000000000000000000000000..21923ac9f5573e93d60513e7056e2c39991a620c
Binary files /dev/null and b/antifurto/bin/code/Antifurto.class differ
diff --git a/antifurto/bin/code/Automa.class b/antifurto/bin/code/Automa.class
new file mode 100644
index 0000000000000000000000000000000000000000..237df0951a7fc4e520312f468ff80b31753a3875
Binary files /dev/null and b/antifurto/bin/code/Automa.class differ
diff --git a/antifurto/bin/code/Esecutore.class b/antifurto/bin/code/Esecutore.class
new file mode 100644
index 0000000000000000000000000000000000000000..986d2e4db3f38519b0f233d33599ffed014df5a0
Binary files /dev/null and b/antifurto/bin/code/Esecutore.class differ
diff --git a/antifurto/bin/code/Helper.class b/antifurto/bin/code/Helper.class
new file mode 100644
index 0000000000000000000000000000000000000000..27eb86ed7d768ec518afd3d2d023d10e0143c0aa
Binary files /dev/null and b/antifurto/bin/code/Helper.class differ
diff --git a/antifurto/bin/code/MyQueue.class b/antifurto/bin/code/MyQueue.class
new file mode 100644
index 0000000000000000000000000000000000000000..9801fb6cbdbcc4c4617ce10657e8202676670f8f
Binary files /dev/null and b/antifurto/bin/code/MyQueue.class differ
diff --git a/antifurto/bin/code/Pair.class b/antifurto/bin/code/Pair.class
new file mode 100644
index 0000000000000000000000000000000000000000..84326ee9449abe916ff70c61d2255b5d5c33cb29
Binary files /dev/null and b/antifurto/bin/code/Pair.class differ
diff --git a/antifurto/bin/code/Publisher.class b/antifurto/bin/code/Publisher.class
new file mode 100644
index 0000000000000000000000000000000000000000..7f601d48df6a54254ba827d30fb5fe762a636eca
Binary files /dev/null and b/antifurto/bin/code/Publisher.class differ
diff --git a/antifurto/bin/code/SubscribeCallback.class b/antifurto/bin/code/SubscribeCallback.class
new file mode 100644
index 0000000000000000000000000000000000000000..a5912ba0334edc387375f85b4f56ce8768563b71
Binary files /dev/null and b/antifurto/bin/code/SubscribeCallback.class differ
diff --git a/antifurto/bin/code/Timer.class b/antifurto/bin/code/Timer.class
new file mode 100644
index 0000000000000000000000000000000000000000..2edff9f10d2659030c9ea4fad254d1e005b90b87
Binary files /dev/null and b/antifurto/bin/code/Timer.class differ
diff --git a/antifurto/bin/conf.xml b/antifurto/bin/conf.xml
new file mode 100644
index 0000000000000000000000000000000000000000..b0ba5f71b929c3598c0adeb2e3d05df60b4932d6
--- /dev/null
+++ b/antifurto/bin/conf.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" ?><set type="pathnames">
+<attribute category="generic" name="agenttype" value="antifurto"/>
+<attribute category="generic" name="agentname" value="antifurto_$HOST"/>
+<attribute category="generic" name="homedir" value="/home/debian/hat_home/antifurto"/>
+<attribute category="generic" name="emergency_homedir" value="/home/debian/hat_home/antifurto"/>
+<attribute category="generic" name="description" value="Local Antifurto"/>
+<attribute category="generic" name="port" value="8090"/>
+<attribute category="generic" name="threads" value="threads"/>
+<attribute category="generic" name="mqtt_domain" value=""/>
+<attribute category="generic" name="mqtt_subdomain" value=""/>
+<attribute category="generic" name="mqtt_service" value="antifurto"/>
+</set>
diff --git a/antifurto/bin/logger.xml b/antifurto/bin/logger.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6bd6903e0e7bed8b59c5b6acbe8cc0a9b603b4b6
--- /dev/null
+++ b/antifurto/bin/logger.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" ?><set type="pathnames">
+	<attribute category="generic" name="log_theme" value="from/$MQTT_DOMAIN/$MQTT_SUBDOMAIN/$MQTT_SERVICE/logger"/>
+	<attribute category="generic" name="status_theme" value="from/$MQTT_DOMAIN/$MQTT_SUBDOMAIN/$MQTT_SERVICE/$LOCALNAME"/>
+	<attribute category="generic" name="notify_theme" value="from/any"/>
+	<attribute category="generic" name="describe_theme" value="from/$MQTT_DOMAIN/$MQTT_SUBDOMAIN/$MQTT_SERVICE/description"/>
+	<attribute category="generic" name="log_msg" value="{$LOCALNAME:$MESSAGE}"/>
+	<attribute category="generic" name="status_msg" value="{status:$MESSAGE}"/>
+	<attribute category="generic" name="notify_msg" value="{$INFOTYPE:$MESSAGE}"/>
+	<attribute category="generic" name="describe_msg" value=" $MESSAGE "/>
+</set>
diff --git a/antifurto/bin/templates/interruttore.xml b/antifurto/bin/templates/interruttore.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0f6b5aeaa693f3bc6971498ac1b9ab9eee18a1d
--- /dev/null
+++ b/antifurto/bin/templates/interruttore.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0"?>
+<set type="interruttore">
+<attribute name="type" value="booleanin"/>
+<attribute name="name" value=""/> <!-- DA RIEMPIRE CON IL NOME SPECIFICATO DALL'UTENTE PER QUELL'INTERRUTTORE. SE NON SPECIFICATO, IL NOME SARA' LO STESSO DEL NOME LOGICO DI QUELL'INPUT -->
+<attribute name="capename" value=""/> <!-- DA RIEMPIRE CON IL NOME LOGICO DELL'INPUT -->
+</set>
diff --git a/antifurto/bin/templates/sensoremovimento1.xml b/antifurto/bin/templates/sensoremovimento1.xml
new file mode 100644
index 0000000000000000000000000000000000000000..706315adb672836504a033a5ec883942c4e12677
--- /dev/null
+++ b/antifurto/bin/templates/sensoremovimento1.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0"?>
+<set type="sensoremovimento">
+<attribute name="type" value="booleanin"/>
+<attribute name="name" value=""/> <!-- DA RIEMPIRE CON IL NOME SPECIFICATO DALL'UTENTE PER QUEL SENSORE. SE NON SPECIFICATO, IL NOME SARA' LO STESSO DEL NOME LOGICO DI QUELL'INPUT -->
+<attribute name="capename" value=""/> <!-- DA RIEMPIRE CON IL NOME LOGICO DELL'INPUT -->
+</set>
diff --git a/antifurto/bin/threads/MqttClientThread.xml b/antifurto/bin/threads/MqttClientThread.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f17afa14bd5deeda8db6237107bc9515cc44e554
--- /dev/null
+++ b/antifurto/bin/threads/MqttClientThread.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0"?>
+<set type="thread">
+<attribute category="generic" name="status" value="ON"/>
+<attribute category="generic" name="host" value="localhost"/>
+<attribute category="generic" name="port" value="1883"/>
+<attribute category="topic" name="to/$MQTT_DOMAIN/$MQTT_SUBDOMAIN/$MQTT_SERVICE/#" value="mqtt_sub"/> <!-- Sottoscrivo i messaggi che provengono da qualsiasi mia componente, ovvero dall'interruttore on/off e dai sensori di movimento -->
+<attribute category="topic" name="from/$MQTT_DOMAIN/+/gpio/#" value="mqtt_sub"/> <!-- Sottoscrivo i messaggi che notificano il cambiamento di stato dei sensori -->
+<attribute category="topic" name="rpc/$MQTT_DOMAIN/$MQTT_SUBDOMAIN/$MQTT_SERVICE" value="mqtt_sub"/> <!-- Su questo topic ricevero' le richieste di inviare il mio stato attuale -->
+<attribute category="topic" name="rpc/$MQTT_DOMAIN/$MQTT_SUBDOMAIN/$MQTT_SERVICE/#" value="mqtt_sub"/> <!-- Su questo topic ricevero' le richieste di inviare lo stato delle mie componenti, che prendero' dallo stato corrispondente del gpio -->
+<attribute category="topic" name="to/all" value="mqtt_sub"/> <!-- Su questo topic ricevero' un messaggio del tipo {request:descripion.json} Dovro' quindi mandare la mia descrizione json -->
+</set>
diff --git a/antifurto/src/org.eclipse.paho.client.mqttv3_1.2.5.jar b/antifurto/org.eclipse.paho.client.mqttv3_1.2.5.jar
similarity index 100%
rename from antifurto/src/org.eclipse.paho.client.mqttv3_1.2.5.jar
rename to antifurto/org.eclipse.paho.client.mqttv3_1.2.5.jar
diff --git a/antifurto/src/org.json-1.0.0.v201011060100.jar b/antifurto/org.json-1.0.0.v201011060100.jar
similarity index 100%
rename from antifurto/src/org.json-1.0.0.v201011060100.jar
rename to antifurto/org.json-1.0.0.v201011060100.jar
diff --git a/antifurto/src/org.json-chargebee-1.0-javadoc.jar b/antifurto/org.json-chargebee-1.0-javadoc.jar
similarity index 100%
rename from antifurto/src/org.json-chargebee-1.0-javadoc.jar
rename to antifurto/org.json-chargebee-1.0-javadoc.jar
diff --git a/antifurto/src/CONF/conf.json b/antifurto/res/CONF/conf.json
similarity index 58%
rename from antifurto/src/CONF/conf.json
rename to antifurto/res/CONF/conf.json
index e0e44ba3a91cd48fa1ac27fa410d9bb8711e3f18..ac9f9f4261f22335c67b4ff3e3c0899ea7aa2191 100644
--- a/antifurto/src/CONF/conf.json
+++ b/antifurto/res/CONF/conf.json
@@ -3,5 +3,7 @@
     "homedir": "./home",
     "broker": "localhost",
     "protocol": "tcp",
-    "port": 1883
+    "port": 1883,
+    "mqttDomain": "gruppo2",
+    "mqttSubdomain":"luci"
 }
diff --git a/antifurto/res/CONF/deltaSensoriMovimento.json b/antifurto/res/CONF/deltaSensoriMovimento.json
new file mode 100644
index 0000000000000000000000000000000000000000..54e876224801c257831395165991aea616deb60b
--- /dev/null
+++ b/antifurto/res/CONF/deltaSensoriMovimento.json
@@ -0,0 +1 @@
+{"IN2":4,"IN1":33,"IN3":8}
diff --git a/antifurto/res/CONF/zona.json b/antifurto/res/CONF/zona.json
new file mode 100644
index 0000000000000000000000000000000000000000..a702f5b9fb5a0945b7c8b9d7d1866e3785bde0a6
--- /dev/null
+++ b/antifurto/res/CONF/zona.json
@@ -0,0 +1 @@
+{"interruttore":"IN0","sensoriMovimento":["IN1","IN2","IN3"],"outputSuono":"OUT0", "nomeOutputAntifurto":"OUT1"}
diff --git a/antifurto/src/automa.json b/antifurto/res/automa.json
similarity index 100%
rename from antifurto/src/automa.json
rename to antifurto/res/automa.json
diff --git a/antifurto/res/stato.json b/antifurto/res/stato.json
new file mode 100644
index 0000000000000000000000000000000000000000..3842fd7560864474ef86ad6662e976b88122f69e
--- /dev/null
+++ b/antifurto/res/stato.json
@@ -0,0 +1 @@
+{"soglia":50,"stato":0,"valore":0,"tempoAllarme":"2022-07-25T17:17:45.550658"}
\ No newline at end of file
diff --git a/antifurto/src/Antifurto.class b/antifurto/src/Antifurto.class
deleted file mode 100644
index 658211a1a444a9301270913d3a5bb0cea62c7ab4..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Antifurto.class and /dev/null differ
diff --git a/antifurto/src/Automa.class b/antifurto/src/Automa.class
deleted file mode 100644
index 227fd713c0f831f7de384b63c9bc1dd8ce5f2626..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Automa.class and /dev/null differ
diff --git a/antifurto/src/CONF/deltaSensoriMovimento.json b/antifurto/src/CONF/deltaSensoriMovimento.json
deleted file mode 100644
index 798edf6d07714548dd4a4b86ea61df3ce2d5c5e1..0000000000000000000000000000000000000000
--- a/antifurto/src/CONF/deltaSensoriMovimento.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
-    "IN1":33,
-    "IN2":4,
-    "IN3":8
-}
diff --git a/antifurto/src/CONF/zona.json b/antifurto/src/CONF/zona.json
deleted file mode 100644
index 4d6845d2a7658d037e59631a4ed6f3a95cb68701..0000000000000000000000000000000000000000
--- a/antifurto/src/CONF/zona.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
-    "interruttore": "IN0",
-    "sensoriMovimento": [
-      "IN1",
-      "IN2",
-      "IN3"
-    ],
-    "outputSuono":"OUT3"
-}
diff --git a/antifurto/src/Conf.class b/antifurto/src/Conf.class
deleted file mode 100644
index b3ab01929c6ec669e9904ecfb6993e9cb47c0257..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Conf.class and /dev/null differ
diff --git a/antifurto/src/Esecutore.class b/antifurto/src/Esecutore.class
deleted file mode 100644
index 3a10616f2b3ad22f10290a135955c179110b79c0..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Esecutore.class and /dev/null differ
diff --git a/antifurto/src/Esecutore.java b/antifurto/src/Esecutore.java
deleted file mode 100644
index afc44b37e878c1a8e287c59da15d2458dca05db0..0000000000000000000000000000000000000000
--- a/antifurto/src/Esecutore.java
+++ /dev/null
@@ -1,63 +0,0 @@
-import java.time.Duration;
-import java.time.LocalDateTime;
-
-
-public class Esecutore extends Thread {
-	
-	private MyQueue<Integer> codaVal; // coda in cui vengono mantenuti i valori da sommare alla variabile valore
-	private int valore; // variabile numerica cumulativa inizialmente impostata a 0
-	public final int SOGLIA = 100;
-	private Publisher publisher;
-	private Automa automa;
-	private String outputSuono; // nome logico dell'interruttore che fa scattare il suono dell'allarme 
-	
-	
-	public Esecutore(Publisher publisher, MyQueue<Integer> codaVal, Automa automa, String outputSuono) {
-		this.codaVal = codaVal;
-		this.valore = 0;
-		this.automa = automa;
-		this.publisher = publisher;
-		this.outputSuono = outputSuono;
-	}
-	
-	
-	public void run() {
-		final long DURATA_SUONO = 5; // l'allarme dura 5 minuti e poi smette di suonare
-		int delta;
-		LocalDateTime tempoAllarme = null;
-		while(true) {
-			while(automa.antifurtoAttivo()) { System.out.println("VALORE = "+ valore);
-				delta = codaVal.receive();
-				valore = valore + delta;
-				if(valore >= SOGLIA && (!automa.allarme()) ) {	
-					publisher.aggiungiComando("to/gruppo2/luci/gpio/"+outputSuono, "{cmd:1}");
-					tempoAllarme = LocalDateTime.now();
-				}
-				else {
-					if(automa.allarme()) {
-						LocalDateTime tempoAttuale = LocalDateTime.now();
-						long durata = Math.abs(Duration.between(tempoAllarme, tempoAttuale).toMinutes());
-						if(valore < SOGLIA || durata >= DURATA_SUONO || !automa.antifurtoAttivo() ) {
-							publisher.aggiungiComando("to/gruppo2/luci/gpio/"+outputSuono, "{cmd:0}"); // l'allarme viene disattivato
-						}
-					}
-				}
-				
-			}
-			if(!automa.antifurtoAttivo()) {
-				reset();
-			}
-		}
-	}
-
-	
-	public void aggiungiVal(int n) {
-		codaVal.send(n);
-	}
-	
-	public void reset() {
-		valore = 0;
-		codaVal.removeAll();
-	}
-	
-}
diff --git a/antifurto/src/MsgQueue.class b/antifurto/src/MsgQueue.class
deleted file mode 100644
index d6956128de101c25dd7df3fa5b3a936253bc75f9..0000000000000000000000000000000000000000
Binary files a/antifurto/src/MsgQueue.class and /dev/null differ
diff --git a/antifurto/src/MyQueue.class b/antifurto/src/MyQueue.class
deleted file mode 100644
index ed150b738845949457f13c011b425006c71015aa..0000000000000000000000000000000000000000
Binary files a/antifurto/src/MyQueue.class and /dev/null differ
diff --git a/antifurto/src/Pair.class b/antifurto/src/Pair.class
deleted file mode 100644
index 2cac32bc7272b7d02a6aacad0738ef50b5930999..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Pair.class and /dev/null differ
diff --git a/antifurto/src/Pair.java b/antifurto/src/Pair.java
deleted file mode 100644
index 2c47068961be4223ddbf52184e7c2bdd2d88fc1c..0000000000000000000000000000000000000000
--- a/antifurto/src/Pair.java
+++ /dev/null
@@ -1,20 +0,0 @@
-
-public class Pair {
-
-	private String topic;
-	private String msg;
-	
-	
-	public Pair(String topic, String msg) {
-		this.topic = topic;
-		this.msg = msg;
-	}
-	
-	public String getTopic() {
-		return topic;
-	}
-	
-	public String getMsg() {
-		return msg;
-	}
-}
diff --git a/antifurto/src/Publisher.class b/antifurto/src/Publisher.class
deleted file mode 100644
index 3cddd01bee097b77cc544d9436535a0ecc5474f5..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Publisher.class and /dev/null differ
diff --git a/antifurto/src/SubscribeCallback.class b/antifurto/src/SubscribeCallback.class
deleted file mode 100644
index a971029b402f4ad48d870288ad4ad7adb8b289c6..0000000000000000000000000000000000000000
Binary files a/antifurto/src/SubscribeCallback.class and /dev/null differ
diff --git a/antifurto/src/SubscribeCallback.java b/antifurto/src/SubscribeCallback.java
deleted file mode 100644
index be24d4b6270672ebeb62febac497c734bc82d3c3..0000000000000000000000000000000000000000
--- a/antifurto/src/SubscribeCallback.java
+++ /dev/null
@@ -1,137 +0,0 @@
-import java.util.Date;
-
-import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
-import org.eclipse.paho.client.mqttv3.MqttCallback;
-import org.eclipse.paho.client.mqttv3.MqttException;
-import org.eclipse.paho.client.mqttv3.MqttMessage;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-public class SubscribeCallback implements MqttCallback{
-	
-	private Antifurto client;
-	private Publisher publisher;
-	private String nomeInterruttore; 
-	private String nomeOutputSuono;
-	private Esecutore esec;
-	private Automa automa;
-	
-	public SubscribeCallback(Antifurto client, Publisher publisher, String nomeInterruttore, String nomeOutputSuono, Esecutore esec, Automa automa) {
-		this.client = client;
-		this.publisher = publisher;
-		this.nomeInterruttore = nomeInterruttore;
-		this.nomeOutputSuono = nomeOutputSuono;
-		this.esec = esec;
-		this.automa = automa;
-	}
-
-	@Override
-	public void connectionLost(Throwable arg0) {
-		boolean retry = true;
-		final Date d = new Date();
-		Date d2 = new Date();
-		long time = Math.abs(d2.getTime()-d.getTime());
-		while(retry & (time<600000)) {
-			try {
-				client.startClient(esec, publisher);
-				retry = false;
-			} catch (MqttException e) {
-				d2 = new Date();
-				time = Math.abs(d2.getTime()-d.getTime());
-			}
-		}
-		if(time>=600000) {
-			System.out.println("Tentativo di riconnessione fallito");
-			System.exit(1);
-		}
-	}
-
-	
-	@Override
-	public void deliveryComplete(IMqttDeliveryToken arg0) {
-		// Nessuna operazione
-		
-	}
-	
-
-	@Override
-	public void messageArrived(String topic, MqttMessage message) throws Exception {
-		if(topic.equals("to/all"))
-			sendDescription("from/gruppo2/luci/antifurto/description");
-		else {
-			if(topic.equals("rpc/gruppo2/luci/antifurto"))
-				sendMyState("from/gruppo2/luci/antifurto"); // CONTROLLA SE VA BENE PUBBLICARE LO STATO SU QUESTO TOPIC O SE IL TOPIC DEVE ESSERE UN'ALTRO. NOTA: NON POSSO PUBBLICARE SULLO STESSO TOPIC CHE HO SOTTOSCRITTO
-			else {
-				JSONObject msgJson = new JSONObject(message.toString());
-				
-				
-				// CONTROLLA SULLA BEAGLEBONE CHE IL MESSAGGIO MANDATO SIA UN INT. CONTROLLA ANCHE IL TOPIC SU CUI MANDA I MESSAGGI (da aver sottoscritto i topic correttamente)
-				
-				if(topic.equals("from/gruppo2/luci/gpio/"+nomeOutputSuono)) {
-					int newStatus = -1;
-					if(msgJson.has("status"))
-						newStatus = msgJson.getInt("status");
-					else {
-						if(msgJson.has("event"))
-							newStatus = msgJson.getInt("event");
-					}
-					handleStateMsgFromOutputSuono(newStatus);
-				}
-				else {
-					int event = msgJson.getInt("event");
-					if(event==0) {
-						// e' stato premuto l'interruttore / il sensore di movimento ha rilevato qualcuno
-						if(topic.equals("from/gruppo2/luci/gpio/"+nomeInterruttore))
-							handleStateMsgFromInterruttore();
-						else {
-							// il topic sara' from/gruppo2/luci/gpio/IN0  dove IN0 e' un sensore di movimento
-							String[] t = topic.split("/");
-							handleMovimento(t[4]);
-						}
-					}
-				}				
-			}
-		}	
-		
-	}
-	
-
-	
-	private synchronized void handleStateMsgFromInterruttore() throws JSONException {
-		automa.changeStatoInterruttore();
-		if(automa.getStatoInterruttore().equals("off")) {
-			publisher.aggiungiComando("to/gruppo2/luci/gpio/"+nomeOutputSuono, "{cmd:0}"); 
-			esec.reset();
-		}
-	}
-	
-	
-	private synchronized void handleStateMsgFromOutputSuono(int newStatus) throws JSONException {
-		if(newStatus!=-1) {
-			String statusOnOff = automa.converter(newStatus); // lo stato e' della forma "on" oppure "off"
-			if(! statusOnOff.equals(automa.getStatoSuono()) ) {
-				automa.aggiornaStatoSuono(statusOnOff);
-			}
-		}
-	}
-	
-
-	
-	
-	private void handleMovimento(String nomeSensore) {
-		if(automa.getStatoInterruttore().equals("on"))
-			esec.aggiungiVal(automa.getDelta(nomeSensore));
-	}
-	
-	private void sendMyState(String topic) throws MqttException {
-		publisher.aggiungiComando(topic, "{\"status\":"+automa.getStatoAutoma()+"}"); 
-	}
-	
-	private void sendDescription(String topic) {
-		// DA FARE: guardare quale descrizione manda netmon, archiver, meter,... e implementare di conseguenza questo metodo
-//		String msg = 
-//		publisher.aggiungiComando(topic, msg); 
-	}
-	
-
-}
diff --git a/antifurto/src/Timer.class b/antifurto/src/Timer.class
deleted file mode 100644
index a922d3a359f247a50f10d27f2ab8cc235c553dd6..0000000000000000000000000000000000000000
Binary files a/antifurto/src/Timer.class and /dev/null differ
diff --git a/antifurto/src/ValQueue.class b/antifurto/src/ValQueue.class
deleted file mode 100644
index e05e8939d7f67878f2f2d04707cf78247d069d4b..0000000000000000000000000000000000000000
Binary files a/antifurto/src/ValQueue.class and /dev/null differ
diff --git a/antifurto/src/Antifurto.java b/antifurto/src/code/Antifurto.java
similarity index 66%
rename from antifurto/src/Antifurto.java
rename to antifurto/src/code/Antifurto.java
index 1a54c583dcc56d6fed1a00c310c0382d044243f7..9c13607e7689fa300d19c0228e469e7ebd72c955 100644
--- a/antifurto/src/Antifurto.java
+++ b/antifurto/src/code/Antifurto.java
@@ -1,3 +1,4 @@
+package code;
 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
@@ -9,6 +10,7 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
 import org.eclipse.paho.client.mqttv3.MqttException;
 import org.eclipse.paho.client.mqttv3.MqttMessage;
 import org.eclipse.paho.client.mqttv3.MqttTopic;
+import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -18,56 +20,80 @@ public class Antifurto {
 	private static String brokerUrl;
 	private String interruttore;
 	private String interruttoreOutputSuono;
+	private String nomeOutputAntifurto;
+	private static JSONArray sensori;  // sensori di movimento
 	private static ArrayList<String> topicsSub;
 	private Date date = new Date();
 	private String clientId = Long.toString(date.getTime()) + "-sub-pub"; // unique client id
 	private Automa automa;
 	
 	private MqttClient mqttClient;
+	private static String mqttDomain;
+	private static String mqttSubdomain;
+	
+	private final String CONF_FILE = "../res/CONF/conf.json";
+	public static final String CONF_ZONA = "../res/CONF/zona.json";
 	
 	public Antifurto(Automa automa) throws JSONException, IOException, MqttException {
 		this.automa = automa;
 		
-		JSONObject jsonObject = new JSONObject(leggiFile("./CONF/conf.json"));
+		JSONObject jsonObject = new JSONObject(Helper.leggiFile(CONF_FILE));
 		brokerUrl = jsonObject.getString("protocol") + "://" + jsonObject.getString("broker") + ":" + jsonObject.getInt("port");
+		mqttDomain = jsonObject.getString("mqttDomain");
+		mqttSubdomain = jsonObject.getString("mqttSubdomain");
 		topicsSub = new ArrayList<String>();
 		
-		// Su questo topic ricevero' un messaggio del tipo {request:description.json} 
+		// Su questo topic ricevero' un messaggio del tipo {request:description} 
 		// Dovro' quindi mandare la mia descrizione json
 		topicsSub.add("to/all"); 
 		
 		// Su questo topic ricevero' le richieste di inviare il mio stato attuale
-		topicsSub.add("rpc/gruppo2/luci/antifurto");
+		topicsSub.add("rpc/"+getMqttTree()+"/antifurto");
 		
 		
-		jsonObject = new JSONObject(leggiFile("./CONF/zona.json"));
+		jsonObject = new JSONObject(Helper.leggiFile(CONF_ZONA));
 		interruttore = jsonObject.getString("interruttore"); 
-		topicsSub.add("from/gruppo2/luci/gpio/" + interruttore); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
+		
+		topicsSub.add("from/"+getMqttTree()+"/gpio/" + interruttore); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
 		
 		// Per ogni sensore di movimento, sottoscrivo i messaggi che notificano il loro cambiamento di stato 
-		JSONArray sensori = jsonObject.getJSONArray("sensoriMovimento");
+		sensori = jsonObject.getJSONArray("sensoriMovimento");
 		for(int i=0; i<sensori.length(); i++) {
-			topicsSub.add("from/gruppo2/luci/gpio/" + sensori.get(i)); 
+			topicsSub.add("from/"+getMqttTree()+"/gpio/" + sensori.get(i)); 
 		}
 		
+		nomeOutputAntifurto = jsonObject.getString("nomeOutputAntifurto");
+		topicsSub.add("from/"+getMqttTree()+"/gpio/" + nomeOutputAntifurto);
+		
 		interruttoreOutputSuono = jsonObject.getString("outputSuono");
-		topicsSub.add("from/gruppo2/luci/gpio/" + interruttoreOutputSuono); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
+		topicsSub.add("from/"+getMqttTree()+"/gpio/" + interruttoreOutputSuono); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
+		
 		
+		topicsSub.add("to/"+getMqttTree()+"/antifurto/soglia"); // Su questo topic mi arrivera' un messaggio {"soglia": 30} e dovrò impostare la soglia di conseguenza
 		
-		this.mqttClient = new MqttClient(brokerUrl, clientId);
+		topicsSub.add("conf/"+getMqttTree()+"/antifurto/sensore"); // Su questo topic mi arrivera' un messaggio per l'aggiunta di un sensore di movimento. 
+																   // Ad esempio se mi arriva il messaggio {"in": "IN3", "delta":33 } devo aggiungere il sensore di movimento che si 
+																   // chiama IN3, il cui valore di delta e' 33 (devo quindi aggiornare il file deltaSensoriMovimento.json
+		
+		this.mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
 		
 	}
 	
 	public void startClient(Esecutore esec, Publisher publisher) throws MqttException {
 		MqttConnectOptions options = new MqttConnectOptions();
 		options.setCleanSession(false);
-		mqttClient.setCallback(new SubscribeCallback(this, publisher, interruttore, interruttoreOutputSuono, esec, automa));
+		mqttClient.setCallback(new SubscribeCallback(this, publisher, interruttore, interruttoreOutputSuono, esec, automa, nomeOutputAntifurto));
 		
 		mqttClient.connect(options);
 		
 		
 		for(String t: topicsSub) 
-			mqttClient.subscribe(t);
+			addTopicToSubscribe(t);
+	}
+	
+	// sottoscrive il topic passato come parametro
+	public void addTopicToSubscribe(String topic) throws MqttException {
+		mqttClient.subscribe(topic);
 	}
 	
 	public void publishMethod(String topic, String msg) throws MqttException {
@@ -75,17 +101,17 @@ public class Antifurto {
 		msgTopic.publish(new MqttMessage(msg.getBytes()));
 	}
 	
-	private String leggiFile(String path) throws IOException {
-		String line;
-		String answer = "";
-		FileReader fileReader = new FileReader(path);
-		BufferedReader bufferedReader = new BufferedReader(fileReader);
-		while((line = bufferedReader.readLine()) != null) {
-			answer += line;
-		}
-		bufferedReader.close();
-		return answer;
-	}
+//	private String leggiFile(String path) throws IOException {
+//		String line;
+//		String answer = "";
+//		FileReader fileReader = new FileReader(path);
+//		BufferedReader bufferedReader = new BufferedReader(fileReader);
+//		while((line = bufferedReader.readLine()) != null) {
+//			answer += line;
+//		}
+//		bufferedReader.close();
+//		return answer;
+//	}
 	
 	
 	
@@ -172,7 +198,7 @@ public class Antifurto {
 		Antifurto antifurto = new Antifurto(automa);
 		Publisher publisher = new Publisher(codaMsg, antifurto);
 		Esecutore esec = new Esecutore(publisher, codaVal, automa, antifurto.interruttoreOutputSuono);
-		Timer timer = new Timer(30000,-5,esec,automa);
+		Timer timer = new Timer(6000,-1,esec,automa);
 		
 		antifurto.startClient(esec, publisher);
 		publisher.start();
@@ -180,8 +206,21 @@ public class Antifurto {
 		timer.start();
 	}
 
+	public static void stopSystem() {
+		
+	}
 	
+	public static String getMqttTree() {
+		return mqttDomain+"/"+mqttSubdomain;
+	}
+
+	public static JSONArray getSensori() {
+		return sensori;
+	}
 	
+	public static void addSensore(String newSensore) { // aggiunge un sensore di movimento
+		sensori.put(newSensore);
+	}
 	
 
 }
diff --git a/antifurto/src/Automa.java b/antifurto/src/code/Automa.java
similarity index 63%
rename from antifurto/src/Automa.java
rename to antifurto/src/code/Automa.java
index 0bf0d4549640f7864c14bc67ae4490eabb50dae9..9b0a8e8ac2945b9abddd0857ef2b9013550a1f52 100644
--- a/antifurto/src/Automa.java
+++ b/antifurto/src/code/Automa.java
@@ -1,5 +1,4 @@
-import java.io.BufferedReader;
-import java.io.FileReader;
+package code;
 import java.io.IOException;
 import java.util.Hashtable;
 import java.util.Iterator;
@@ -13,20 +12,36 @@ public class Automa {
 	private int statoAttuale;
 	private String statoInterruttore;
 	private String statoSuono;
+	private static final String FILE_AUTOMA = "../res/automa.json";
+	public static final String FILE_STATO = "../res/stato.json";
+	public static final String FILE_DELTA_SENSORI = "../res/CONF/deltaSensoriMovimento.json";
 	
 	
 	public Automa() throws JSONException, IOException {
-		this.jsonObject = new JSONObject(leggiFile("./automa.json"));
-		this.statoInterruttore = "off";
-		this.statoSuono = "off";
-		this.statoAttuale = 0;
+		this.jsonObject = new JSONObject(Helper.leggiFile(FILE_AUTOMA));
+		setStati(false);
 		riempiHashTable();
 	}
 	
 	
+	private synchronized void setStati(boolean write) throws JSONException, IOException {
+		JSONObject statoJson = new JSONObject(Helper.leggiFile(FILE_STATO)); 
+		if(write) {
+			// devo aggiornare lo stato nel FILE_STATO
+			Helper.scriviFile(statoJson.put("stato",this.statoAttuale), FILE_STATO);
+		}
+		else {
+			// devo capire in quale stato mi trovo e impostare di conseguenza lo statoInterruttore e lo statoSuono
+			this.statoAttuale = statoJson.getInt("stato");
+		}
+		aggiornaInterruttoreESuono();
+	}
+	
+	
 	private void riempiHashTable() throws JSONException, IOException {
 		this.deltaSensori = new Hashtable<String, Integer>();
-		JSONObject jsObj = new JSONObject(leggiFile("./CONF/deltaSensoriMovimento.json"));
+		JSONObject jsObj = new JSONObject(Helper.leggiFile(FILE_DELTA_SENSORI));
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsObj.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
@@ -35,19 +50,29 @@ public class Automa {
 		}
 	}
 	
-	
-	private String leggiFile(String path) throws IOException {
-		String line;
-		String answer = "";
-		FileReader fileReader = new FileReader(path);
-		BufferedReader bufferedReader = new BufferedReader(fileReader);
-		while((line = bufferedReader.readLine()) != null) {
-			answer += line;
-		}
-		bufferedReader.close();
-		return answer;
+	public void addDeltaSensori(String nomeSensore, int delta) {
+		deltaSensori.put(nomeSensore, delta);
 	}
 	
+//	private synchronized void scriviFile(JSONObject json, String path) throws IOException {
+//		BufferedWriter b = new BufferedWriter(new FileWriter(path));
+//		b.write(json.toString());
+//		b.close();
+//	}
+	
+	
+//	private String leggiFile(String path) throws IOException {
+//		String line;
+//		String answer = "";
+//		FileReader fileReader = new FileReader(path);
+//		BufferedReader bufferedReader = new BufferedReader(fileReader);
+//		while((line = bufferedReader.readLine()) != null) {
+//			answer += line;
+//		}
+//		bufferedReader.close();
+//		return answer;
+//	}
+	
 	public int getDelta(String nomeSensore) {
 		return deltaSensori.get(nomeSensore);
 	}
@@ -68,19 +93,21 @@ public class Automa {
 	
 	
 	// e' cambiato lo stato dell'interruttore, per cui cerco nel file json in quale nuovo stato devo andare
-	private synchronized void calcolaNuovoStatoMsgFromInterruttore(String newStatoInterruttore) throws JSONException {
+	private synchronized void calcolaNuovoStatoMsgFromInterruttore(String newStatoInterruttore) throws JSONException, IOException {
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsonObject.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
 			JSONObject riga = jsonObject.getJSONObject(key);
 			if(riga.getInt("stato")==statoAttuale) {
 				this.statoAttuale = riga.getInt("cmd"+newStatoInterruttore);
-				aggiornaInterruttoreESuono();
+				setStati(true); //scrivo nel file il nuovo stato in cui mi trovo
 			}
 		}
 	}
 	//in base allo stato attuale dell'antifurto, calcolo lo stato dell'interruttore e del suono
 	private synchronized void aggiornaInterruttoreESuono() throws JSONException {
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsonObject.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
@@ -93,38 +120,39 @@ public class Automa {
 	}
 	
 	// e' cambiato lo stato del suono, per cui cerco nel file json in quale nuovo stato devo andare
-	private synchronized void calcolaNuovoStatoMsgFromSuono(String newStatoSuono) throws JSONException {
+	private synchronized void calcolaNuovoStatoMsgFromSuono(String newStatoSuono) throws JSONException, IOException {
 		String jsonKey = "";
 		if(newStatoSuono.equals("on"))
 			jsonKey = "eventValMaggioreSoglia";
 		else
 			jsonKey = "eventValMinoreSoglia";
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsonObject.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
 			JSONObject riga = jsonObject.getJSONObject(key);
 			if(riga.getInt("stato")==statoAttuale) {
 				this.statoAttuale = riga.getInt(jsonKey);
-				aggiornaInterruttoreESuono();
+				setStati(true); //scrivo nel file il nuovo stato in cui mi trovo
 			}
 		}
 	}
 	
 	
-	public synchronized void changeStatoInterruttore() throws JSONException {
+	public synchronized void changeStatoInterruttore() throws JSONException, IOException {
 		if(statoInterruttore.equals("on"))
 			calcolaNuovoStatoMsgFromInterruttore("off");
 		else 
 			calcolaNuovoStatoMsgFromInterruttore("on");
 	}
 	
-	public synchronized void aggiornaStatoSuono(String newStatoSuono) throws JSONException {
+	public synchronized void aggiornaStatoSuono(String newStatoSuono) throws JSONException, IOException {
 		calcolaNuovoStatoMsgFromSuono(newStatoSuono);
 	}
 	
 	
-	public synchronized String getStatoAutoma() {
-		return "{\"stato\":"+statoAttuale+",\"interruttore\":\""+statoInterruttore+"\",\"allarme\":\""+statoSuono+"\"}";
+	public synchronized int getStatoAutoma() {
+		return statoAttuale;
 	}
 	
 	
@@ -137,6 +165,14 @@ public class Automa {
 		return statoSuono;
 	}
 	
+	public synchronized boolean getStatoSuonoTrueFalse() {
+		return statoSuono.equals("on");
+	}
+	
+	public synchronized boolean getStatoInterrutoreTrueFalse() {
+		return statoInterruttore.equals("on");
+	}
+	
 	
 	// Ritorna true se l'antifurto e' attivo
 	public synchronized boolean antifurtoAttivo() {
diff --git a/antifurto/src/code/Esecutore.java b/antifurto/src/code/Esecutore.java
new file mode 100644
index 0000000000000000000000000000000000000000..2a52fda64098c751f563f57b20a41d08af5b7641
--- /dev/null
+++ b/antifurto/src/code/Esecutore.java
@@ -0,0 +1,123 @@
+package code;
+import java.io.IOException;
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+
+public class Esecutore extends Thread {
+	
+	private MyQueue<Integer> codaVal; // coda in cui vengono mantenuti i valori da sommare alla variabile valore
+	private int valore; // variabile numerica cumulativa inizialmente impostata a 0
+	private static  int soglia;
+	private Publisher publisher;
+	private Automa automa;
+	private String outputSuono; // nome logico dell'interruttore che fa scattare il suono dell'allarme 
+	private LocalDateTime tempoAllarme; //valorizzato solo quando l'allarme sta suonando. Contiene l'ora in cui l'allarme ha iniziato a suonare 
+	private static long allarmeTimeout;
+	
+	public Esecutore(Publisher publisher, MyQueue<Integer> codaVal, Automa automa, String outputSuono) throws JSONException, IOException {
+		this.codaVal = codaVal;
+		this.automa = automa;
+		this.publisher = publisher;
+		this.outputSuono = outputSuono;
+		
+		JSONObject statoJson = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
+		this.valore = statoJson.getInt("valore");
+		setSoglia(statoJson.getInt("soglia"));
+		if(statoJson.getInt("stato")==2)
+			this.tempoAllarme = LocalDateTime.parse(statoJson.getString("tempoAllarme"));
+	}
+	
+	private int getSogliaMax() {
+		return Math.round(soglia+soglia*0.2f);  // il valore non puo' andare oltre il 20 % sopra la soglia 
+	}
+	
+	public void run() {
+		final long DURATA_SUONO = 1; // l'allarme dura 1 minuti e poi smette di suonare. 
+		int delta;
+		int valoreToSend = valore; // ogni volta che aumento / diminuisco il valore di 5, notifico la web app pubblicando un messaggio 
+		while(true) {
+			while(automa.antifurtoAttivo()) { System.out.println("VALORE = "+ valore);
+				delta = codaVal.receive();
+				valore = valore + delta;
+				if(valore < 0)
+					valore = 0;
+				if(valore > getSogliaMax())
+					valore = getSogliaMax();
+				try {
+					if(Math.abs(valore-valoreToSend) >= 5) {
+						JSONObject msgJson = new JSONObject();
+						msgJson.put("event", valore);
+						publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/valore", msgJson.toString());
+						valoreToSend = valore;
+					}
+					
+					JSONObject statoJson = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
+					statoJson.put("valore", valore);
+					if(valore >= soglia && (!automa.allarme()) && delta>0) {	
+						publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/gpio/"+outputSuono, "{cmd:1}");
+						tempoAllarme = LocalDateTime.now();
+						statoJson.put("tempoAllarme",tempoAllarme.toString());
+					}
+					else {
+						if(automa.allarme()) {
+							LocalDateTime tempoAttuale = LocalDateTime.now();
+							long durata = Math.abs(Duration.between(tempoAllarme, tempoAttuale).toMinutes());
+							if(valore < soglia || durata >= DURATA_SUONO || !automa.antifurtoAttivo() ) {
+								publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/gpio/"+outputSuono, "{cmd:0}"); // l'allarme viene disattivato
+							}
+						}
+					}
+					statoJson.put("soglia", soglia);
+					statoJson.put("stato", automa.getStatoAutoma());
+					Helper.scriviFile(statoJson, Automa.FILE_STATO); 
+				}
+				catch (JSONException e) {
+					e.printStackTrace();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+				
+			}
+			if(!automa.antifurtoAttivo()) {
+				reset();
+			}
+		}
+	}
+
+	
+	public void aggiungiVal(int n) {
+		codaVal.send(n);
+	}
+	
+	public void reset() {
+		valore = 0;
+		codaVal.removeAll();
+	}
+	
+	public static int getSoglia() {
+		return soglia;
+	}
+	
+	public int getValore() {
+		return valore;
+	}
+	
+	public static long getAllarmeTimeout() {
+		return allarmeTimeout;
+	}
+	
+	public static void setSoglia(int newValue) throws JSONException, IOException {
+		JSONObject js = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
+		js.put("soglia", newValue);
+		Helper.scriviFile(js, Automa.FILE_STATO);
+		soglia = newValue;
+	}
+	
+}
diff --git a/antifurto/src/code/Helper.java b/antifurto/src/code/Helper.java
new file mode 100644
index 0000000000000000000000000000000000000000..7732e4c5afee2dbd7374c78d6744a8d2cb78ddc1
--- /dev/null
+++ b/antifurto/src/code/Helper.java
@@ -0,0 +1,123 @@
+package code;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class Helper {
+
+	public static synchronized void scriviFile(JSONObject json, String path) throws IOException {
+		BufferedWriter b = new BufferedWriter(new FileWriter(path));
+		b.write(json.toString());
+		b.close();
+	}
+	
+	public static synchronized String leggiFile(String path) throws IOException {
+		String line;
+		String answer = "";
+		FileReader fileReader = new FileReader(path);
+		BufferedReader bufferedReader = new BufferedReader(fileReader);
+		while((line = bufferedReader.readLine()) != null) {
+			answer += line;
+		}
+		bufferedReader.close();
+		return answer;
+	}
+	
+	// se add = true, aggiungo il valore n alla codaVal; 
+	// se add = false, rimuovo il valore n dalla codaVal
+//	public static synchronized void modificaFileStato(MyQueue<Integer> coda, boolean add, int n, int valore, String path) {
+//		try {
+//			JSONObject statoJson = new JSONObject(Helper.leggiFile(path));
+//			statoJson.put("valore",valore);
+//			JSONArray arrayCodaVal = statoJson.getJSONArray("codaVal");
+//			if(add)
+//				arrayCodaVal.put(n);
+//			else {
+//				int index = -1;
+//				for(int i=0; i<arrayCodaVal.length(); i++) {
+//					if(arrayCodaVal.getInt(i)==n)
+//						index = i;
+//				}
+//				arrayCodaVal.remove(index);
+//			}
+//			Helper.scriviFile(statoJson.put("codaVal",arrayCodaVal), path);
+//		} catch (JSONException e) {
+//			e.printStackTrace();
+//		} catch (IOException e) {
+//			e.printStackTrace();
+//		}
+//	}
+//	
+//	public static synchronized void modificaFileStato(boolean add, int n, String path) {
+//		try {
+//			JSONObject statoJson = new JSONObject(Helper.leggiFile(path));
+//			JSONArray arrayCodaVal = statoJson.getJSONArray("codaVal");
+//			if(add)
+//				arrayCodaVal.put(n);
+//			else {
+//				int index = -1;
+//				for(int i=0; i<arrayCodaVal.length(); i++) {
+//					if(arrayCodaVal.getInt(i)==n)
+//						index = i;
+//				}
+//				arrayCodaVal.remove(index);
+//			}
+//			Helper.scriviFile(statoJson.put("codaVal",arrayCodaVal), path);
+//		} catch (JSONException e) {
+//			e.printStackTrace();
+//		} catch (IOException e) {
+//			e.printStackTrace();
+//		}
+//	}
+//
+//	public static synchronized void modificaFileStato(boolean add, Pair p, String path) {
+//		try { System.out.println("pair = " + p+ " path  = " + path);
+//			JSONObject statoJson = new JSONObject(Helper.leggiFile(path)); 
+//			JSONArray arrayCodaMsg = statoJson.getJSONArray("codaMsg"); 
+//			if(add) 
+//				arrayCodaMsg.put(p.toJsonObject());
+//			else {
+//				int index = -1;
+//				for(int i=0; i<arrayCodaMsg.length(); i++) {
+//					JSONObject msgJson = arrayCodaMsg.getJSONObject(i); 
+//					if(msgJson.getString("topic").equals(p.getTopic()) && msgJson.getJSONObject("msg").toString().equals(p.getMsg()) )
+//						index = i;
+//				}
+//				arrayCodaMsg.remove(index);
+//			}
+//			Helper.scriviFile(statoJson.put("codaMsg",arrayCodaMsg), path);  System.out.println("FINE");
+//		} catch (JSONException e) {
+//			e.printStackTrace();
+//		} catch (IOException e) {
+//			e.printStackTrace();
+//		}
+//	}
+	
+//	public static synchronized <T> void getFromFileStato(MyQueue<T> coda, String key, String path) throws JSONException, IOException {
+//		JSONObject statoJson = new JSONObject(Helper.leggiFile(path));
+//		JSONArray arrayCoda = statoJson.getJSONArray(key);
+//		if(coda.getClass().equals(Pair.class)) {
+//			MyQueue<Pair> codaMsg = (MyQueue<Pair>) coda;
+//			for(int i = 0; i<arrayCoda.length(); i++) {
+//				JSONObject pairJson = arrayCoda.getJSONObject(i);
+//				Pair p = new Pair(pairJson.getString("topic"), pairJson.getString("msg"));
+//				codaMsg.send(p);
+//				
+//			}
+//		}
+//		if(coda.getClass().equals(Integer.class)) {
+//			MyQueue<Integer> codaVal = (MyQueue<Integer>) coda;
+//			for(int i = 0; i<arrayCoda.length(); i++) {
+//				codaVal.send(arrayCoda.getInt(i));
+//			}
+//		}
+//			
+//	}
+	
+}
diff --git a/antifurto/src/MyQueue.java b/antifurto/src/code/MyQueue.java
similarity index 97%
rename from antifurto/src/MyQueue.java
rename to antifurto/src/code/MyQueue.java
index 1d4553821deb6a59ba1f1012bfbdef9f2504801e..691cbbdf795066c55b15a17bc87203af819e7c2b 100644
--- a/antifurto/src/MyQueue.java
+++ b/antifurto/src/code/MyQueue.java
@@ -1,3 +1,4 @@
+package code;
 import java.util.ArrayList;
 
 public class MyQueue<T> {
diff --git a/antifurto/src/code/Pair.java b/antifurto/src/code/Pair.java
new file mode 100644
index 0000000000000000000000000000000000000000..977d71ede54c2b42befad81c7b1901f9bf2c6751
--- /dev/null
+++ b/antifurto/src/code/Pair.java
@@ -0,0 +1,39 @@
+package code;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class Pair {
+
+	private String topic;
+	private String msg;
+	
+	
+	public Pair(String topic, String msg) {
+		this.topic = topic;
+		this.msg = msg;
+	}
+	
+	public String getTopic() {
+		return topic;
+	}
+	
+	public String getMsg() {
+		return msg;
+	}
+	
+	public JSONObject toJsonObject() throws JSONException {
+		JSONObject js = new JSONObject();
+		js.put("topic", topic);
+		js.put("msg", msg); System.out.println(msg);
+		return js;
+	}
+	
+	public String toString() {
+		try {
+			return toJsonObject().toString();
+		} catch (JSONException e) {
+			e.printStackTrace();
+		}
+		return null;
+	}
+}
diff --git a/antifurto/src/Publisher.java b/antifurto/src/code/Publisher.java
similarity index 88%
rename from antifurto/src/Publisher.java
rename to antifurto/src/code/Publisher.java
index 2309b0634ec7c2b46702f22b4acf45c1879e90a2..becc9b0005f6271a50d80e6505fe38776c6ca54f 100644
--- a/antifurto/src/Publisher.java
+++ b/antifurto/src/code/Publisher.java
@@ -1,5 +1,7 @@
+package code;
 import org.eclipse.paho.client.mqttv3.MqttException;
 
+
 public class Publisher extends Thread {
 
 	private MyQueue<Pair> coda;
@@ -11,7 +13,8 @@ public class Publisher extends Thread {
 	}
 	
 	public void aggiungiComando(String topic, String msg) {
-		coda.send(new Pair(topic, msg));
+		Pair p = new Pair(topic, msg);  
+		coda.send(p);
 	}
 	
 	
diff --git a/antifurto/src/code/SubscribeCallback.java b/antifurto/src/code/SubscribeCallback.java
new file mode 100644
index 0000000000000000000000000000000000000000..39a64256237330da7ce02e3d25a06f0fdbb156ef
--- /dev/null
+++ b/antifurto/src/code/SubscribeCallback.java
@@ -0,0 +1,248 @@
+package code;
+import java.io.IOException;
+import java.util.Date;
+
+import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
+import org.eclipse.paho.client.mqttv3.MqttCallback;
+import org.eclipse.paho.client.mqttv3.MqttException;
+import org.eclipse.paho.client.mqttv3.MqttMessage;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class SubscribeCallback implements MqttCallback{
+	
+	private Antifurto client;
+	private Publisher publisher;
+	private String nomeInterruttore; 
+	private String nomeOutputSuono;
+	private String nomeOutputAntifurto;
+	private Esecutore esec;
+	private Automa automa;
+	
+	public SubscribeCallback(Antifurto client, Publisher publisher, String nomeInterruttore, String nomeOutputSuono, Esecutore esec, Automa automa, String nomeOutputAntifurto) {
+		this.client = client;
+		this.publisher = publisher;
+		this.nomeInterruttore = nomeInterruttore;
+		this.nomeOutputSuono = nomeOutputSuono;
+		this.nomeOutputAntifurto = nomeOutputAntifurto;
+		this.esec = esec;
+		this.automa = automa;
+	}
+
+	@Override
+	public void connectionLost(Throwable arg0) {
+		boolean retry = true;
+		final Date d = new Date();
+		Date d2 = new Date();
+		long time = Math.abs(d2.getTime()-d.getTime());
+		while(retry & (time<600000)) {
+			try {
+				client.startClient(esec, publisher);
+				retry = false;
+			} catch (MqttException e) {
+				d2 = new Date();
+				time = Math.abs(d2.getTime()-d.getTime());
+			}
+		}
+		if(time>=600000) {
+			System.out.println("Tentativo di riconnessione fallito");
+			System.exit(1);
+		}
+	}
+
+	
+	@Override
+	public void deliveryComplete(IMqttDeliveryToken arg0) {
+		// Nessuna operazione
+		
+	}
+	
+
+	@Override
+	public void messageArrived(String topic, MqttMessage message) throws Exception { 
+		
+		if(topic.equals("to/all")) {
+			System.out.println("MESSAGGIO MQTT = "+message.toString());
+			if(message.toString().equals("{request:description}"))
+				sendDescription("from/"+Antifurto.getMqttTree()+"/antifurto/description");
+			if(message.toString().equals("{request:status}"))
+				sendMyStateToAll("from/"+Antifurto.getMqttTree()+"/antifurto");  // DA FARE: vedi cosa pubblicano gli altri microservizi e implementa di conseguenza questa funzione
+		}
+		else {
+			JSONObject msgJson = new JSONObject(message.toString());
+			if(topic.equals("conf/"+Antifurto.getMqttTree()+"/antifurto/sensore")) {
+				if(msgJson.has("in") && msgJson.has("delta")) 
+					handleConfSensoreMovimento(msgJson);
+			}
+			else {
+				if(topic.equals("to/"+Antifurto.getMqttTree()+"/antifurto/soglia") && msgJson.has("soglia")) {
+					handleSetSoglia(msgJson);
+				}
+				else {
+					if(topic.equals("rpc/"+Antifurto.getMqttTree()+"/antifurto") && message.toString().equals("{\"request\":\"description\"}"))
+						sendMyState("from/"+Antifurto.getMqttTree()+"/antifurto");  
+					else {
+						if(topic.equals("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputSuono)) {
+							int newStatus = -1;
+							if(msgJson.has("status"))
+								newStatus = msgJson.getInt("status");
+							else {
+								if(msgJson.has("event"))
+									newStatus = msgJson.getInt("event");
+							}
+							handleStateMsgFromOutputSuono(newStatus);
+						}
+						else {
+							if(topic.equals("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputAntifurto)) {
+								if(msgJson.has("event"))
+									handleLuceAntifurto();
+							}
+							else {
+								int event = msgJson.getInt("event");
+								if(event==1) {
+									// e' stato premuto l'interruttore / il sensore di movimento ha rilevato qualcuno
+									if(topic.equals("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeInterruttore))
+										handleStateMsgFromInterruttore();
+									else {
+										// il topic sara' from/gruppo2/luci/gpio/IN0  dove IN0 e' un sensore di movimento
+										System.out.println("TOPIC = "+topic);
+										String[] t = topic.split("/");
+										handleMovimento(t[4]);
+									}
+								}
+							}
+						}				
+					}					
+				}
+				
+			}
+		}	
+		
+	}
+	
+
+	
+	private synchronized void handleStateMsgFromInterruttore() throws JSONException, IOException {
+		if(automa.getStatoInterruttore().equals("on")) 
+			publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputAntifurto, "{cmd:0}"); // voglio spegnere l'antifurto, quindi invio un messaggio per spegnere la luce che indica che l'antifurto e' acceso
+		else 
+			publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputAntifurto, "{cmd:1}"); // voglio accendere l'antifurto, quindi invio un messaggio per accendere la luce che indica che l'antifurto e' acceso
+	}
+	
+	private synchronized void handleLuceAntifurto() throws JSONException {
+		try {
+		automa.changeStatoInterruttore();
+		if(automa.getStatoInterruttore().equals("off")) {
+			publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputSuono, "{cmd:0}"); 
+			esec.reset();
+		}		
+		JSONObject js = new JSONObject();
+		js.put("event", automa.getStatoInterrutoreTrueFalse());
+		publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/antifurto", js.toString());
+		}
+		catch(IOException e) {
+			JSONObject jsError = new JSONObject();
+			jsError.put("error", e.getMessage());
+			publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/antifurto", jsError.toString());
+		}
+	}
+	
+	
+	private synchronized void handleStateMsgFromOutputSuono(int newStatus) throws JSONException, IOException {
+		if(newStatus!=-1) {
+			String statusOnOff = automa.converter(newStatus); // lo stato e' della forma "on" oppure "off"
+			if(! statusOnOff.equals(automa.getStatoSuono()) ) {
+				automa.aggiornaStatoSuono(statusOnOff);
+				JSONObject js = new JSONObject();
+				js.put("event", automa.getStatoSuonoTrueFalse());
+				publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/allarme", js.toString());
+			}
+		}
+	}
+	
+
+	
+	
+	private void handleMovimento(String nomeSensore) { 
+		if(automa.getStatoInterruttore().equals("on"))
+			esec.aggiungiVal(automa.getDelta(nomeSensore));
+	}
+	
+	private void handleConfSensoreMovimento(JSONObject toAdd) throws JSONException { 
+		// aggiorno il file che contiene l'associazione sensore-movimento, delta
+		try {
+			JSONObject sensori = new JSONObject(Helper.leggiFile(Automa.FILE_DELTA_SENSORI));
+			String nomeSensore = toAdd.getString("in").toUpperCase();
+			int delta = toAdd.getInt("delta");
+			sensori.put(nomeSensore, delta);
+			Helper.scriviFile(sensori, Automa.FILE_DELTA_SENSORI);
+			
+			// aggiorno il file zona: ho un sensore di movimento in più
+			JSONObject zona = new JSONObject(Helper.leggiFile(Antifurto.CONF_ZONA));
+			zona.getJSONArray("sensoriMovimento").put(nomeSensore);
+			Helper.scriviFile(zona, Antifurto.CONF_ZONA);
+			Antifurto.addSensore(nomeSensore);
+			automa.addDeltaSensori(nomeSensore, delta);
+			client.addTopicToSubscribe("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeSensore); System.out.println("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeSensore);
+			publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/sensore", toAdd.toString()); // invio questo messaggio per confermare alla web app che il sensore di movimento e' stato aggiunto		
+		} catch(IOException | MqttException e) {
+			JSONObject jsError = new JSONObject();
+			jsError.put("error", e.getMessage());
+			publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/sensore", jsError.toString());
+		}
+	}
+	
+	private void handleSetSoglia(JSONObject jsSoglia) throws JSONException {
+		try {
+			Esecutore.setSoglia(jsSoglia.getInt("soglia")); 
+			JSONObject jsToSend = new JSONObject();
+			jsToSend.put("soglia", Esecutore.getSoglia());
+			publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/soglia", jsToSend.toString());
+		} catch(IOException e) {
+			JSONObject jsError = new JSONObject();
+			jsError.put("error", e.getMessage());
+			publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/soglia", jsError.toString());
+		}
+	}
+	
+	private void sendMyState(String topic) throws MqttException, NumberFormatException, JSONException {
+		JSONObject json = new JSONObject();
+		json.put("stato", automa.getStatoAutoma());
+		json.put("interruttore", nomeInterruttore);
+		json.put("sensori-movimento", Antifurto.getSensori());
+		json.put("output-suono", nomeOutputSuono);
+		json.put("output-antifurto", nomeOutputAntifurto);
+		json.put("soglia", Esecutore.getSoglia());
+		json.put("allarme", automa.getStatoSuonoTrueFalse());
+		json.put("valore-attuale", esec.getValore());
+		json.put("antifurto", automa.getStatoInterrutoreTrueFalse());
+		long allarmeTimeout = Esecutore.getAllarmeTimeout();
+		if(automa.getStatoAutoma() == 2 && allarmeTimeout > 0)
+			json.put("allarme-timeout", allarmeTimeout);
+		publisher.aggiungiComando(topic, json.toString());		
+	}
+	
+	private void sendDescription(String topic) {
+		// DA FARE: guardare quale descrizione manda netmon, archiver, meter,... e confrontare l'implementazione di questo metodo
+		String key = topic.replaceFirst("/description", "");
+		String msg = "{\""+key+"\":[\"statoAntifurto\":\"" + automa.getStatoInterruttore()+"]"+"}";
+//		
+//		//DA FARE quali IN uso, quali Out uso, statoSuono, valore, soglia, statoInterruttore
+//		[{"statoAntifurto":"on"},
+//		    {"allarme":"on"},
+//		    {"valore":5},
+//		    {"soglia":1000},
+//		    {"interruttore":"IN0"},
+//		    {"sensoreDiMovimento":"IN1"},
+//		    {"sensoreDiMovimento":"IN2"},
+//		    {"sensoreDiMovimento":"IN3"},
+//		    {"sensoreSuono":"OUT3"},]
+//		publisher.aggiungiComando(topic, msg); 
+	}
+	
+	private void sendMyStateToAll(String topic) {
+		// DA FARE
+	}
+	
+
+}
diff --git a/antifurto/src/Timer.java b/antifurto/src/code/Timer.java
similarity index 97%
rename from antifurto/src/Timer.java
rename to antifurto/src/code/Timer.java
index 808651da6e93561eaec39a01bb8839642cc1bc53..70221cec31fa596eccc74e484c57cfb74fd0cff7 100644
--- a/antifurto/src/Timer.java
+++ b/antifurto/src/code/Timer.java
@@ -1,4 +1,4 @@
-
+package code;
 public class Timer extends Thread {
 	
 	private int delay;
diff --git a/mqtt.txt b/mqtt.txt
index 40bd56ff300b6d9b62d744bc7bf4477dda2081d8..1bb049085abd8b974adce642021f2816a5e926f7 100644
--- a/mqtt.txt
+++ b/mqtt.txt
@@ -1 +1 @@
-mosquitto_sub -t '#' -h luci.local -u gruppo2 -P funziona -v
+mosquitto_sub -h luci.local -u gruppo2 -P funziona -t '#' -v
diff --git a/progetto.bash b/progetto.bash
index a520b11c7a0321a30291f4a392df37430b5235a9..fdf3e3163b340151b7fec48fae08beeb928ff981 100755
--- a/progetto.bash
+++ b/progetto.bash
@@ -8,9 +8,10 @@ osascript << EOF
 	end tell
 EOF
 
-
 #inserite al fondo della seguente riga il comando che vi serve per far partire il vostro microservizio, facendo attenzione a farlo precedere da una & per eseguire il tutto in parallelo; la doppia && serve per far eseguire le operazioni una dopo l'altra
-cd WebServer && bash server.bash & cd ScenariMicroservizio && bash scenari.bash
+#per luci: basta rimuovere il cancelletto qui sotto 
+
+cd WebServer && bash server.bash $1 & cd ScenariMicroservizio && bash scenari.bash $1 & cd antifurto && bash antifurto.bash $1 #& cd LuciMicro && bash luci.bash
 
 #chiudo tutto il resto
 #tokill=$(ps | grep 'progetto.bash' && ps | grep 'code.Server' && ps | grep 'server.bash')
@@ -21,5 +22,25 @@ do
   kill -15 $i
 done
 
+for i in ` ps -ef | grep "code.Luci" | grep -v grep | awk '{print $2}'`
+do
+  kill -15 $i
+done
+
+for i in ` ps -ef | grep "scenari.Scenari" | grep -v grep | awk '{print $2}'`
+do
+  kill -15 $i
+done
+
+for i in ` ps -ef | grep "code.Antifurto" | grep -v grep | awk '{print $2}'`
+do
+  kill -15 $i
+done
+
+for i in ` ps -ef | grep "mosquitto_sub" | grep -v grep | awk '{print $2}'`
+do
+  kill -15 $i
+done
+
 echo '
 tutto chiuso'
diff --git a/webapp/public/index.html b/webapp/public/index.html
index 1296b99f6b8511c3dd4b05e323c179e14b366f2d..37ee17f344dbf766e584a9dfd0519a46d5f18bc5 100644
--- a/webapp/public/index.html
+++ b/webapp/public/index.html
@@ -56,17 +56,6 @@
             <span>Antifurto</span>
         </button>
     </div>
-    <div id="sensoriContainer" class="container-fluid">
-        <ul class="d-flex flex-row justify-content-center more-margin-top no-padding-left">
-            <!-- <li class="d-flex flex-column">
-                <span class="d-flex justify-content-center">
-                    <img id="sensore-in1" src="res/led-red.png" alt="sensore in0" class="" height="70" width="70"
-                        data-bs-toggle="tooltip" data-bs-placement="bottom" title="I believe I could even add a very long text and still be able to make it pretty!">
-                </span>
-                <p class="d-flex justify-content-center">in1</p>
-            </li> -->
-        </ul>
-    </div>
     <!-- actual containers -->
     <div id="luciContainer" class="invisible container-fluid">
         <!-- luci -->
@@ -172,17 +161,20 @@
                 </button>
             </div>
         </div>
-        <i class="fa-solid fa-bell fa-3x" id="antifurto-bell"></i>
-        <i class="fa-brands fa-github fa-3x" id="boost-progressbar">
-            <!-- FIXME test remove this -->
-        </i>
-        <!-- <div class="switch-container no-box-sizing">
-            <div class="toggle-button no-box-sizing">
-                <div class="inner-circle no-box-sizing">
-                    antifurto
-                </div>
-            </div>
-        </div> -->
+        <i class="fa-solid fa-bell fa-3x" id="antifurto-bell" data-bs-toggle="tooltip" data-bs-placement="bottom"></i>
+        <!-- <i class="fa-brands fa-github fa-3x" id="boost-progressbar">
+        </i> -->
+        <div id="sensoriContainer" class="container-fluid">
+            <ul class="d-flex flex-row justify-content-center more-margin-top no-padding-left">
+                <!-- <li class="d-flex flex-column">
+                    <span class="d-flex justify-content-center">
+                        <img id="sensore-in1" src="res/led-red.png" alt="sensore in0" class="" height="70" width="70"
+                            data-bs-toggle="tooltip" data-bs-placement="bottom" title="I believe I could even add a very long text and still be able to make it pretty!">
+                    </span>
+                    <p class="d-flex justify-content-center">in1</p>
+                </li> -->
+            </ul>
+        </div>
     </div>
     <!-- modals for new stuff -->
     <!-- luci modal -->
@@ -262,7 +254,7 @@
                 </div>
                 <div class="modal-footer justify-content-around">
                     <button type="button" class="btn btn-danger w-25" data-bs-dismiss="modal">Annulla</button>
-                    <button type="button" class="btn btn-info w-25" data-bs-toggle="tooltip" data-bs-placement="bottom">Registra</button>
+                    <button type="button" class="btn btn-info w-25" id="scenari-modal-recordbtn" data-bs-toggle="tooltip" data-bs-placement="bottom">Registra</button>
                 </div>
             </div>
         </div>
@@ -309,7 +301,7 @@
                 </div>
                 <div class="modal-footer justify-content-around">
                     <button type="button" class="btn btn-danger w-25" data-bs-dismiss="modal">Cancella</button>
-                    <button type="button" class="btn btn-success w-25" id="attiva-scenari-btn">Attiva</button>
+                    <button type="button" class="btn btn-success w-25" id="attiva-scenari-btn" data-bs-toggle="tooltip" data-bs-placement="bottom">Attiva</button>
                 </div>
             </div>
         </div>
@@ -349,7 +341,7 @@
                 </div>
                 <div class="modal-footer justify-content-around">
                     <button type="button" class="btn btn-danger w-25" data-bs-dismiss="modal">Cancella</button>
-                    <button type="button" class="btn btn-success w-25" id="attiva-antifurto-btn">Attiva</button>
+                    <button type="button" class="btn btn-success w-25" data-bs-toggle="tooltip" data-bs-placement="bottom" id="attiva-antifurto-btn">Attiva</button>
                 </div>
             </div>
         </div>
@@ -395,7 +387,7 @@
                 </div>
                 <div class="modal-footer justify-content-around">
                     <button type="button" class="btn btn-danger w-25" data-bs-dismiss="modal">Cancella</button>
-                    <button type="button" class="btn btn-success w-25" id="toggle-antifurto-btn">Attiva</button>
+                    <button type="button" class="btn btn-success w-25" data-bs-toggle="tooltip" data-bs-placement="bottom" id="toggle-antifurto-btn">Attiva</button>
                 </div>
             </div>
         </div>
diff --git a/webapp/public/js/antifurto.js b/webapp/public/js/antifurto.js
index e5e1c104fed94c81769e497313edad0aa11df9d3..887eb8d2270c923558ae0482d23887ff2dab1cb8 100644
--- a/webapp/public/js/antifurto.js
+++ b/webapp/public/js/antifurto.js
@@ -6,7 +6,10 @@ import Api from "./mqtt/api.js";
 import Sensori from './sensori.js';
 
 class Antifurto {
-    static attivaAntifurtoINbtn = null;//FIXME is now set when filling scenari table
+    static attivaAntifurtoINbtn = null;
+    static sensoriMovimento = [];
+    static outputSuono = null;
+    static outputAntifurtoStato = null;
     /**
      * the div where everything related to the AntiFurto is stored
      */
@@ -26,7 +29,7 @@ class Antifurto {
     /**
      * contains the user's preferences regarding when to trigger the alarm
      */
-    static soglia = 50;//FIXME go back to undefined;
+    static soglia = undefined;//50;
     /**
      * shows if the alarm is on or off
      */
@@ -34,7 +37,6 @@ class Antifurto {
 
     constructor() {
         Antifurto.init();
-        Antifurto.timer();
         Antifurto.setupModalListener();
     }
 
@@ -49,10 +51,6 @@ class Antifurto {
         }, false);
 
         Antifurto.antifurtoBtnListener();
-        const bell = document.getElementById('antifurto-bell');
-        bell.addEventListener('click', () => {
-            Antifurto.activateAlarm(false, true);
-        }, false);
     }
     /**
      * listener for the form in the modal used to retrieve the soglia value from the user
@@ -86,7 +84,7 @@ class Antifurto {
      * sets up the progress bar to better accomodate the user's preferences
      * @param {number} soglia the integer value from which the alarm will be triggered
      */
-    static async setupSoglia(soglia,fromServer = false) {
+    static setupSoglia(soglia,fromServer = false) {
         //HERE server send soglia
         if(soglia == null)
             return;
@@ -110,7 +108,7 @@ class Antifurto {
     static showEditsSoglia(soglia,fromServer = false) {
         Antifurto.soglia = soglia;
         Antifurto.progressBar.setAttribute('aria-valuemax', Antifurto.maxProgressBar());//the progress bar goes a little bit more than the soglia
-        Antifurto.resetProgressBar(false,fromServer);
+        Antifurto.resetProgressBar(fromServer);
     }
     /**
      * edits and shows the modal to toggle the antitheft
@@ -153,8 +151,7 @@ class Antifurto {
             closeModal.click();
             // toggle the antitheft
             const activating = antifurtoBtn.innerText === 'OFF';
-            console.log('modal',activating)
-            Antifurto.activate(activating,undefined,undefined,true);
+            Antifurto.activate(activating);
         }, false);
     }
     /**
@@ -162,8 +159,7 @@ class Antifurto {
      * @param {Boolean} newStatus whether to activate or deactivate the antitheft
      * @param {Boolean} fromScenari usually false or undefined; true only if the function is called from the scenari
      */
-    static activate(newStatus, fromScenari = false,fromServer = false,fromBellClick = false) {
-        // console.log('activate',{newStatus, fromScenari,fromServer,fromBellClick});
+    static activate(newStatus, fromScenari = false,fromServer = false) {
         if (newStatus === Antifurto.status)
             return;
         if (newStatus && Antifurto.soglia === undefined && !fromServer) {
@@ -172,22 +168,20 @@ class Antifurto {
             Scenari.deactivateActiveScenario();
             return;
         }
-        if (fromScenari === false){
+        /*if (fromScenari === false && fromServer === true ){
             Scenari.correctlySetAntifurto(newStatus, true, fromServer);
             // return;
-        }
+        }*/
         const previousStatus = Antifurto.status;
         Antifurto.status = newStatus;
         if(fromServer){
-            Antifurto.showChangeAntifurtoStatus(previousStatus,newStatus,fromScenari,fromServer,fromBellClick);
+            Antifurto.showChangeAntifurtoStatus(previousStatus,newStatus,fromScenari,fromServer);
             return;
         }
         // HERE ok server set the status of the antitheft
         try {
-            // const resp = Api.setAntifurtoStatus({ stato: newStatus });
-            // if (await resp == null)
-            //     Antifurto.showChangeAntifurtoStatus(previousStatus, newStatus,fromScenari,fromServer,fromBellClick);
-            Api.setAntifurtoStatus(newStatus,Antifurto.attivaAntifurtoINbtn,{previousStatus,fromScenari,fromServer,fromBellClick},Antifurto.showChangeAntifurtoStatus)
+            const inBtn = Antifurto.attivaAntifurtoINbtn != null ? Antifurto.attivaAntifurtoINbtn : Scenari.antifurtoINbtn;
+            Api.setAntifurtoStatus(newStatus,inBtn.nome,{previousStatus,fromScenari,fromServer},Antifurto.showChangeAntifurtoStatus)
         } catch (error) {
             if (error.error)
                 showAlert('Errore', error.error, false);
@@ -201,7 +195,7 @@ class Antifurto {
         }
     }
 
-    static showChangeAntifurtoStatus(previousStatus, newStatus,fromScenari = false,fromServer = false,fromBellClick = false) {
+    static showChangeAntifurtoStatus(previousStatus, newStatus,fromScenari = false,fromServer = false) {
         if (fromScenari === false){
             Scenari.correctlySetAntifurto(newStatus, true, fromServer);
             // return;
@@ -227,10 +221,10 @@ class Antifurto {
             antifurtoBtn2.innerText = 'OFF';
             antifurtoBtn2.classList.remove('btn-success');
             antifurtoBtn2.classList.add('btn-danger');
-            Antifurto.activateAlarm(false,true);
+            Antifurto.activateAlarm(false);
             //this trick is needed because resetProgressBar checks whether the antitheft is on or not
             Antifurto.status = previousStatus;
-            Antifurto.resetProgressBar(false,fromBellClick,fromServer);
+            Antifurto.resetProgressBar(fromServer);
             Antifurto.status = newStatus;
         }
     }
@@ -238,22 +232,22 @@ class Antifurto {
      * toggles the bell if the alarm is on
      * @param {Boolean} activating if true, the bell will turn on
      */
-    static activateAlarm(activating, fromBellClick = false, fromServer = false) {
+    static activateAlarm(activating, fromServer = false) {
         // if the antitheft is off, the bell shouldn't turn on
         // if the alarmStatus is already set, nothing else should be done
         if (Antifurto.status === false || Antifurto.alarmStatus === activating)
             return;
         if(fromServer)
-            Antifurto.showChangeAlarmStatus(activating, fromBellClick,fromServer);
+            Antifurto.showChangeAlarmStatus(activating,fromServer);
         else
-            Antifurto.sendAlarmStatusServer(activating,fromBellClick,fromServer);
+            Antifurto.sendAlarmStatusServer(activating,fromServer);
     }
 
-    static async sendAlarmStatusServer(activating, fromBellClick = false,fromServer = false) {
+    static async sendAlarmStatusServer(activating,fromServer = false) {
         try {
             const resp = await Api.setAntifurtoAllarme({ stato: activating });
             if(await resp == null)
-                Antifurto.showChangeAlarmStatus(activating, fromBellClick,fromServer);
+                Antifurto.showChangeAlarmStatus(activating,fromServer);
         } catch (error) {
             if(error.error)
                 showAlert('Errore', error.error, false);
@@ -262,28 +256,23 @@ class Antifurto {
         }
     }
 
-    static showChangeAlarmStatus(activating, fromBellClick = false,fromServer = false) {
+    static showChangeAlarmStatus(activating,fromServer = false) {
         Antifurto.alarmStatus = activating;
         const bell = document.getElementById('antifurto-bell');
         if (activating) {
             bell.classList.add('fa-shake');
-            // auto stop of alarm after 5 minutes (only stopping the bell)
-            setTimeout(() => {
-                if (Antifurto.alarmStatus)
-                    Antifurto.activateAlarm(false);
-            }, 300000);
         } else {
             bell.classList.remove('fa-shake');
             // empty the progress bar
             if (fromBellClick){
-                Antifurto.resetProgressBar(fromBellClick,fromServer);
+                Antifurto.resetProgressBar(fromServer);
             }
         }}
     /**
      * inputs a delta and takes care of updating the progress bar and the server
      * @param {number} percentage the percentage to add to the progress bar (+/-)
      */
-    static changeProgressBar(percentage, fromBellClick = false,fromServer = false) {
+    static changeProgressBar(percentage,fromServer = false) {
         // if the antitheft is turned off, the progress bar shouldn't change
         if (!Antifurto.status && !fromServer) {
             showAlert('Antifurto', "L'antifurto è spento", false);
@@ -307,16 +296,16 @@ class Antifurto {
         }
         // HERE server send the new percentage
         if(!fromServer)
-            Antifurto.sendServerPercentage(newPercentage, fromBellClick);
-        else 
-            Antifurto.showChangeProgressBar(newPercentage, fromBellClick);
+            Antifurto.sendServerPercentage(newPercentage);
+        else
+            Antifurto.showChangeProgressBar(newPercentage);
     }
 
-    static async sendServerPercentage(percentage, fromBellClick = false) {
+    static async sendServerPercentage(percentage) {
         try {
             const resp = await Api.setAntifurtoAttenzione(percentage);
             if (await resp == null)
-                Antifurto.showChangeProgressBar(percentage, fromBellClick);
+                Antifurto.showChangeProgressBar(percentage);
         } catch (error) {
             if (error.error)
                 showAlert('Errore', error.error, false);
@@ -325,13 +314,13 @@ class Antifurto {
         }
     }
 
-    static showChangeProgressBar(newPercentage, fromBellClick = false) {
+    static showChangeProgressBar(newPercentage) {
         Antifurto.progressBar.style.width = newPercentage + '%';
         Antifurto.progressBar.setAttribute('aria-valuenow', newPercentage.toString());
         Antifurto.progressBar.innerHTML = newPercentage + '%';
         Antifurto.currentPercentage = newPercentage;
         // check if the soglia is reached
-        Antifurto.activateAlarm(newPercentage >= Antifurto.soglia, fromBellClick);
+        Antifurto.activateAlarm(newPercentage >= Antifurto.soglia);
         const quarterSoglia = Antifurto.soglia / 4;
         // change colors of the progress bar
         if (newPercentage <= quarterSoglia) {
@@ -364,28 +353,11 @@ class Antifurto {
             Antifurto.progressBar.classList.add('bg-danger');
         }
     }
-    /**
-     * every minute, the progress bar recevies a delta of -5%
-     */
-    static timer() {
-        setInterval(() => {
-            if (Antifurto.status && Antifurto.soglia != null && Antifurto.currentPercentage > 0)
-                Antifurto.changeProgressBar(-5);
-        }, 60000);
-        const github = document.getElementById('boost-progressbar');
-        github.addEventListener('click', () => {
-            if (!Antifurto.status) {
-                alert("attiva l'antifurto");
-                return;
-            }
-            Antifurto.changeProgressBar(3);
-        }, false);
-    }
     /**
      * resets the progress bar to 0
      */
-    static resetProgressBar(fromBellClick = false,fromServer = false) {
-        Antifurto.changeProgressBar(-Antifurto.currentPercentage, fromBellClick,fromServer);
+    static resetProgressBar(fromServer = false) {
+        Antifurto.changeProgressBar(-Antifurto.currentPercentage,fromServer);
     }
     /**
      * @returns the maximum value of the progress bar
@@ -399,7 +371,7 @@ class Antifurto {
     /**
      * get all user's data from the server and show them in the table
      */
-    static async fillTable() {
+    static fillTable() {
         // HERE server get all sensors for the antitheft
         // HERE server get antitheft status
         // HERE server get soglia
@@ -410,16 +382,7 @@ class Antifurto {
                 setTimeout(Antifurto.fillTable, 2500);
                 return;
             }
-            // console.log('antifurto going')
-            const resp = await Api.getAntifurto();
-            if (await resp != null) {
-                Antifurto.setupSoglia(resp.soglia != null ? resp.soglia : null,true);//imposta currentPercentage a 0
-                Antifurto.activate(resp.stato != null ? resp.stato : false,false,true);
-                Antifurto.changeProgressBar(resp.attenzione != null ? resp.attenzione : 0,false,true);//imposta currentPercentage a resp.attenzione o 0
-                Antifurto.activateAlarm(resp.allarme != null ? resp.allarme : Antifurto.currentPercentage >= Antifurto.soglia,true);
-                const sensori = resp.sensori;
-                // TODO show all sensors in the table
-            }
+            Api.getAntifurto(Antifurto.mostraAntifurtoServer);
         } catch (error) {
             if (error.error)
                 showAlert('Errore', error.error, false);
@@ -429,22 +392,76 @@ class Antifurto {
     }
 
     static mostraAntifurtoServer(datiVari){
-        /*TODO da confermare!
+       /*
         {
-        "stato":2,
-        "interruttore": "IN0",
-        "sensori-movimento": [
+        "stato": 0,
+    +    "soglia": 50,
+    +    "output-suono": "OUT0",
+    +    "interruttore": "IN0",
+    +    "output-antifurto": "OUT1",
+    +    "valore-attuale": 0,
+    +    "sensori-movimento": [
             "IN1",
             "IN2",
             "IN3"
         ],
-        "output-suono":"OUT3",
-        "soglia":35,
-        "allarme":true,
-        "valore-attuale":40,
-        "allarme-timeout":300000
+    +    "allarme": false,
+    +    "antifurto": false
+        }
+       */
+        if(Antifurto.attivaAntifurtoINbtn == null){
+            const sensoreIN = datiVari.interruttore;
+            const sin = Sensori.claimSensore(sensoreIN);
+            if(sin != null || Scenari.antifurtoINbtn.nome === sensoreIN){
+                const utilizzo = `Cambia stato dell'antifurto [${sensoreIN}]`;
+                // sin?.utilizzo = utilizzo;
+                Antifurto.attivaAntifurtoINbtn = sin;
+                document.getElementById('attiva-antifurto-btn').setAttribute('title',/*sin != null ? sin.utilizzo : */utilizzo);
+                document.getElementById('toggle-antifurto-btn').setAttribute('title',/*sin != null ? sin.utilizzo : */utilizzo);
+                if(Scenari.antifurtoINbtn !== Antifurto.attivaAntifurtoINbtn)
+                    Scenari.updateINbtn(Antifurto.attivaAntifurtoINbtn);
+            }
+        }
+
+        if(Antifurto.outputSuono == null){
+            const suonoOUT = datiVari["output-suono"];
+            const sensSuonoOUT = Sensori.claimSensore(suonoOUT);
+            if(sensSuonoOUT != null){
+                sensSuonoOUT.utilizzo = `Suono dell'antifurto [${sensSuonoOUT.nome.toUpperCase()}]`;
+                Antifurto.outputSuono = sensSuonoOUT;
+                const bell = document.getElementById('antifurto-bell');
+                bell.setAttribute('title',sensSuonoOUT.utilizzo);
+            }
+        }
+
+        if(Antifurto.outputAntifurtoStato == null){
+            const sensoreOUT = datiVari["output-antifurto"];
+            const sout = Sensori.claimSensore(sensoreOUT);
+            if(sout != null){
+                sout.utilizzo = `Stato dell'antifurto [${sout.nome.toUpperCase()}]`;
+                Antifurto.outputSuono = sout;
+                document.getElementById('scenari-stato-antifurto').setAttribute('title',sout.utilizzo);
+                document.getElementById('antifurto-stato-antifurto').setAttribute('title',sout.utilizzo);
+            }
         }
-        */
+
+
+        Antifurto.setupSoglia(datiVari.soglia != null ? datiVari.soglia : null,true);//imposta currentPercentage a 0
+        Antifurto.activate(datiVari.antifurto != null ? datiVari.antifurto : false,false,true);
+        Antifurto.changeProgressBar(datiVari["valore-attuale"] != null ? datiVari["valore-attuale"] : 0,true);//imposta currentPercentage a valore-attuale o 0
+        Antifurto.activateAlarm((datiVari.allarme != null ? datiVari.allarme : Antifurto.currentPercentage >= Antifurto.soglia),true);//HERE this true was from the bellClick
+        const sensori = datiVari["sensori-movimento"];
+        // TODO show all sensors in the table
+        for(const sens of sensori){
+            const s = Sensori.claimSensore(sens);
+            if(s != null){
+                s.utilizzo = `Sensore di movimento per l'antifurto [${s.nome.toUpperCase()}]`;
+                Antifurto.sensoriMovimento.push(s);
+                Sensori.showSensore(s);
+            }
+        }
+
+        Sensori.initializaTooltips();
     }
 
     static setTooltip(sensore){
diff --git a/webapp/public/js/mqtt/api-mqtt-in.js b/webapp/public/js/mqtt/api-mqtt-in.js
index b15ea7180de6bc7b94af0c903d2ef367d0b5028a..cb5bdd2e28f6bef31ce9215df64364ad71ea017a 100644
--- a/webapp/public/js/mqtt/api-mqtt-in.js
+++ b/webapp/public/js/mqtt/api-mqtt-in.js
@@ -1,5 +1,7 @@
 "use strict";
+import Antifurto from "../antifurto.js";
 import Luci from "../luci.js";
+import Scenari from "../scenari.js";
 import Api from "./api.js";
 
 class ApiMqttIn {
@@ -34,7 +36,7 @@ class ApiMqttIn {
 
     static outForToggleLuciStato = null;//luce con "luce-out" = out0/.../out7
     /**
-     * 
+     *
      * @param {*} outVal out0/.../out7
      * @param {*} payloadJSON {event:true/false} luce accesa o spenta
      */
@@ -53,6 +55,14 @@ class ApiMqttIn {
         Api.sendWebNewLuci(payloadJSON);
     }
 
+    static readAllRPCScenari = payloadJSON => {
+        if (payloadJSON.status != null){//escludo le luci
+            console.log('ricevuto roba inutile',payloadJSON)
+            return;
+        }
+        Api.sendScenariWeb(payloadJSON);
+    }
+
     static cambioStatoScenario = payloadJSON => {
         Api.sendWebNewScenarioStatus(payloadJSON);
     }
@@ -65,14 +75,27 @@ class ApiMqttIn {
         Api.sendWebSavedScenario(JSON.parse(payloadJSON));
     }
 
-    static readStatoAutomaAntifurto = stato => {
-        Api.sendWebAntifurtoAutoma(stato);
+    static readAllRPCAntifurto = payloadJSON => {
+        Api.sendWebGetAntifurto(payloadJSON);
     }
 
-    static readAllRPCScenari = payloadJSON => {
-        if (payloadJSON.status != null)//escludo le luci
+    static readNewStatoAntifurto = (stato,oldFrom = null) => {
+        if(oldFrom == null){
+            Api.sendWebSetAntifurtoStatus(stato);
             return;
-        Api.sendScenariWeb(payloadJSON);
+        }
+        switch(oldFrom){
+            case 'scenari':{
+                // se lo stato dell'antifurto è 0 (spento), lo stato degli scenari è 0 o 1 (antifurto spento)
+                Scenari.correctlySetAntifurto(stato !== 0,true,true)
+                break;
+            }
+            case 'antifurto':{
+                // se lo stato degli scenari è 2 (antifurto acceso), lo stato dell'antifurto è 1 o 2 (antifurto acceso)
+                Antifurto.activate(stato !== 2,true,true);
+                break;
+            }
+        }
     }
 
 }
diff --git a/webapp/public/js/mqtt/api-mqtt-out.js b/webapp/public/js/mqtt/api-mqtt-out.js
index c253e9e2182f58e9133108bf021961ec0013aa88..c9722e88d65fb60752122c5ca76ab0baf32bdcf3 100644
--- a/webapp/public/js/mqtt/api-mqtt-out.js
+++ b/webapp/public/js/mqtt/api-mqtt-out.js
@@ -35,6 +35,12 @@ class ApiMqttOut {
         sendMessage(topic, message);
     }
 
+    static setAntifurtoINbtnFromScenari = newINbtn => {
+        const topic = `to/${mqtt_tree}scenari/sensoreAntifurto`;
+        const message = `{"attiva-scenari":"${newINbtn}"}`;
+        sendMessage(topic, message);
+    }
+
     static setScenarioStatus = scenario => {
         const topic = `to/${mqtt_tree}scenari`;
         const message = `{"evento":${scenario.stato === false ? '0' : '1'},"nome":"${scenario.nome}"}`;
@@ -53,6 +59,12 @@ class ApiMqttOut {
         sendMessage(topic, message);
     }
 
+    static getAntifurto = () => {
+        const topic = `rpc/${mqtt_tree}antifurto`;
+        const message = `{"request":"description"}`;
+        sendMessage(topic, message);
+    }
+
     static setAntifurtoStatus = INBtn => {
         const topic = `from/${mqtt_tree}gpio/${INBtn.toUpperCase()}`;
         const message = `{"event":1}`;
@@ -60,7 +72,7 @@ class ApiMqttOut {
     }
 
     static setAntifurtoSoglia = soglia => {
-        const topic = `rpc/${mqtt_tree}antifurto`;
+        const topic = `to/${mqtt_tree}antifurto/soglia`;
         const message = `{"soglia":${soglia}}`;
         sendMessage(topic, message);
     }
diff --git a/webapp/public/js/mqtt/api.js b/webapp/public/js/mqtt/api.js
index cc05a3a10a42e0285df907c87669bf8581aefa98..48f88551562bbe1ba8d3fe15542e3e7c4911630c 100644
--- a/webapp/public/js/mqtt/api.js
+++ b/webapp/public/js/mqtt/api.js
@@ -20,7 +20,7 @@ class Api {
         ApiMqttOut.getStatusLuci();
     };
     static sendLuciWeb = luci => {
-        if( Api.callbackGetLuci == null)
+        if (Api.callbackGetLuci == null)
             return;
         const callback = Api.callbackGetLuci;
         Api.callbackGetLuci = null;
@@ -29,13 +29,13 @@ class Api {
 
     static callbackGetAllLuci = null;
     static getAllLuci = callback => {
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         Api.callbackGetAllLuci = callback;
         ApiMqttOut.getAllLuci();
     }
     static sendDataLuciWeb = luci => {
-        if(Api.callbackGetAllLuci == null)
+        if (Api.callbackGetAllLuci == null)
             return;
         const callback = Api.callbackGetAllLuci;
         Api.callbackGetAllLuci = null;
@@ -49,10 +49,10 @@ class Api {
      * @param {luceTemplate} luce the luce to add to the server
      * @returns {*} null if the light was added
      */
-    static makeNewLuci = (luce,callback) => {
+    static makeNewLuci = (luce, callback) => {
         if (luce == null)
             throw new Error("luce must be defined");
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         /*const url = Api.baseURL + "luci/";
         const response = await fetch(url, {
@@ -71,11 +71,11 @@ class Api {
         ApiMqttOut.makeNewLuci(luce);
     }
     static sendWebNewLuci = luce => {
-        if(Api.callbackMakeNewLuci == null)
+        if (Api.callbackMakeNewLuci == null)
             return;
         const oldLuce = Api.luceMakeNewLuci;
-        if(oldLuce !== luce) {
-            console.log('le luci non corrispondono',{oldLuce, luce});
+        if (oldLuce !== luce) {
+            console.log('le luci non corrispondono', { oldLuce, luce });
         }
         const callback = Api.callbackMakeNewLuci;
         Api.callbackMakeNewLuci = null;
@@ -90,14 +90,14 @@ class Api {
      * @param {luceTemplate} luce the luce to change the status of
      * @returns {*} null if the light's status was changed
      */
-    static setLuciStato = (luce,toggle,callback,fixedCallback) => {
-        if(Api.fixedCallbackLuciStato == null)
+    static setLuciStato = (luce, toggle, callback, fixedCallback) => {
+        if (Api.fixedCallbackLuciStato == null)
             Api.fixedCallbackLuciStato = fixedCallback;
-        if(luce == null)
+        if (luce == null)
             throw new Error("luce must be defined");
-        if(toggle == null)
+        if (toggle == null)
             throw new Error("toggle must be defined");
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
 
         Api.callbackLuciStato = callback;
@@ -105,7 +105,7 @@ class Api {
         ApiMqttOut.setLuciStato(luce);
     }
     static sendLuciStatoWeb = response => {
-        if(response == null){
+        if (response == null) {
             const callback = Api.callbackLuciStato;
             const toggle = Api.toggleForLuciStato;
             Api.callbackLuciStato = null;
@@ -122,18 +122,24 @@ class Api {
      * @returns {*} all the scenarios of the user
      */
     static getScenari = callback => {
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         Api.callbackGetScenari = callback;
         ApiMqttOut.getAllFromScenari();
     };
     static sendScenariWeb = scenari => {
-        if( Api.callbackGetScenari == null)
+        if (Api.callbackGetScenari == null)
             return;
         const callback = Api.callbackGetScenari;
         Api.callbackGetScenari = null;
         callback(scenari);
     }
+
+    static setAntifurtoINbtnFromScenari = newINbtn => {
+        if(newINbtn == null || newINbtn?.nome == null)
+            throw new Error("newINbtn must be defined");
+        ApiMqttOut.setAntifurtoINbtnFromScenari(newINbtn.nome);
+    }
     // /api/scenari/attiva/
     static callbackSetScenarioStatus = null;
     static scenarioSetScenarioStatus = null;
@@ -145,14 +151,14 @@ class Api {
      * @param {scenarioTemplate} scenario the scenario to activate or deactivate
      * @returns {*} null if the scenario was activated or deactivated
      */
-    static setScenarioStatus = (scenario,activating,isActivatingNewScenario,callback) => {
-        if(scenario == null)
+    static setScenarioStatus = (scenario, activating, isActivatingNewScenario, callback) => {
+        if (scenario == null)
             throw new Error("scenario must be defined");
-        if(activating == null)
+        if (activating == null)
             throw new Error("activating must be defined");
-        if(isActivatingNewScenario == null)
+        if (isActivatingNewScenario == null)
             throw new Error("isActivatingNewScenario must be defined");
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         Api.callbackSetScenarioStatus = callback;
         Api.scenarioSetScenarioStatus = scenario;
@@ -161,7 +167,7 @@ class Api {
         ApiMqttOut.setScenarioStatus(scenario);
     };
     static sendWebNewScenarioStatus = scenarioNome => {
-        if( Api.callbackSetScenarioStatus == null)
+        if (Api.callbackSetScenarioStatus == null)
             return;
         const callback = Api.callbackSetScenarioStatus;
         const scenario = Api.scenarioSetScenarioStatus;
@@ -172,10 +178,10 @@ class Api {
         Api.activatingSetScenarioStatus = null;
         Api.isActivatingNewScenarioSetScenarioStatus = null;
         // FIXME forse dovrei controllare scenarioNome
-        if(scenario.nome === scenarioNome) {
-            console.log('gli scenari hanno lo stesso nome',{scenario, scenarioNome});
+        if (scenario.nome === scenarioNome) {
+            console.log('gli scenari hanno lo stesso nome', { scenario, scenarioNome });
         }
-        callback(scenario,activating,isActivatingNewScenario);
+        callback(scenario, activating, isActivatingNewScenario);
     }
     // /api/scenari/registra/
     static recordingRecordScenario = null;
@@ -188,31 +194,31 @@ class Api {
      * @param {Boolean} recording true to start the recording, false to stop it
      * @returns {*} null if the recording was started or stopped
      */
-    static recordScenario = (recording,endRecordingModalLauncher,registraBtn,learnINBtn,callback) => {
-        if(recording == null)
+    static recordScenario = (recording, endRecordingModalLauncher, registraBtn, learnINBtn, callback) => {
+        if (recording == null)
             throw new Error("recording must be defined");
-        if(endRecordingModalLauncher == null)
+        if (endRecordingModalLauncher == null)
             throw new Error("endRecordingModalLauncher must be defined");
-        if(registraBtn == null)
+        if (registraBtn == null)
             throw new Error("registraBtn must be defined");
-        if(learnINBtn == null)
+        if (learnINBtn == null)
             throw new Error("learnINBtn must be defined");
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         Api.recordingRecordScenario = recording;//true se voglio registrare
         Api.endRecordingModalLauncherRecordScenario = endRecordingModalLauncher;
         Api.callbackRecordScenario = callback;
         Api.learnINBtnRecordScenario = learnINBtn;
         Api.registraBtnRecordScenario = registraBtn;
-        ApiMqttOut.recordScenario(learnINBtn);
+        ApiMqttOut.recordScenario(learnINBtn.nome);
     }
     static retriesRecordScenario = 0;
     static sendWebScenarioAutoma = stato => {
-        if( Api.callbackRecordScenario == null)
+        if (Api.callbackRecordScenario == null)
             return;
         const recording = Api.recordingRecordScenario;
         const statoAspettato = recording ? 1 : 0;
-        if(stato !== statoAspettato && Api.retriesRecordScenario < 3){
+        if (stato !== statoAspettato && Api.retriesRecordScenario < 3) {
             Api.retriesRecordScenario++;
             ApiMqttOut.recordScenario(Api.learnINBtnRecordScenario);
             return;
@@ -226,7 +232,7 @@ class Api {
         Api.learnINBtnRecordScenario = null;
         Api.registraBtnRecordScenario = null;
         Api.retriesRecordScenario = 0;
-        callback(recording,endRecordingModalLauncher,registraBtn);
+        callback(recording, endRecordingModalLauncher, registraBtn);
     }
     // /api/scenari/salva/
     static callbackSaveScenario = null;
@@ -234,37 +240,48 @@ class Api {
      * tells the server to save the currently recorded scenario
      * @returns {*} the scenario if it was saved
      */
-    static saveScenario = (nome,callback) => {
-        if(nome == null)
+    static saveScenario = (nome, callback) => {
+        if (nome == null)
             throw new Error("nome must be defined");
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         Api.callbackSaveScenario = callback;
         ApiMqttOut.saveScenario(nome);
     };
-
     static sendWebSavedScenario = scenario => {
-        if( Api.callbackSaveScenario == null)
+        if (Api.callbackSaveScenario == null)
             return;
         const callback = Api.callbackSaveScenario;
         Api.callbackSaveScenario = null;
         callback(scenario);
     }
     // /api/antifurto/
+
+    static callbackGetAntifurto = null;
     /**
      * gets everything about the antifurto (stato, allarme, attenzione (valore progress bar), soglia, sensori)
      * @returns {*} the antifurto's values
      */
-    static getAntifurto = async () => {
-        
-        // const url = Api.baseURL + "antifurto/";
-        // const response = await fetch(url);
-        // const data = await response.json();
-        // if (response.ok)
-        //     return data;
-        // else
-        //     throw data;
+    static getAntifurto = callback => {
+        if (callback == null)
+            throw new Error("callback must be defined");
+        Api.callbackGetAntifurto = callback;
+        ApiMqttOut.getAntifurto();
+        /*const url = Api.baseURL + "antifurto/";
+        const response = await fetch(url);
+        const data = await response.json();
+        if (response.ok)
+            return data;
+        else
+            throw data;*/
     };
+    static sendWebGetAntifurto = antifurto => {
+        if (Api.callbackGetAntifurto == null)
+            return;
+        const callback = Api.callbackGetAntifurto;
+        Api.callbackGetAntifurto = null;
+        callback(antifurto);
+    }
     // /api/antifurto/stato/
     /**
      * gets the status of the antifurto
@@ -288,14 +305,14 @@ class Api {
      * @param {Boolean} status the new status of the antifurto
      * @returns {*} null if the status was changed
      */
-    static setAntifurtoStatus = (newStatus,antifurtoINbtn,payload,callback) => {
-        if(newStatus == null)
+    static setAntifurtoStatus = (newStatus, antifurtoINbtn, payload, callback) => {
+        if (newStatus == null)
             throw new Error("newStatus must be defined");
-        if(antifurtoINbtn == null)
+        if (antifurtoINbtn == null)
             throw new Error("antifurtoINbtn must be defined");
-        if(payload == null)
+        if (payload == null)
             throw new Error("payload must be defined");
-        if(callback == null)
+        if (callback == null)
             throw new Error("callback must be defined");
         Api.newStatusSetAntifurtoStatus = newStatus;
         Api.antifurtoINbtnSetAntifurtoStatus = antifurtoINbtn;
@@ -304,12 +321,12 @@ class Api {
         ApiMqttOut.setAntifurtoStatus(antifurtoINbtn);
     };
     static retriesSetAntifurtoStatus = 0;
-    static sendWebAntifurtoAutoma = stato => {
-        if( Api.callbackSetAntifurtoStatus == null)
+    static sendWebSetAntifurtoStatus = stato => {
+        if (Api.callbackSetAntifurtoStatus == null)
             return;
         const newStatus = Api.newStatusSetAntifurtoStatus;
         const expectedStatus = newStatus ? 2 : 0;
-        if(stato !== expectedStatus && Api.retriesSetAntifurtoStatus < 3){
+        if (stato !== expectedStatus && Api.retriesSetAntifurtoStatus < 3) {
             Api.retriesSetAntifurtoStatus++;
             ApiMqttOut.setAntifurtoStatus(Api.antifurtoINbtnSetAntifurtoStatus);
             return;
@@ -321,7 +338,7 @@ class Api {
         Api.payloadSetAntifurtoStatus = null;
         Api.callbackSetAntifurtoStatus = null;
         Api.retriesSetAntifurtoStatus = 0;
-        callback(payload.previousStatus,newStatus,payload.fromScenari,payload.fromServer,payload.fromBellClick);
+        callback(payload.previousStatus, newStatus, payload.fromScenari, payload.fromServer);
     }
     // /api/antifurto/allarme/
     /**
@@ -362,7 +379,7 @@ class Api {
     /**
      * sets the status for the progress bar of the antifurto's alarm
      * @param {Number} attenzione the new value of the antifurto's attention
-     * @returns {*} null if the value was changed 
+     * @returns {*} null if the value was changed
      */
     static setAntifurtoAttenzione = async attenzione => {
         if (attenzione == null || isNaN(parseInt(attenzione)))
@@ -376,7 +393,7 @@ class Api {
             headers: {
                 "Content-Type": "application/json"
             },
-            body: JSON.stringify({attenzione:val})
+            body: JSON.stringify({ attenzione: val })
         });
         if (response.ok)
             return null;
@@ -392,16 +409,16 @@ class Api {
      * @param {Number} soglia the user's value of the antifurto's threshold
      * @returns {*} null if the value was changed
      */
-    static setAntifurtoSoglia = (soglia,fromServer,callback) => {
+    static setAntifurtoSoglia = (soglia, fromServer, callback) => {
         if (soglia == null || isNaN(parseInt(soglia)))
             throw new Error("soglia must be a set integer");
         const val = parseInt(soglia);
         if (val < 0 || val > 100)
             throw new Error("soglia must be between 0 and 100");
-            if(fromServer == null)
-                throw new Error("fromServer must be defined");
-            if(callback == null)
-                throw new Error("callback must be defined");
+        if (fromServer == null)
+            throw new Error("fromServer must be defined");
+        if (callback == null)
+            throw new Error("callback must be defined");
         Api.sogliaSetAntifurtoSoglia = val;
         Api.fromServerSetAntifurtoSoglia = fromServer;
         Api.callbackSetAntifurtoSoglia = callback;
@@ -420,18 +437,18 @@ class Api {
             throw await response.json();*/
     };
     static sendWebSoglia = soglia => {
-        if( Api.callbackSetAntifurtoSoglia == null)
+        if (Api.callbackSetAntifurtoSoglia == null)
             return;
         const expectedSoglia = Api.sogliaSetAntifurtoSoglia;
-        if(expectedSoglia !== soglia){
-            console.log('soglie differenti',{expectedSoglia,soglia});
+        if (expectedSoglia !== soglia) {
+            console.log('soglie differenti', { expectedSoglia, soglia });
         }
         const fromServer = Api.fromServerSetAntifurtoSoglia;
         const callback = Api.callbackSetAntifurtoSoglia;
         Api.sogliaSetAntifurtoSoglia = null;
         Api.fromServerSetAntifurtoSoglia = null;
         Api.callbackSetAntifurtoSoglia = null;
-        callback(soglia,fromServer);
+        callback(soglia, fromServer);
     }
 }
 
diff --git a/webapp/public/js/mqtt/mqtthat.js b/webapp/public/js/mqtt/mqtthat.js
index acf4b2b54994656edd6bffbe8098c7361e2452b8..d742f8df00cc8a119815c68d2c2444d04eb3d4e6 100644
--- a/webapp/public/js/mqtt/mqtthat.js
+++ b/webapp/public/js/mqtt/mqtthat.js
@@ -97,7 +97,7 @@ function onMessageArrived(message) {
     if (topic_name.length < 4) return;
     const from = topic_name.pop().toLowerCase();//get the last element
     waitedForAntifurtoMessage = waitedForAntifurtoMessage != null ? waitedForAntifurtoMessage+1 : null;
-    if(waitedForAntifurtoMessage >= 3)
+    if(waitedForAntifurtoMessage >= 6)
         dealWithAntifurtoStatus(undefined,true);
     const name_content = message.payloadString.split(":");
     const valueInt = parseInt(cleanItem(name_content[1]));
@@ -120,8 +120,8 @@ function onMessageArrived(message) {
         else if(from === 'learn')
             ApiMqttIn.readStatoAutomaScenario(valueInt);
         else if(from === 'antifurto')
-            // ApiMqttIn.readStatoAutomaAntifurto(valueInt);
-            dealWithAntifurtoStatus({from:"scenari",value:valueInt});
+            // dealWithAntifurtoStatus({from:"scenari",value:valueInt});
+            ApiMqttIn.readNewStatoAntifurto(valueInt);
         else if(from === 'salva')
             ApiMqttIn.renamedSavedScenario(message.payloadString);
         return;
@@ -136,22 +136,27 @@ function onMessageArrived(message) {
         return;
     }
     if (message.topic.startsWith(`from/${mqtt_tree}antifurto`)) {
-        if(from === 'antifurto')
-            dealWithAntifurtoStatus({from:"antifurto",value:valueInt});
+        if(from === 'antifurto' && topic_name[topic_name.length-1] === 'antifurto')
+            // qui dopo aver dato set stato (scenari -> cmd -> event -> ... -> qui)
+            // dealWithAntifurtoStatus({from:"antifurto",value:valueInt});
+            ApiMqttIn.readNewStatoAntifurto(valueInt);
+        else if(from === 'antifurto')
+            // dopo rpc per descrizione
+            ApiMqttIn.readAllRPCAntifurto(JSON.parse(message.payloadString));
         return;
     }
     console.log('impossibile',message.topic, message.payloadString);
 }
 
-function dealWithAntifurtoStatus(newJSON,launch = false){
+/*function dealWithAntifurtoStatus(newJSON,launch = false){
     if(launch){
         waitedForAntifurtoMessage = null;
         const oldJSON = antifurtoStatoValues.pop();
-        if(oldJSON.from === 'scenari'){
-            ApiMqttIn.readStatoAutomaAntifurto(oldJSON.value);
-        } else {
-            // ApiMqttIn.readStatoAntifurto(oldJSON.value);//TODO implementare
-        }
+        // if(oldJSON.from === 'scenari'){
+            ApiMqttIn.readNewStatoAntifurto(oldJSON.value);
+        // } else {
+            // ApiMqttIn.readStatoAntifurto(oldJSON.value);
+        // }
         return;
     }
     switch (antifurtoStatoValues.length) {
@@ -162,33 +167,54 @@ function dealWithAntifurtoStatus(newJSON,launch = false){
         }
         case 1: {
             const oldJSON = antifurtoStatoValues.pop();
-            if(oldJSON.from === newJSON.from){
-                const value = oldJSON.value;
-                antifurtoStatoValues.pop();
-                if(oldJSON.from === 'scenari'){
-                    ApiMqttIn.readStatoAutomaAntifurto(value);
-                } else {
-                    // ApiMqttIn.readStatoAntifurto(value);//TODO implementare
-                }
-                return;
-            }
-            // the jsons are different
-            if(oldJSON.value === newJSON.value){
-                ApiMqttIn.readStatoAutomaAntifurto(value);//TODO switch to be based from the antifurto. for now it works but it's not the best way
-                return;
-            }
-            console.log('impossible situation',{oldJSON,newJSON});
+            // if(oldJSON.from === newJSON.from){
+            //     const value = oldJSON.value;
+            //     // antifurtoStatoValues.pop();
+            //     // if(oldJSON.from === 'scenari'){
+            //         ApiMqttIn.readNewStatoAntifurto(value);
+            //     // } else {
+            //         // ApiMqttIn.readStatoAntifurto(value);
+            //     // }
+            //     return;
+            // }
+            // // the jsons are from different sources
+            // if(oldJSON.value === newJSON.value){
+            //     ApiMqttIn.readNewStatoAntifurto(value);
+            //     return;
+            // }
+            // if(oldJSON.from === newJSON.from || isTheSameStatus(oldJSON,newJSON)){
+            //     ApiMqttIn.readNewStatoAntifurto(newJSON.value);
+            //     return;
+            // }
+            // here the jsons come from both scenari and antifurto and their values differ. I have to use the newest one
+
+            // if(newJSON.from === 'scenari'){
+                // set the antifurto to the same state as the scenari
+
+                ApiMqttIn.readNewStatoAntifurto(newJSON.value,oldJSON.from);
+            // } else {
+                // set the scenari to the same state as the antifurto
+
+                // ApiMqttIn.readStatoAntifurto(newJSON.value);
+            // }
+            // console.log('impossible situation',{oldJSON,newJSON});
             break;
         }
         case 2: {//should never enter here
             antifurtoStatoValues.pop();
             antifurtoStatoValues.pop();
-            dealWithAntifurtoStatus(newJSON);
+            dealWithAntifurtoStatus(newJSON,launch);
             break;
         }
     }
 }
 
+function isTheSameStatus(oldJSON,newJSON){
+    const statoAntifurto = oldJSON.from === 'antifurto' ? oldJSON.value : newJSON.value;
+    const statoScenari = oldJSON.from === 'scenari' ? oldJSON.value : newJSON.value;
+    return (statoAntifurto === 0 && (statoScenari === 0 || statoScenari === 1)) || ((statoAntifurto === 1 || statoAntifurto === 2) && statoScenari === 2);
+}*/
+
 function cleanItem(item) {
     let citem = "";
     for (let i = 0; i < item.length; i++)
@@ -254,4 +280,3 @@ doClick = function (name) {
     }
     return;
 }*/
-
diff --git a/webapp/public/js/scenari.js b/webapp/public/js/scenari.js
index 5c200788f32be474aa8c704fb5fd85e1cd0a5020..a3ce7ba6b8913210e5654bebccdb35f50a8fe81b 100644
--- a/webapp/public/js/scenari.js
+++ b/webapp/public/js/scenari.js
@@ -4,6 +4,7 @@ import Antifurto from './antifurto.js';
 import { scenariToggleListener } from "./toggles.js";
 import { showAlert, makeElementBounce } from "./alerts.js";
 import Api from "./mqtt/api.js";
+import Sensori from './sensori.js';
 
 // JSON templeate for scenario
 const scenarioTemplate = {
@@ -15,6 +16,7 @@ const scenarioTemplate = {
 
 class Scenari {
     static learnINbtn = null;//correctly set when filling table
+    static antifurtoINbtn = null;
     /**
      * the div where everything related to the Scenari is stored
      */
@@ -76,8 +78,15 @@ class Scenari {
 
         antifurtoBtn.addEventListener('click', () => {
             if (registerBtn.innerText !== "Registra") {//sto registrando
-                showAlert("Attenzione", "Stai registrando uno scenario, termina la registrazione per attivare l'antifurto.", false);
-                makeElementBounce(registerBtn);
+                // showAlert("Attenzione", "Stai registrando uno scenario, termina la registrazione per attivare l'antifurto.", false);
+                // makeElementBounce(registerBtn);
+                // stop recording
+                const endRecordingModalLauncher = document.getElementById('termina-registrazione-launcher');
+                Scenari.recordScenario(false,endRecordingModalLauncher,registerBtn);
+                // turn on modal to change name of the recorded scenario
+                modalLauncher.click();
+                // activate antitheft
+                Scenari.correctlySetAntifurto(false);
                 return;
             }
             if (Scenari.scenariBucket.length === 0) {
@@ -138,7 +147,7 @@ class Scenari {
             const isActivatingAntitheft = antifurtoBtn.innerText === 'OFF';
             // Scenari.toggleAntifurto(isActivatingAntitheft);
             isActivatingAntitheft ? Scenari.activateRandomScenario() : Scenari.deactivateActiveScenario();//cannot use toggleScenario because I don't have the scenarioID
-            Antifurto.activate(isActivatingAntitheft);//,undefined,true)
+            Antifurto.activate(isActivatingAntitheft);
         }, false);
     }
     /**
@@ -330,7 +339,7 @@ class Scenari {
                 makeElementBounce(registerBtn);
                 return;
             }
-            // TODO server get the scenario's data 
+            // TODO server get the scenario's data
             // show the scenario in the modal (choose how to display it)
             modalBody.innerHTML = `
             <p>${scenario.nome}</p>
@@ -406,21 +415,18 @@ class Scenari {
     }
     /**
      * changes the antifurto button to the given state
-     * @param {Boolean} activating true if the antitheft is being activated, false otherwise
+     * @param {Boolean} newStatus true if the antitheft is being activated, false otherwise
      * @param {Boolean} fromAntifurto usually false or undefined; true only if the function is called from the scenari
      */
-    static correctlySetAntifurto(activating, fromAntifurto = false,fromServer = false) {
+    static correctlySetAntifurto(newStatus, fromAntifurto = false,fromServer = false) {
         if (fromAntifurto === false){
-            Antifurto.activate(activating, true,fromServer);
-            // return;
-        } else if(!fromServer){
-            //{
-                if(activating)
-                    Scenari.activateRandomScenario();
-                else
-                    Scenari.deactivateActiveScenario();
-            //}
-            
+            Antifurto.activate(newStatus, true,fromServer);
+        }
+        else {//if(!fromServer){//HERE it was else if
+            if(newStatus)
+                Scenari.activateRandomScenario();
+            else
+                Scenari.deactivateActiveScenario();
         }
     }
     /**
@@ -540,7 +546,7 @@ class Scenari {
                 showAlert("Errore", error.message,false);
         }
     }
-    
+
     static mostraScenariServer(statoScenariJSON){
         /*
         {
@@ -566,8 +572,27 @@ class Scenari {
         }
         */
         //imposta learn e antifurto correttamente
-        Scenari.learnINbtn = statoScenariJSON["learn-trigger"];
-        Antifurto.attivaAntifurtoINbtn = statoScenariJSON["attiva-scenari"];
+        const sensoreINLearn = statoScenariJSON["learn-trigger"];
+        const sinL = Sensori.claimSensore(sensoreINLearn);
+        if(sinL != null){
+            sinL.utilizzo = `Modalità di apprendimento [${sinL.nome.toUpperCase()}]`;
+            Scenari.learnINbtn = sinL;
+            document.getElementById('scenari-modal-recordbtn').setAttribute('title',sinL.utilizzo);
+        }
+
+
+        if(Antifurto.attivaAntifurtoINbtn == null){
+            const sensoreINAntifurto = statoScenariJSON["attiva-scenari"];
+            const sinA = Sensori.claimSensore(sensoreINAntifurto);
+            if(sinA != null){
+                sinA.utilizzo = `Cambia stato dell'antifurto [${sinA.nome.toUpperCase()}]`;
+                // Antifurto.attivaAntifurtoINbtn = statoScenariJSON["attiva-scenari"];
+                // document.getElementById('scenari-stato-antifurto').setAttribute('title',sinA.utilizzo);
+                // document.getElementById('antifurto-stato-antifurto').setAttribute('title',sinA.utilizzo);
+                Scenari.antifurtoINbtn = sinA;
+            }
+        } else Scenari.antifurtoINbtn = Antifurto.attivaAntifurtoINbtn;
+
         if(statoScenariJSON.learn != null){
             const registraBtn = document.getElementById('scenari-registra').innerText = statoScenariJSON.learn ? 'Termina' : 'Registra';
         }
@@ -584,6 +609,17 @@ class Scenari {
             scen.stato = Scenari.compareScenarios(scenario,scenarioAttivo);
             Scenari.mostraNuovoScenario(scen,scen.stato,true);
         }
+
+        Sensori.initializaTooltips();
+    }
+
+    static updateINbtn(newINbtn){
+        if(Scenari.learnINbtn != null){
+            Sensori.liberaSensore(Scenari.learnINbtn);
+        }
+        Scenari.antifurtoINbtn = newINbtn;
+        // HERE server send newINbtn
+        Api.setAntifurtoINbtnFromScenari(newINbtn);
     }
 
     static compareScenarios(scenario1,scenario2){
diff --git a/webapp/public/js/sensori.js b/webapp/public/js/sensori.js
index d1834828c253cf72bfc86f6e6d40eec1520fce26..04100f788a313e3b9bf14ee7e3d43604cea119d0 100644
--- a/webapp/public/js/sensori.js
+++ b/webapp/public/js/sensori.js
@@ -48,11 +48,11 @@ class Sensori {
      */
     static claimSensore(nome){
         // console.log(nome)
-        nome = nome.toLowerCase();
+        nome = nome.toUpperCase();
         if(!Sensori.checkNomeSensore(nome))
             return;
         let sensore = null;
-        if(nome.startsWith("in")){
+        if(nome.startsWith("IN")){
             const index = Sensori.sensoriDisponibiliIn.findIndex(s => s.nome === nome);
             if(index === -1){
                 // Sensori.liberaSensore(nome);
@@ -76,12 +76,12 @@ class Sensori {
 
     /**
      * rimette il sensore nella lista dei sensori disponibili
-     * @param {*} sensore il sensore che non si utilizza piu' 
+     * @param {*} sensore il sensore che non si utilizza piu'
      */
     static liberaSensore(sensore){
         // the sensor is removed from sensoriDisponibili but isn't yet in sensoriBucket
         if(Sensori.checkNomeSensore(sensore?.nome))
-            sensore.nome.startsWith("in") ? Sensori.sensoriDisponibiliIn.push(sensore) : Sensori.sensoriDisponibiliOut.push(sensore);
+            sensore.nome.startsWith("IN") ? Sensori.sensoriDisponibiliIn.push(sensore) : Sensori.sensoriDisponibiliOut.push(sensore);
     }
 
     static showSensore(sensore) {
@@ -95,7 +95,7 @@ class Sensori {
         // sensore.utilizzo = sensore.utilizzo.trim();
         // if(sensore.utilizzo == null || sensore.utilizzo.length === 0)
         //     throw new Error("Utilizzo sensore non impostato");
-        
+
         // if(!fromRemove){
             // remove the sensor with the same name from sensoriDisponibili
             // then add the new sensor to sensoriBucket
@@ -122,15 +122,15 @@ class Sensori {
     }
     /**
      * creates a new sensor and returns it. It can also be added to the bucket.
-     * @param {*} nome 
-     * @param {*} stato 
-     * @param {*} utilizzo 
-     * @param {*} createSensore 
-     * @returns 
+     * @param {*} nome
+     * @param {*} stato
+     * @param {*} utilizzo
+     * @param {*} createSensore
+     * @returns
      */
     static createSensoreDaValori(nome,stato,utilizzo,createSensore = false){
         const sensore = Object.assign({}, sensoreTemplate);
-        sensore.nome = nome;
+        sensore.nome = nome.toUpperCase().trim();
         sensore.stato = stato ? stato : false;
         sensore.utilizzo = utilizzo ? utilizzo : null;
         if(createSensore)
@@ -138,7 +138,7 @@ class Sensori {
         return sensore;
     }
     /**
-     * 
+     *
      * @param {String} nome il nome del sensore
      * @returns true se il nome e' corretto ed il sensore e' disponibile
      */
@@ -147,7 +147,7 @@ class Sensori {
             return false;
         if(nome == null || nome.length === 0)
             return false;
-        if(nome.startsWith("in")){
+        if(nome.startsWith("IN")){
             const number = nome.substring(2);
             if(number == null || isNaN(number) || isNaN(parseInt(number)) || number < 0 || number > 8)
                 return false;
@@ -155,7 +155,7 @@ class Sensori {
                 if(sensore.nome === nome)
                     return false;
             return Sensori.sensoriDisponibiliIn.length > 0;
-        } else if(nome.startsWith("out")){
+        } else if(nome.startsWith("OUT")){
             const number = nome.substring(3);
             if(number == null || isNaN(number) || isNaN(parseInt(number)) || number < 0 || number > 8)
                 return false;