Skip to content
Snippets Groups Projects
Commit 85f0e9d6 authored by A C's avatar A C
Browse files

LuciMicro da testare

parent 3cb44b5a
No related branches found
No related tags found
No related merge requests found
{"sensM":"IN5",
"lamp3":{"output":"OUT3",
"stato":false,
"input":"IN4",
"nome":"Garage"},
"lamp2":{"output":"OUT1",
"stato":false,
"input":"IN3",
"nome":"Ingresso"},
"lamp1":{"output":"OUT2",
"stato":false,
"input":"IN1",
......
......@@ -15,99 +15,79 @@ import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONException;
import org.json.JSONObject;
public class Esecutore extends Thread {
public class Esecutore /* extends Thread */ {
private final Luci luci;
static private Timer timer;
private boolean firstrun;
//private int durata;
public Esecutore(Luci luci) throws IOException, JSONException {
static Timer timer;
public Boolean running;
private static Esecutore istanza = null;//
static ArrayList<Luce> j = new ArrayList<Luce>();
// arraylist mi serve per sapere se una luce era accesa manualmente. Se la era
// non la spengo quando scade il timer
private Esecutore(Luci luci) throws IOException, JSONException {
this.luci = luci;
}
public static Esecutore istanziatore(Luci l) throws IOException, JSONException {
if (istanza == null) {
istanza = new Esecutore(l);
}
return istanza;
}
class AccendiTutto extends TimerTask {
int durata=5;
ArrayList<Luce> j=new ArrayList<Luce>();
//arraylist mi serve per sapere se una luce era accesa manualmente. Se la era non la spengo quando scade il timer
// boolean running=false;
int durata = 5;
ArrayList<Luce> j;
public AccendiTutto(ArrayList j) {
this.j = j;
}
public void run() {
//int durata=12;
if (durata > 0) {
String req="{cmd:1}";
//System.out.println("Restano " + durata + " secondi");
for(Luce k:luci.luciList) {
if(firstrun && k.getStato()) j.add(k);
k.setStato(true);
try {
luci.sendMqttMessage(luci.getMqttTree("to", "gpio/" +k.getOUT()), req);
System.out.println("-----" + durata);
if (durata > 0) {
String req = "{cmd:1}";
for (Luce k : Luci.luciList) {
try {
luci.sendMqttMessage(Luci.getMqttTree("to", "gpio/" + k.getOUT()), req);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
durata--;
}else{
//System.out.println("FINE!");
String req="{cmd:0}";
for(Luce k:luci.luciList) {
if(!j.contains(k)) {
k.setStato(false);
try {
luci.sendMqttMessage(luci.getMqttTree("to", "gpio/" +k.getOUT()), req);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//System.exit(0);
timer.cancel();
}
firstrun=false;
}
public void resetDurata() {
this.durata=5;
}
durata--;
} else {
System.out.println("FINE!" + running);
String req = "{cmd:0}";
for (Luce k : Luci.luciList) {
if (!j.contains(k)) {
k.setStato(false);
try {
luci.sendMqttMessage(Luci.getMqttTree("to", "gpio/" + k.getOUT()), req);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
j.clear();
timer.cancel();
timer.purge();
Subscriber.runningEsec = false;
}
}
}
public void run() {
// qui ci va la business logic
if(timer != null)
timer.cancel();
public void run(Boolean running) {
timer = new Timer();
AccendiTutto a=new AccendiTutto();
a.resetDurata();
firstrun=true;
//try {
timer.schedule(a, 0, 1000);
// }catch(IllegalStateException e) {
// Helper.print("Errore illegal state");
// //run();
// }
//
//
AccendiTutto a = new AccendiTutto(j);
this.running = running;
timer.schedule(a, 0, 1000);
}
}
\ No newline at end of file
package code;
import java.util.Date;
import java.util.Iterator;
//import java.util.Iterator;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
......@@ -9,133 +9,113 @@ 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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
//import java.util.Collections;
public class Luci {
public static ArrayList<Luce> luciList;//per ogni luce ho uno stato
public static ArrayList<Luce> luciList;
private static String brokerUrl;
private JSONObject jsonObject;
private final static String DATABASE_PATH = "./Luci.json";
//private JSONObject jsonObject;
//private final static String DATABASE_PATH = "./Luci.json";
private static ArrayList<String> topicsSub;
private String clientId = Long.toString(new Date().getTime()) + "-luci"; // unique client id
private String mqttDomain;
private String mqttSubdomain;
private static String mqttTree;
//public static final String RES_FOLDER = "../res/";
public static final String CONF_FOLDER = "../CONF/";
private final static String FILE_CONF = CONF_FOLDER+"conf.json";//"./CONF/conf.json";
//private final static String FILE_ZONA = CONF_FOLDER+"zona.json";//"./CONF/zona.json"
final static String FILE_ZONA = "../CONF/zona.json";//"./CONF/zona.json"
private final static String FILE_CONF = CONF_FOLDER + "conf.json";// "./CONF/conf.json";
// private final static String FILE_ZONA =
// CONF_FOLDER+"zona.json";//"./CONF/zona.json"
final static String FILE_ZONA = "../CONF/zona.json";// "./CONF/zona.json"
public MqttClient mqttClient;
public Luci() throws JSONException, IOException, MqttException {
JSONObject config = new JSONObject(Helper.leggiFile(FILE_CONF));//dove mi salvo le strutture dal file? cioè leggo e poi?
JSONObject config = new JSONObject(Helper.leggiFile(FILE_CONF));// dove mi salvo le strutture dal file? cioè
// leggo e poi?
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/","luci")); //mandare lo stato attuale
topicsSub.add("to/all"); // mandare la mia descrizione json
topicsSub.add(getMqttTree("rpc/", "luci")); // 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");
// topicsSub.add("from/"+Scenari.getMqttTree()+"gpio/" + learnTrigger); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
//attivaScenari = config.getString("attiva-scenari");
// topicsSub.add("from/"+Scenari.getMqttTree()+"gpio/"+attivaScenari);
// interruttoreOutputSuono = config.getString("outputSuono");
// topicsSub.add("from/"+Scenari.getMqttTree()+"gpio/" + interruttoreOutputSuono); // Sottoscrivo i messaggi che notificano il cambiamento di stato dell'interruttore
// topicsSub.add("to/"+Scenari.getMqttTree()+"scenari/learn");
topicsSub.add(getMqttTree("from/","gpio/#"));
topicsSub.add(getMqttTree("to/","luci/#"));//{"evento":0,"nome":nome_scenario} per attivare/disattivare uno scenario; risposta su from/tree/scenari/attiva con {"nome":nome_scenario}
//topicsSub.add(getMqttTree("to/","luci/salva"));//per rinominare lo scenario piu recente
topicsSub.add(getMqttTree("from/", "gpio/#"));
topicsSub.add(getMqttTree("to/", "luci/#"));// {"evento":0,"nome":nome_scenario} per attivare/disattivare uno
topicsSub.add(getMqttTree("from/", "arduino/AN0")); // scenario; risposta su from/tree/scenari/attiva con
// {"nome":nome_scenario}
// topicsSub.add(getMqttTree("to/","luci/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
}
private void makeMqttTree() {
if(mqttTree != null)
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 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 {
System.out.println("started");
luciList= new ArrayList<Luce>();
startSystemo();
luciList = new ArrayList<Luce>();
startSystemo();
}
private static void startSystemo() throws JSONException, IOException, MqttException {
System.out.println(Helper.leggiFile(FILE_ZONA));
JSONObject config = new JSONObject(Helper.leggiFile(FILE_ZONA));
System.out.println(config);
String sensM=config.getString("sensM");
int index=0;
while (config.has("lamp"+index)) { //(keys.hasNext()) {
System.out.println(index+"\n");
//String key = keys.next();
//if (config.get(key) instanceof String) {
JSONObject k= config.getJSONObject("lamp"+index);
System.out.println(k);
String a=k.getString("output");
String b=k.getString("input");
boolean c = k.getBoolean("stato");
String d = k.getString("nome");
Luce luce=new Luce(a,b,c,d);
luciList.add(luce);
System.out.println(config.get("lamp"+index));
index++;
String sensM = config.getString("sensM");
int index = 0;
while (config.has("lamp" + index)) {
System.out.println(index + "\n");
JSONObject k = config.getJSONObject("lamp" + index);
System.out.println(k);
String a = k.getString("output");
String b = k.getString("input");
boolean c = k.getBoolean("stato");
String d = k.getString("nome");
Luce luce = new Luce(a, b, c, d);
luciList.add(luce);
System.out.println(config.get("lamp" + index));
index++;
}
Luci luci = new Luci();
Esecutore esec = new Esecutore(luci);
luci.startClient(esec, sensM/*esec,,publisher*/);//, publisher);
//esec.start();
Luci luci = new Luci();
Esecutore esec = Esecutore.istanziatore(luci);
luci.startClient(esec, sensM);
}
public void sendMqttMessage(String topic, String msg) throws MqttException {
final MqttTopic msgTopic = mqttClient.getTopic(topic);
msgTopic.publish(new MqttMessage(msg.getBytes()));
}
public void startClient(Esecutore esec, String sensM) throws MqttException {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("gruppo2");
......@@ -145,12 +125,8 @@ public class Luci {
mqttClient.connect(options);
for(String t: topicsSub)
for (String t : topicsSub)
mqttClient.subscribe(t);
// query the antifurto microservice to set the SAME luceAntifurto
}
}
package code;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
......@@ -18,26 +19,29 @@ import org.json.JSONObject;
//import scenari.Automa;
//import scenari.Scenari;
public class Subscriber implements MqttCallback{
public class Subscriber implements MqttCallback {
private Luci luci;
private Esecutore esec;
static Boolean runningEsec;
public String sensM;
Boolean giorno=false;
public Subscriber(Luci luci, Esecutore esec, String sensm) {
this.luci=luci;
this.luci = luci;
this.esec = esec;
this.sensM = sensm;
Subscriber.runningEsec = false;
}
@Override
public void connectionLost(Throwable arg0) {
Helper.print("connessione persa\t"+arg0);
Helper.print("connessione persa\t" + arg0);
final Date d = new Date();
Date d2 = new Date();
long time = Math.abs(d2.getTime()-d.getTime());
long time = Math.abs(d2.getTime() - d.getTime());
while (time<600000) {
while (time < 600000) {
try {
Helper.print("retrying...");
......@@ -46,17 +50,16 @@ public class Subscriber implements MqttCallback{
} catch (MqttException | JSONException | IOException e) {
Helper.print("non sono riusciuto");
d2 = new Date();
time = Math.abs(d2.getTime()-d.getTime());
time = Math.abs(d2.getTime() - d.getTime());
}
}
Helper.print("fuori dal while");
if(time>=600000) {
if (time >= 600000) {
Helper.print("Tentativo di riconnessione fallito");
System.exit(1);
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
Helper.print("inviato");
......@@ -64,179 +67,163 @@ public class Subscriber implements MqttCallback{
@Override
public void messageArrived(String topic, MqttMessage message) throws MqttException, JSONException, IOException {
Helper.print("new message: "+topic+" "+message.toString());
if(topic.equals(Luci.getMqttTree("rpc/","luci"))) {
Helper.print("new message: " + topic + " " + message.toString());
if (topic.equals(Luci.getMqttTree("rpc/", "luci"))) {
Helper.print("invio la mia configurazione");
sendFile(Luci.getMqttTree("from/","luci"));
sendFile(Luci.getMqttTree("from/", "luci"));
return;
}
if(topic.equals("to/all")) {
if (topic.equals("to/all")) {
Helper.print("invio il mio stato");
sendStatus(Luci.getMqttTree("from/","luci"));
sendStatus(Luci.getMqttTree("from/", "luci"));
return;
}
JSONObject msgJson = new JSONObject(message.toString());
//la beaglebone risponde sutopic {"event":1} se è acceso, 0 altrimenti
if(topic.equals(Luci.getMqttTree("to", "luci/new"))){
// la beaglebone risponde sutopic {"event":1} se è acceso, 0 altrimenti
if (topic.equals(Luci.getMqttTree("to", "luci/new"))) {
JSONObject config = new JSONObject(Helper.leggiFile(Luci.FILE_ZONA));
String nome= msgJson.getString("nome");
for(Luce k: Luci.luciList) {
if(k.getNome().equalsIgnoreCase(nome)) {
//luci.sendMqttMessage(topic, topic)//che ci scrivo se fallisco?
//rispondi impossibile su topic
String nome = msgJson.getString("nome");
for (Luce k : Luci.luciList) {
if (k.getNome().equalsIgnoreCase(nome)) {
System.out.println("Nome gia' presente, inserimento annullato\n");
return;
}
}
int k=Luci.luciList.size();
config.put("lamp"+k, msgJson);
//System.out.println("---"+config);
Luci.luciList.add(new Luce(msgJson));//,"lamp"+k
int k = Luci.luciList.size();
config.put("lamp" + k, msgJson);
// System.out.println("---"+config);
Luci.luciList.add(new Luce(msgJson));// ,"lamp"+k
Helper.scriviFile(config, Luci.FILE_ZONA);
luci.sendMqttMessage(Luci.getMqttTree("from", "luci/new"), msgJson.toString());
return;
}
if(topic.equals(Luci.getMqttTree("to", "luci/sensore"))){
//salvati il sensore di movimento
sensM=msgJson.getString("sensM");
//devo aggiornare in file
if (topic.equals(Luci.getMqttTree("to", "luci/sensore"))) {
// salvati il sensore di movimento
sensM = msgJson.getString("sensM");
// devo aggiornare in file
JSONObject config = new JSONObject(Helper.leggiFile(Luci.FILE_ZONA));
config.put("sensM", sensM);
Helper.scriviFile(config, Luci.FILE_ZONA);
luci.sendMqttMessage(Luci.getMqttTree("from", "luci/sensore"), msgJson.toString());
return;
} // gruppo2/luci/luci/sensore
// sensM tempo
if (topic.equals(Luci.getMqttTree("from", "gpio/" + sensM))) {
System.out.println(giorno);
if(giorno)return;
}//gruppo2/luci/luci/sensore
//sensM tempo
if(topic.equals(Luci.getMqttTree("from", "gpio/"+sensM))){
//prendo l'ultimo pezzo del topic, diventa il mio nome
//String nomeSensM =topic.substring(23);//seleziono solo il nome della lamp
//System.out.println("nome lamp\t"+pezzo);
//if(nomeSensM==sensM) {
//Esecutore es=new Esecutore(luci);
//Esecutore esec= new
if(msgJson.has("event")&& msgJson.getInt("event")==1)esec.run();
if (msgJson.has("event") && msgJson.getInt("event") == 1) {
if (runningEsec) {
Esecutore.timer.cancel();
Esecutore.timer.purge();
} else {
for (Luce k : Luci.luciList) {
if (k.getStato())
Esecutore.j.add(k);
}
}
runningEsec = true;
esec.run(runningEsec);
//
}
return;
}
//}
//controllo i topic su cui mi arrivano gli on/off
if(topic.startsWith(Luci.getMqttTree("from", "gpio/IN"))){
//prendo l'ultimo pezzo del topic, diventa il mio nome
String pezzo =topic.substring(23);//seleziono solo il nome della lamp
System.out.println("nome lamp\t"+pezzo);
for(int i=0;i<Luci.luciList.size();i++) {
if(Luci.luciList.get(i).getIN().equalsIgnoreCase(pezzo) && msgJson.has("event") && msgJson.getInt("event")==1) {//non è k.getIN()?
String req=Luci.luciList.get(i).getStato() ? "{cmd:0}":"{cmd:1}";
// if(Luci.luciList.get(i).getStato()) {
// req = "{cmd:0}";
// //topic corretto? poi risponde, se risposta è ok allora setto stato e scrivo
// }
// else {req="{cmd:1}";}
luci.sendMqttMessage(luci.getMqttTree("to", "gpio/" + Luci.luciList.get(i).getOUT()), req);
//to/gruppo2/luci/gpio/OUTn
//JSON {cmd:1} o 0 accendi/spegni
// controllo i topic su cui mi arrivano gli on/off
if (topic.startsWith(Luci.getMqttTree("from", "gpio/IN"))) {
// prendo l'ultimo pezzo del topic, diventa il mio nome
String pezzo = topic.substring(23);// seleziono solo il nome della lamp
System.out.println("nome lamp\t" + pezzo);
for (int i = 0; i < Luci.luciList.size(); i++) {
if (Luci.luciList.get(i).getIN().equalsIgnoreCase(pezzo) && msgJson.has("event")
&& msgJson.getInt("event") == 1) {// non è k.getIN()?
String req = Luci.luciList.get(i).getStato() ? "{cmd:0}" : "{cmd:1}";
luci.sendMqttMessage(Luci.getMqttTree("to", "gpio/" + Luci.luciList.get(i).getOUT()), req);
}
}
return;
}//gruppo2/luci/luci/sensore
if(topic.startsWith(Luci.getMqttTree("from", "gpio/OUT"))){
if(msgJson.has("status"))return;
String pezzo =topic.substring(23);//seleziono solo il nome della lamp
System.out.println("nome lamp\t"+pezzo);
for(int i=0;i<Luci.luciList.size();i++) {
if(Luci.luciList.get(i).getOUT().equalsIgnoreCase(pezzo) && msgJson.has("event")) {
//&& msgJson.getInt("event")==1)
boolean stato= msgJson.getInt("event")==1;
Luci.luciList.get(i).setStato(stato);//(!Luci.luciList.get(i).getStato());
return;
} // gruppo2/luci/luci/sensore
if (topic.startsWith(Luci.getMqttTree("from", "gpio/OUT"))) {
if (msgJson.has("status"))
return;
String pezzo = topic.substring(23);// seleziono solo il nome della lamp
System.out.println("nome lamp\t" + pezzo);
for (int i = 0; i < Luci.luciList.size(); i++) {
if (Luci.luciList.get(i).getOUT().equalsIgnoreCase(pezzo) && msgJson.has("event")) {
// && msgJson.getInt("event")==1)
boolean stato = msgJson.getInt("event") == 1;
Luci.luciList.get(i).setStato(stato);// (!Luci.luciList.get(i).getStato());
JSONObject config = new JSONObject(Helper.leggiFile(Luci.FILE_ZONA));
JSONObject lux=new JSONObject();
JSONObject lux = new JSONObject();
lux.put("nome", Luci.luciList.get(i).getNome());
lux.put("stato", Luci.luciList.get(i).getStato());
lux.put("input", Luci.luciList.get(i).getIN());
lux.put("output", Luci.luciList.get(i).getOUT());
config.put("lamp"+i, lux);
Helper.scriviFile(config, Luci.FILE_ZONA);
//mando conferma
config.put("lamp" + i, lux);
Helper.scriviFile(config, Luci.FILE_ZONA);
// mando conferma
lux.remove("input");
lux.remove("nome");
luci.sendMqttMessage(Luci.getMqttTree("from", "luci/luce"), lux.toString() );
luci.sendMqttMessage(Luci.getMqttTree("from", "luci/luce"), lux.toString());
}
}
return;
}
if (topic.startsWith(Luci.getMqttTree("from", "arduino/AN0"))) {
if (msgJson.has("event")){
//
// if(msgJson.getInt("event")<200)giorno=false;
// else giorno=true;
giorno=(msgJson.getInt("event")>=200);
}
return;
}
Helper.print("Impossibile");
}
private void sendFile(String topic) throws MqttException, JSONException, IOException {
JSONObject j = new JSONObject(Helper.leggiFile(Luci.FILE_ZONA));
//System.out.println(luci.FILE_ZONA);
//j.put("stato", luci.luciList.toString());
luci.sendMqttMessage(topic, j.toString());
}
private void sendStatus(String topic) throws MqttException, JSONException, IOException {
JSONObject j = new JSONObject(Helper.leggiFile(Luci.FILE_ZONA));
j.remove("sensM");
//System.out.println(luci.FILE_ZONA);
//j.put("stato", luci.luciList.toString());
luci.sendMqttMessage(topic, j.toString());
}
}
\ No newline at end of file
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