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..8ceee73a134bc01304f619ec008df9f73513046f
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..e7c5c2575f330bc66376541054a0212bd2ae441d
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..e5c632a21e44d6bef8a89c8062d1b7beae587149
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..cbfca13d4240a1884a93c6cbb7ccbb591b612e09
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..50ac71d1e9f4ea9afa31bd320196bcda41a7245b
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..2470277b8b66da852c3f09e4877b4624b7c51b5b
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..4d607d806d239c2b6883e4b242d430e7d963e18a
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..23929201c5cbee84789f64070e14972ad29b922f
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..453e7f52694373063e3dfdbee7b4c29d1ec4ba84
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/res/CONF/deltaSensoriMovimento.json b/antifurto/res/CONF/deltaSensoriMovimento.json
index 798edf6d07714548dd4a4b86ea61df3ce2d5c5e1..cfa0e95aa9e9ab6f6f34b4d0551f0d768eb874b0 100644
--- a/antifurto/res/CONF/deltaSensoriMovimento.json
+++ b/antifurto/res/CONF/deltaSensoriMovimento.json
@@ -1,5 +1 @@
-{
-    "IN1":33,
-    "IN2":4,
-    "IN3":8
-}
+{"IN6":33,"IN5":5,"IN2":4,"IN1":33,"IN3":8}
\ No newline at end of file
diff --git a/antifurto/res/CONF/zona.json b/antifurto/res/CONF/zona.json
index c58acf8f7abc378512543ca70f6ac2562589fae3..c2f6770ef6fe0867b1f4cfecf8c86bfff55a5e90 100644
--- a/antifurto/res/CONF/zona.json
+++ b/antifurto/res/CONF/zona.json
@@ -1,9 +1 @@
-{
-    "interruttore": "IN0",
-    "sensoriMovimento": [
-      "IN1",
-      "IN2",
-      "IN3"
-    ],
-    "outputSuono":"OUT0"
-}
+{"interruttore":"IN0","sensoriMovimento":["IN1","IN2","IN3","IN5","IN6"],"outputSuono":"OUT0", "nomeOutputAntifurto":"OUT1"}
diff --git a/antifurto/res/stato.json b/antifurto/res/stato.json
index 13ac491d75e12144235198680dabc84f5349c0e5..a8a62240c0c5c66b219eac259de23554f493136d 100644
--- a/antifurto/res/stato.json
+++ b/antifurto/res/stato.json
@@ -1 +1 @@
-{"stato":0,"valore":0,"codaVal":[],"codaMsg":[{"msg":{"status":{"stato":0,"interruttore":"off","allarme":"off"}},"topic":"from/gruppo2/luci/antifurto"},{"msg":{"status":{"stato":0,"interruttore":"off","allarme":"off"}},"topic":"from/gruppo2/luci/antifurto"},{"msg":{"status":{"stato":0,"interruttore":"off","allarme":"off"}},"topic":"from/gruppo2/luci/antifurto"}]}
\ No newline at end of file
+{"soglia":30,"stato":0,"valore":0,"tempoAllarme":"2022-07-24T19:48:50.175953"}
\ No newline at end of file
diff --git a/antifurto/src/code/Antifurto.java b/antifurto/src/code/Antifurto.java
index a0c44f85347d2cea0b03fb8bb8a4c57c770f5ff7..9c13607e7689fa300d19c0228e469e7ebd72c955 100644
--- a/antifurto/src/code/Antifurto.java
+++ b/antifurto/src/code/Antifurto.java
@@ -20,6 +20,8 @@ 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
@@ -30,11 +32,12 @@ public class Antifurto {
 	private static String mqttSubdomain;
 	
 	private final String CONF_FILE = "../res/CONF/conf.json";
-	private final String CONF_ZONA = "../res/CONF/zona.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_FILE));
+		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");
@@ -45,22 +48,32 @@ public class Antifurto {
 		topicsSub.add("to/all"); 
 		
 		// Su questo topic ricevero' le richieste di inviare il mio stato attuale
-		topicsSub.add("rpc/"+mqttDomain+"/"+mqttSubdomain+"/antifurto");
+		topicsSub.add("rpc/"+getMqttTree()+"/antifurto");
 		
 		
-		jsonObject = new JSONObject(leggiFile(CONF_ZONA));
+		jsonObject = new JSONObject(Helper.leggiFile(CONF_ZONA));
 		interruttore = jsonObject.getString("interruttore"); 
-		topicsSub.add("from/"+mqttDomain+"/"+mqttSubdomain+"/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/"+mqttDomain+"/"+mqttSubdomain+"/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/"+mqttDomain+"/"+mqttSubdomain+"/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
+		
+		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());
 		
@@ -69,13 +82,18 @@ public class Antifurto {
 	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 {
@@ -83,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;
+//	}
 	
 	
 	
@@ -180,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();
@@ -188,11 +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/code/Automa.java b/antifurto/src/code/Automa.java
index 8e5baa630113db6e43be27513fe28b6a685aa942..9b0a8e8ac2945b9abddd0857ef2b9013550a1f52 100644
--- a/antifurto/src/code/Automa.java
+++ b/antifurto/src/code/Automa.java
@@ -1,8 +1,4 @@
 package code;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.FileReader;
-import java.io.FileWriter;
 import java.io.IOException;
 import java.util.Hashtable;
 import java.util.Iterator;
@@ -18,7 +14,7 @@ public class Automa {
 	private String statoSuono;
 	private static final String FILE_AUTOMA = "../res/automa.json";
 	public static final String FILE_STATO = "../res/stato.json";
-	private static final String FILE_DELTA_SENSORI = "../res/CONF/deltaSensoriMovimento.json";
+	public static final String FILE_DELTA_SENSORI = "../res/CONF/deltaSensoriMovimento.json";
 	
 	
 	public Automa() throws JSONException, IOException {
@@ -29,7 +25,7 @@ public class Automa {
 	
 	
 	private synchronized void setStati(boolean write) throws JSONException, IOException {
-		JSONObject statoJson = new JSONObject(Helper.leggiFile(FILE_STATO));
+		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);
@@ -37,14 +33,15 @@ public class Automa {
 		else {
 			// devo capire in quale stato mi trovo e impostare di conseguenza lo statoInterruttore e lo statoSuono
 			this.statoAttuale = statoJson.getInt("stato");
-			aggiornaInterruttoreESuono();	
 		}
+		aggiornaInterruttoreESuono();
 	}
 	
 	
 	private void riempiHashTable() throws JSONException, IOException {
 		this.deltaSensori = new Hashtable<String, Integer>();
 		JSONObject jsObj = new JSONObject(Helper.leggiFile(FILE_DELTA_SENSORI));
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsObj.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
@@ -53,6 +50,10 @@ public class Automa {
 		}
 	}
 	
+	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());
@@ -93,6 +94,7 @@ 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, IOException {
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsonObject.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
@@ -100,12 +102,12 @@ public class Automa {
 			if(riga.getInt("stato")==statoAttuale) {
 				this.statoAttuale = riga.getInt("cmd"+newStatoInterruttore);
 				setStati(true); //scrivo nel file il nuovo stato in cui mi trovo
-				aggiornaInterruttoreESuono();
 			}
 		}
 	}
 	//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();
@@ -124,6 +126,7 @@ public class Automa {
 			jsonKey = "eventValMaggioreSoglia";
 		else
 			jsonKey = "eventValMinoreSoglia";
+		@SuppressWarnings("unchecked")
 		Iterator<String> keys = jsonObject.keys();
 		while(keys.hasNext()) {
 			String key = keys.next();
@@ -131,7 +134,6 @@ public class Automa {
 			if(riga.getInt("stato")==statoAttuale) {
 				this.statoAttuale = riga.getInt(jsonKey);
 				setStati(true); //scrivo nel file il nuovo stato in cui mi trovo
-				aggiornaInterruttoreESuono();
 			}
 		}
 	}
@@ -149,8 +151,8 @@ public class Automa {
 	}
 	
 	
-	public synchronized String getStatoAutoma() {
-		return "{\"stato\":"+statoAttuale+",\"interruttore\":\""+statoInterruttore+"\",\"allarme\":\""+statoSuono+"\"}";
+	public synchronized int getStatoAutoma() {
+		return statoAttuale;
 	}
 	
 	
@@ -163,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
index ff582c0a851519bbf6a7035db2e5acb82d66dceb..77614b9705cbaa8c6f555584114901922ba0fcd3 100644
--- a/antifurto/src/code/Esecutore.java
+++ b/antifurto/src/code/Esecutore.java
@@ -2,8 +2,10 @@ 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.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 
@@ -12,11 +14,12 @@ 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 = 100;
+	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;
@@ -26,26 +29,41 @@ public class Esecutore extends Thread {
 		
 		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 = 5; // l'allarme dura 5 minuti e poi smette di suonare
+		final long DURATA_SUONO = 5; // l'allarme dura 5 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 {
-					Helper.modificaFileStato(codaVal, false, delta, valore, Automa.FILE_STATO);
-					if(valore >= soglia && (!automa.allarme()) ) {	
+					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();
-						JSONObject statoJson = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
-						Helper.scriviFile(statoJson.put("tempoAllarme",tempoAllarme.toString()), Automa.FILE_STATO);
+						statoJson.put("tempoAllarme",tempoAllarme.toString());
 					}
 					else {
 						if(automa.allarme()) {
@@ -56,6 +74,8 @@ public class Esecutore extends Thread {
 							}
 						}
 					}
+					statoJson.put("soglia", soglia);
+					Helper.scriviFile(statoJson, Automa.FILE_STATO); 
 				}
 				catch (JSONException e) {
 					e.printStackTrace();
@@ -72,7 +92,6 @@ public class Esecutore extends Thread {
 
 	
 	public void aggiungiVal(int n) {
-		Helper.modificaFileStato(true, n, Automa.FILE_STATO);
 		codaVal.send(n);
 	}
 	
@@ -81,6 +100,23 @@ public class Esecutore extends Thread {
 		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
index b765038f4594d3d2f2bac7843d37fd300640d850..7732e4c5afee2dbd7374c78d6744a8d2cb78ddc1 100644
--- a/antifurto/src/code/Helper.java
+++ b/antifurto/src/code/Helper.java
@@ -31,93 +31,93 @@ public class Helper {
 	
 	// 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(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 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 {
-			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);
-		} 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));
-			}
-		}
-			
-	}
+//	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/code/Pair.java b/antifurto/src/code/Pair.java
index 87880af5b8b0b625dd3f283c375b4c324dacb7c3..977d71ede54c2b42befad81c7b1901f9bf2c6751 100644
--- a/antifurto/src/code/Pair.java
+++ b/antifurto/src/code/Pair.java
@@ -22,10 +22,18 @@ public class Pair {
 	}
 	
 	public JSONObject toJsonObject() throws JSONException {
-		return new JSONObject(toString());
+		JSONObject js = new JSONObject();
+		js.put("topic", topic);
+		js.put("msg", msg); System.out.println(msg);
+		return js;
 	}
 	
 	public String toString() {
-		return "{\"topic\":\""+topic+"\",\"msg\":"+msg+"}";
+		try {
+			return toJsonObject().toString();
+		} catch (JSONException e) {
+			e.printStackTrace();
+		}
+		return null;
 	}
 }
diff --git a/antifurto/src/code/Publisher.java b/antifurto/src/code/Publisher.java
index 5326a209db53a68eb334b3012fb2d20310be4587..becc9b0005f6271a50d80e6505fe38776c6ca54f 100644
--- a/antifurto/src/code/Publisher.java
+++ b/antifurto/src/code/Publisher.java
@@ -13,8 +13,7 @@ public class Publisher extends Thread {
 	}
 	
 	public void aggiungiComando(String topic, String msg) {
-		Pair p = new Pair(topic, msg); 
-		Helper.modificaFileStato(true, p, Automa.FILE_STATO);
+		Pair p = new Pair(topic, msg);  
 		coda.send(p);
 	}
 	
@@ -22,7 +21,6 @@ public class Publisher extends Thread {
 	public void run() {
 		while(true) {
 			Pair p = coda.receive();
-			Helper.modificaFileStato(false, p, Automa.FILE_STATO);
 			try {
 				client.publishMethod(p.getTopic(), p.getMsg());
 			} catch (MqttException e) {
diff --git a/antifurto/src/code/SubscribeCallback.java b/antifurto/src/code/SubscribeCallback.java
index a28648bcb8143324e1c9c89ad7f4a23d73b7322d..77e98d5f8e498a40a368c2ded67c2499c39fe902 100644
--- a/antifurto/src/code/SubscribeCallback.java
+++ b/antifurto/src/code/SubscribeCallback.java
@@ -15,14 +15,16 @@ public class SubscribeCallback implements MqttCallback{
 	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) {
+	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;
 	}
@@ -57,45 +59,62 @@ public class SubscribeCallback implements MqttCallback{
 	
 
 	@Override
-	public void messageArrived(String topic, MqttMessage message) throws Exception {
-		System.out.println("nuovo: "+topic+" ; "+message.toString());
+	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}"))
-				sendMyState("from/"+Antifurto.getMqttTree()+"/antifurto");
+				sendMyStateToAll("from/"+Antifurto.getMqttTree()+"/antifurto");  // DA FARE: vedi cosa pubblicano gli altri microservizi e implementa di conseguenza questa funzione
 		}
 		else {
-			if(topic.equals("rpc/"+Antifurto.getMqttTree()+"/antifurto")) // DA FARE: capire quale messaggio voglio ricevere per poi pubblicare il mio stato
-				// DA FARE: vedi foto foglio Alfredo
-				sendMyState("from/"+Antifurto.getMqttTree()+"/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
+			JSONObject msgJson = new JSONObject(message.toString());
+			if(topic.equals("conf/"+Antifurto.getMqttTree()+"/antifurto/sensore")) {
+				if(msgJson.has("in") && msgJson.has("delta")) 
+					handleConfSensoreMovimento(msgJson);
+			}
 			else {
-				JSONObject msgJson = new JSONObject(message.toString());
-				
-				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);
+				if(topic.equals("to/"+Antifurto.getMqttTree()+"/antifurto/soglia") && msgJson.has("soglia")) {
+					handleSetSoglia(msgJson);
 				}
 				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
-							String[] t = topic.split("/");
-							handleMovimento(t[4]);
+					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]);
+									}
+								}
+							}
+						}				
+					}					
+				}
+				
 			}
 		}	
 		
@@ -104,12 +123,28 @@ public class SubscribeCallback implements MqttCallback{
 
 	
 	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());
 		}
-		publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto", "{\"event\": {\"antifurto\":\""+automa.getStatoInterruttore()+"\",\"allarme\":\""+automa.getStatoSuono()+"\"}}");
 	}
 	
 	
@@ -118,7 +153,9 @@ public class SubscribeCallback implements MqttCallback{
 			String statusOnOff = automa.converter(newStatus); // lo stato e' della forma "on" oppure "off"
 			if(! statusOnOff.equals(automa.getStatoSuono()) ) {
 				automa.aggiornaStatoSuono(statusOnOff);
-				publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto", "{\"event\": {\"antifurto\":\""+automa.getStatoInterruttore()+"\",\"allarme\":\""+automa.getStatoSuono()+"\"}}");
+				JSONObject js = new JSONObject();
+				js.put("event", automa.getStatoSuonoTrueFalse());
+				publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/allarme", js.toString());
 			}
 		}
 	}
@@ -126,13 +163,62 @@ public class SubscribeCallback implements MqttCallback{
 
 	
 	
-	private void handleMovimento(String nomeSensore) {
+	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 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("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) {
@@ -153,5 +239,9 @@ public class SubscribeCallback implements MqttCallback{
 //		publisher.aggiungiComando(topic, msg); 
 	}
 	
+	private void sendMyStateToAll(String topic) {
+		// DA FARE
+	}
+	
 
 }