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

aggiornamenti

parent ac4691c9
No related branches found
No related tags found
No related merge requests found
......@@ -101,17 +101,6 @@ 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;
// }
......@@ -170,6 +159,18 @@ public class Antifurto {
* Ho una classe che implementa l'automa a stati finiti
*
*
*
*
* DA FARE:
* All'avvio, leggo il file stato e mi imposto di conseguenza. Poi interrogo la beaglebone per sapere SOLO lo stato
* dell'antifurto (luce rossa), ovvero se l'antifurto e' on o off. Lo stato del sensore di suono, non mi interessa: poiche'
* sono solo io a impostarlo (la web app si comporta in conseguenza dei miei messaggi).
* Mi serve interrogare la beaglebone per lo stato dell'antifurto perche' puo' succedere che l'antifurto abbia avuto
* dei problemi e quindi non abbia funzionato per un po' e nel mentre l'utente ha attivato l'antifurto dagli scenari.
* Quindi proprio perche' sia il mio antifurto sia gli scenari comandano lo stesso antifurto, devo fare questa richiesta
* alla beaglebone.
* Dopo aver chiesto lo stato dell'antifurto alla beaglebone, so esattamente lo stato in cui devo essere --> mi imposto
* di conseguenza!
*/
public static void main(String args[]) throws JSONException, IOException, MqttException {
......
......@@ -21,6 +21,7 @@ public class Automa {
this.jsonObject = new JSONObject(Helper.leggiFile(FILE_AUTOMA));
setStati(false);
riempiHashTable();
}
......@@ -54,24 +55,7 @@ public class Automa {
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);
......@@ -106,7 +90,7 @@ public class Automa {
}
}
//in base allo stato attuale dell'antifurto, calcolo lo stato dell'interruttore e del suono
private synchronized void aggiornaInterruttoreESuono() throws JSONException {
public synchronized void aggiornaInterruttoreESuono() throws JSONException {
@SuppressWarnings("unchecked")
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
......@@ -155,6 +139,10 @@ public class Automa {
return statoAttuale;
}
public synchronized void setStatoAutoma(int newStato) {
statoAttuale = newStato;
}
public synchronized String getStatoInterruttore() {
return statoInterruttore;
......
......@@ -27,6 +27,7 @@ public class Esecutore extends Thread {
this.publisher = publisher;
this.outputSuono = outputSuono;
publisher.aggiungiComando("to/gruppo2/luci/gpio", "{request:status}");
JSONObject statoJson = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
this.valore = statoJson.getInt("valore");
setSoglia(statoJson.getInt("soglia"));
......@@ -46,12 +47,12 @@ public class Esecutore extends Thread {
while(automa.antifurtoAttivo()) { System.out.println("VALORE = "+ valore);
delta = codaVal.receive();
valore = valore + delta;
if(valore < 0)
if(valore < 0)
valore = 0;
if(valore > getSogliaMax())
valore = getSogliaMax();
try {
if(Math.abs(valore-valoreToSend) >= 5) {
if(Math.abs(valore-valoreToSend) >= 5 || (valore==0 && valoreToSend!=0) || valore==getSogliaMax()) {
JSONObject msgJson = new JSONObject();
msgJson.put("event", valore);
publisher.aggiungiComando("from/"+Antifurto.getMqttTree()+"/antifurto/valore", msgJson.toString());
......
package code;
import java.io.IOException;
import java.util.Date;
......@@ -9,17 +10,25 @@ import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONException;
import org.json.JSONObject;
public class SubscribeCallback implements MqttCallback{
public class SubscribeCallback implements MqttCallback {
private Antifurto client;
private Publisher publisher;
private String nomeInterruttore;
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) {
private int contatore = 0; // quando pubblico un messaggio per accendere la luce che indica che l'antifurto
// e' on, incremento questa variabile.
// Quando ricevo la conferma dal gpio, decremento il contatore. Questo contatore
// non può scendere sotto a 0.
// Ho introdotto questa variabile perche' sia il microservizio dell'antifurto
// sia il microservizio degli scenari
// inviano il comando allo stesso OUT per dire che l'antifurto e' acceso
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;
......@@ -34,29 +43,27 @@ public class SubscribeCallback implements MqttCallback{
boolean retry = true;
final Date d = new Date();
Date d2 = new Date();
long time = Math.abs(d2.getTime()-d.getTime());
while(retry & (time<600000)) {
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());
time = Math.abs(d2.getTime() - d.getTime());
}
}
if(time>=600000) {
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 {
......@@ -75,100 +82,142 @@ public class SubscribeCallback implements MqttCallback{
handleConfSensoreMovimento(msgJson);
}
else {
if(topic.equals("to/"+Antifurto.getMqttTree()+"/antifurto/soglia") && msgJson.has("soglia")) {
handleSetSoglia(msgJson);
}
if(topic.equals("to/"+Antifurto.getMqttTree()+"/antifurto/luceAntifurto") && msgJson.has("request")) {
sendOutAntifurto();
}
else {
if(topic.equals("rpc/"+Antifurto.getMqttTree()+"/antifurto") && message.toString().equals("{\"request\":\"description\"}"))
sendMyState("from/"+Antifurto.getMqttTree()+"/antifurto");
if(topic.equals("to/"+Antifurto.getMqttTree()+"/antifurto/soglia") && msgJson.has("soglia")) {
handleSetSoglia(msgJson);
}
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);
}
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/"+nomeOutputAntifurto)) {
if(msgJson.has("event"))
handleLuceAntifurto();
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 {
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]);
if(topic.equals("from/"+Antifurto.getMqttTree()+"/gpio/"+nomeOutputAntifurto)) {
if(msgJson.has("event"))
handleLuceAntifurto();
if(msgJson.has("status"))
setConsistentStatus(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
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
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
contatore++;
}
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());
contatore--;
if (contatore < 0) {
contatore = 0;
return;
}
catch(IOException e) {
try {
JSONObject js = new JSONObject();
automa.changeStatoInterruttore();
if (automa.getStatoInterruttore().equals("off")) {
publisher.aggiungiComando("to/" + Antifurto.getMqttTree() + "/gpio/" + nomeOutputSuono, "{cmd:0}");
esec.reset();
js.put("event", esec.getValore());
publisher.aggiungiComando("from/" + Antifurto.getMqttTree() + "/antifurto/valore", js.toString());
}
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/antifurto", jsError.toString());
}
}
private synchronized void handleStateMsgFromOutputSuono(int newStatus) throws JSONException, IOException {
if(newStatus!=-1) {
if (newStatus != -1) {
String statusOnOff = automa.converter(newStatus); // lo stato e' della forma "on" oppure "off"
if(! statusOnOff.equals(automa.getStatoSuono()) ) {
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());
publisher.aggiungiComando("from/" + Antifurto.getMqttTree() + "/antifurto/allarme", js.toString());
js.put("event", esec.getValore());
publisher.aggiungiComando("from/" + Antifurto.getMqttTree() + "/antifurto/valore", js.toString());
}
}
}
private void handleMovimento(String nomeSensore) {
if(automa.getStatoInterruttore().equals("on"))
private void handleMovimento(String nomeSensore) {
if (automa.getStatoInterruttore().equals("on"))
esec.aggiungiVal(automa.getDelta(nomeSensore));
}
private void handleConfSensoreMovimento(JSONObject toAdd) throws JSONException {
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));
......@@ -176,36 +225,51 @@ public class SubscribeCallback implements MqttCallback{
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) {
client.addTopicToSubscribe("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());
publisher.aggiungiComando("from/" + Antifurto.getMqttTree() + "/antifurto/sensore", jsError.toString());
}
}
private void handleSetSoglia(JSONObject jsSoglia) throws JSONException {
try {
Esecutore.setSoglia(jsSoglia.getInt("soglia"));
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) {
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());
publisher.aggiungiComando("from/" + Antifurto.getMqttTree() + "/antifurto/soglia", jsError.toString());
}
}
private void sendMyState(String topic) throws MqttException, NumberFormatException, JSONException {
private void sendMyState(String topic) throws MqttException, JSONException {
JSONObject json = new JSONObject();
json.put("stato", automa.getStatoAutoma());
json.put("interruttore", nomeInterruttore);
......@@ -217,15 +281,43 @@ public class SubscribeCallback implements MqttCallback{
json.put("valore-attuale", esec.getValore());
json.put("antifurto", automa.getStatoInterrutoreTrueFalse());
long allarmeTimeout = Esecutore.getAllarmeTimeout();
if(automa.getStatoAutoma() == 2 && allarmeTimeout > 0)
if (automa.getStatoAutoma() == 2 && allarmeTimeout > 0)
json.put("allarme-timeout", allarmeTimeout);
publisher.aggiungiComando(topic, json.toString());
publisher.aggiungiComando(topic, json.toString());
}
private void setConsistentStatus(JSONObject msgJson) throws JSONException, IOException {
int statoOutGpio = msgJson.getInt("status");
if (statoOutGpio == 0 && automa.getStatoInterruttore().equals("on")) {
// devo andare nello stato 0 dell'automa
automa.setStatoAutoma(0);
automa.aggiornaInterruttoreESuono();
esec.reset();
}
if (statoOutGpio == 1 && automa.getStatoInterruttore().equals("off")) {
// devo andare nello stato 1 dell'automa
automa.setStatoAutoma(1);
automa.aggiornaInterruttoreESuono();
}
// aggiorno il file di persistenza
JSONObject statoJson = new JSONObject(Helper.leggiFile(Automa.FILE_STATO));
statoJson.put("stato", automa.getStatoAutoma());
statoJson.put("valore", esec.getValore());
Helper.scriviFile(statoJson, Automa.FILE_STATO);
}
private void sendOutAntifurto() throws JSONException {
JSONObject js = new JSONObject();
js.put("attiva-scenari", nomeOutputAntifurto);
publisher.aggiungiComando("to/"+Antifurto.getMqttTree()+"/scenari/luceAntifurto", js.toString());
}
private void sendDescription(String topic) {
// DA FARE: guardare quale descrizione manda netmon, archiver, meter,... e confrontare l'implementazione di questo metodo
// 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()+"]"+"}";
String msg = "{\"" + key + "\":[\"statoAntifurto\":\"" + automa.getStatoInterruttore() + "]" + "}";
//
// //DA FARE quali IN uso, quali Out uso, statoSuono, valore, soglia, statoInterruttore
// [{"statoAntifurto":"on"},
......@@ -239,10 +331,9 @@ public class SubscribeCallback implements MqttCallback{
// {"sensoreSuono":"OUT3"},]
// publisher.aggiungiComando(topic, msg);
}
private void sendMyStateToAll(String topic) {
// DA FARE
}
}
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