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

aggiornamenti

parent 9649190f
No related branches found
No related tags found
No related merge requests found
......@@ -9,6 +9,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;
......@@ -24,37 +25,43 @@ public class Antifurto {
private Automa automa;
private MqttClient mqttClient;
private static String mqttDomain;
private static String mqttSubdomain;
private final String CONF_FILE = "../CONF/conf.json";
private final String CONF_ZONA = "../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(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/"+mqttDomain+"/"+mqttSubdomain+"/antifurto");
jsonObject = new JSONObject(leggiFile("./CONF/zona.json"));
jsonObject = new JSONObject(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/"+mqttDomain+"/"+mqttSubdomain+"/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");
for(int i=0; i<sensori.length(); i++) {
topicsSub.add("from/gruppo2/luci/gpio/" + sensori.get(i));
topicsSub.add("from/"+mqttDomain+"/"+mqttSubdomain+"/gpio/" + sensori.get(i));
}
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/"+mqttDomain+"/"+mqttSubdomain+"/gpio/" + interruttoreOutputSuono); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
this.mqttClient = new MqttClient(brokerUrl, clientId);
this.mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
}
......@@ -181,7 +188,10 @@ public class Antifurto {
}
public static String getMqttTree() {
return mqttDomain+"/"+mqttSubdomain;
}
}
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;
......@@ -13,20 +15,35 @@ public class Automa {
private int statoAttuale;
private String statoInterruttore;
private String statoSuono;
private static final String FILE_AUTOMA = "../automa.json";
public static final String FILE_STATO = "../stato.json";
private static final String FILE_DELTA_SENSORI = "../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));
Iterator<String> keys = jsObj.keys();
while(keys.hasNext()) {
String key = keys.next();
......@@ -35,18 +52,24 @@ public class Automa {
}
}
// 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;
}
// 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,13 +91,14 @@ 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 {
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);
setStati(true); //scrivo nel file il nuovo stato in cui mi trovo
aggiornaInterruttoreESuono();
}
}
......@@ -93,7 +117,7 @@ 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";
......@@ -105,20 +129,21 @@ public class Automa {
JSONObject riga = jsonObject.getJSONObject(key);
if(riga.getInt("stato")==statoAttuale) {
this.statoAttuale = riga.getInt(jsonKey);
setStati(true); //scrivo nel file il nuovo stato in cui mi trovo
aggiornaInterruttoreESuono();
}
}
}
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);
}
......
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Esecutore extends Thread {
......@@ -10,38 +15,52 @@ public class Esecutore extends Thread {
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
public Esecutore(Publisher publisher, MyQueue<Integer> codaVal, Automa automa, String outputSuono) {
public Esecutore(Publisher publisher, MyQueue<Integer> codaVal, Automa automa, String outputSuono) throws JSONException, IOException {
this.codaVal = codaVal;
this.valore = 0;
this.automa = automa;
this.publisher = publisher;
this.outputSuono = outputSuono;
JSONObject statoJson = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
this.valore = statoJson.getInt("valore");
if(statoJson.getInt("stato")==2)
this.tempoAllarme = LocalDateTime.parse(statoJson.getString("tempoAllarme"));
}
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
try {
Helper.modificaFileStato(codaVal, false, delta, valore, Automa.FILE_STATO);
if(valore >= SOGLIA && (!automa.allarme()) ) {
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);
}
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
}
}
}
}
catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!automa.antifurtoAttivo()) {
......@@ -52,6 +71,7 @@ public class Esecutore extends Thread {
public void aggiungiVal(int n) {
Helper.modificaFileStato(true, n, Automa.FILE_STATO);
codaVal.send(n);
}
......@@ -60,4 +80,6 @@ public class Esecutore extends Thread {
codaVal.removeAll();
}
}
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 {
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));
}
}
}
}
import org.json.JSONException;
import org.json.JSONObject;
public class Pair {
......@@ -17,4 +19,12 @@ public class Pair {
public String getMsg() {
return msg;
}
public JSONObject toJsonObject() throws JSONException {
return new JSONObject(toString());
}
public String toString() {
return "{\"topic\":\""+topic+"\",\"msg\":"+msg+"}";
}
}
import org.eclipse.paho.client.mqttv3.MqttException;
public class Publisher extends Thread {
private MyQueue<Pair> coda;
......@@ -11,13 +12,16 @@ public class Publisher extends Thread {
}
public void aggiungiComando(String topic, String msg) {
coda.send(new Pair(topic, msg));
Pair p = new Pair(topic, msg);
Helper.modificaFileStato(true, p, Automa.FILE_STATO);
coda.send(p);
}
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) {
......
import java.io.IOException;
import java.util.Date;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
......@@ -56,18 +57,22 @@ public class SubscribeCallback implements MqttCallback{
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
if(topic.equals("to/all"))
sendDescription("from/gruppo2/luci/antifurto/description");
System.out.println("nuovo: "+topic+" ; "+message.toString());
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");
}
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
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
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)) {
if(topic.equals("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputSuono)) {
int newStatus = -1;
if(msgJson.has("status"))
newStatus = msgJson.getInt("status");
......@@ -79,9 +84,9 @@ public class SubscribeCallback implements MqttCallback{
}
else {
int event = msgJson.getInt("event");
if(event==0) {
if(event==1) {
// e' stato premuto l'interruttore / il sensore di movimento ha rilevato qualcuno
if(topic.equals("from/gruppo2/luci/gpio/"+nomeInterruttore))
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
......@@ -97,20 +102,22 @@ public class SubscribeCallback implements MqttCallback{
private synchronized void handleStateMsgFromInterruttore() throws JSONException {
private synchronized void handleStateMsgFromInterruttore() throws JSONException, IOException {
automa.changeStatoInterruttore();
if(automa.getStatoInterruttore().equals("off")) {
publisher.aggiungiComando("to/gruppo2/luci/gpio/"+nomeOutputSuono, "{cmd:0}");
publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputSuono, "{cmd:0}");
esec.reset();
}
publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto", "{\"event\": {\"antifurto\":\""+automa.getStatoInterruttore()+"\",\"allarme\":\""+automa.getStatoSuono()+"\"}}");
}
private synchronized void handleStateMsgFromOutputSuono(int newStatus) throws JSONException {
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);
publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto", "{\"event\": {\"antifurto\":\""+automa.getStatoInterruttore()+"\",\"allarme\":\""+automa.getStatoSuono()+"\"}}");
}
}
}
......@@ -124,12 +131,24 @@ public class SubscribeCallback implements MqttCallback{
}
private void sendMyState(String topic) throws MqttException {
publisher.aggiungiComando(topic, "{\"status\":"+automa.getStatoAutoma()+"}");
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 =
// 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);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment