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

LuciMicro da testare

parent 99ee3792
No related branches found
No related tags found
No related merge requests found
{"lamp1":"OUT5",
"lamp2":"OUT6",
"att1":"IN6",
"att2":"IN7",
"sensM":"IN5"
{
"sensM":"IN5",
"lamp0":{
"nome":"cucina",
"stato":false,
"input":"IN6",
"output":"OUT5"
}
}
package code;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
public class Automa {
private boolean stato;
private JSONObject jsonObject;// leggo e scrivo stato attuale-possibilità
private final String DATABASE_PATH = "./Luci.json";
public boolean unreadStatus = false;
public Automa() throws JSONException, IOException {
this.jsonObject = new JSONObject(Helper.leggiFile(DATABASE_PATH));
setCollaterals(this.jsonObject.getInt("stato-attuale"));
}
private synchronized void setCollaterals(int stato) {
setCollaterals(stato,false);
}
private synchronized void setCollaterals(int stato,boolean write) {
switch (stato) {
case 0: {
this.stato = false;
break;
}
case 1: {
this.stato = true;
break;
}
}
unreadStatus = true;
// notifyAll();
/*
if(write)
writeStatoOnDatabase();*/
}
}
package code;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONException;
import org.json.JSONObject;
public class Esecutore extends Thread {
private final Luci luci;
static private Timer timer;
public Esecutore(Luci luci) throws IOException, JSONException {
this.luci = luci;
timer = new Timer();
}
class AccendiTutto extends TimerTask {
int durata=2;
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
public void run() {
if (durata > 0) {
String req="{cmd=1}";
//System.out.println("Restano " + durata + " secondi");
for(Luce k:luci.luciList) {
if(k.getStato()) j.add(k);
k.setStato(true);
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);
}
}
}
public void run() {
// qui ci va la business logic
timer.schedule(new AccendiTutto(), 0, 1000);
//
//
}
}
\ No newline at end of file
......@@ -108,4 +108,21 @@ public class Helper {
public static long timeDifference(Temporal older, Temporal newer) {
return Duration.between(older, newer).toSeconds();
}
public static void print(String toPrint){
//if(Luci.shouldPrint)
System.out.println("[Scenari] "+toPrint);
}
}
package code;
import java.io.IOException;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Luce {
private boolean stato;
private String IN;
private String OUT;
private String nome;
public Luce(String out, String in, boolean st, String name) throws JSONException, IOException {
setIN(in);
setOUT(out);
setNome(name);
setStato(st);
}
public Luce(JSONObject k) throws JSONException, IOException {
this(k.getString("output"),k.getString("input"),k.getBoolean("stato"),k.getString("nome"));//, String lmp, lmp
}
public boolean getStato() {
return stato;
}
public void setStato(boolean stato) {
this.stato = stato;
}
public String getIN() {
return IN;
}
public void setIN(String iN) {
IN = iN;
}
public String getOUT() {
return OUT;
}
public void setOUT(String oUT) {
OUT = oUT;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
......@@ -4,7 +4,10 @@ import java.util.Date;
import java.util.Iterator;
import org.eclipse.paho.client.mqttv3.MqttClient;
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;
......@@ -16,18 +19,15 @@ import java.util.Collections;
public class Luci {
public ArrayList<Automa> Luci;//per ogni luce ho uno stato
public static ArrayList<Luce> luciList;//per ogni luce ho uno stato
private static String brokerUrl;
//private String learnTrigger;
//private String attivaScenari;
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 Automa automa;
private String mqttDomain;
private String mqttSubdomain;
private static String mqttTree;
......@@ -36,7 +36,7 @@ public class Luci {
public static final String CONF_FOLDER = RES_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"
private final static String FILE_ZONA = "CONF/zona.json";//"./CONF/zona.json"
final static String FILE_ZONA = "CONF/zona.json";//"./CONF/zona.json"
public MqttClient mqttClient;
......@@ -45,7 +45,9 @@ public class Luci {
public Luci() throws JSONException, IOException, MqttException {
JSONObject config = new JSONObject(Helper.leggiFile(FILE_CONF));
luciList= new ArrayList<Luce>();
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");
......@@ -57,6 +59,7 @@ public class Luci {
// 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");
......@@ -91,104 +94,60 @@ public class Luci {
public static void main(String args[]) throws JSONException, IOException, MqttException {
System.out.println("started");
//PER TESTARE PRIMA TOGLI IL TRY CATCH !!!!! POI QUANDO TUTTO FUNZIONA, METTI IL TRY CATCH, togli le throws E IMPLEMENTA LA RIPARTENZA!
// while(true) {
// try {
startSystemo();
// }
// catch(Exception e) {
// // DA FARE:
// // qui metto il codice per far ripartire il processo: rileggo lo stato dei sensori e dell'interruttore,
// // capisco di conseguenza in quale stato dell'automa mi trovo e riparto.
// startSystem();
// }
// }
// Scenari antifurto =
// new Scenari(new Automa());
startSystemo();
}
private static void startSystemo() throws JSONException, IOException, MqttException {
// MyQueue<Integer> codaVal = new MyQueue<Integer>();
// MyQueue<Pair> codaMsg = ;
JSONObject config = new JSONObject(Helper.leggiFile(FILE_ZONA));
System.out.println(config);
//conto quante lampadine
Iterator<String> keys = config.keys();
int countI=0;
int countO=0;
while(keys.hasNext()) {
String key = keys.next();
if (config.get(key) instanceof String) {
System.out.println(config.get(key));
if(config.get(key).toString().contains("OUT")) countO++;
if(config.get(key).toString().contains("IN")) countI++;
}
String sensM=config.getString("sensM");
int index=0;
while (config.has("lamp"+index)) { //(keys.hasNext()) {
//String key = keys.next();
//if (config.get(key) instanceof String) {
JSONObject k=new JSONObject (config.get("lamp"+index));
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++;
}
System.out.println(countI);
System.out.println(countO);
ArrayList<Automa> automa = new ArrayList<Automa>();
//Luci luci = new Luci(automa);
// Publisher publisher = new Publisher(new MyQueue<Pair>(), scenari);
// Esecutore esec = new Esecutore(publisher, codaVal, automa, antifurto.interruttoreOutputSuono);
//Esecutore esec = new Esecutore(/*publisher,*/automa,scenari);
// Timer timer = new Timer(30000,-5,esec,automa);
//luci.startClient(esec/*,publisher*/);//, publisher);
// publisher.start();
//esec.start();
// timer.start();
Luci luci = new Luci();
Esecutore esec = new Esecutore(luci);
luci.startClient(esec,sensM/*,publisher*/);//, publisher);
esec.start();
}
/*
private int setAutomi() throws JSONException, IOException {
jsonObject = new JSONObject(Helper.leggiFile(DATABASE_PATH));
setCollaterals(this.jsonObject.getInt("stato-attuale"));
public void sendMqttMessage(String topic, String msg) throws MqttException {
final MqttTopic msgTopic = mqttClient.getTopic(topic);
msgTopic.publish(new MqttMessage(msg.getBytes()));
}
private synchronized void setCollaterals(int stato,boolean write) {
switch (stato) {
case 0: {
this.stato = false;
break;
}
case 1: {
this.stato = true;
break;
}
}
unreadStatus = true;
// notifyAll();
if(write)
writeStatoOnDatabase();
public void startClient(Esecutore esec, String sensM) throws MqttException {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("gruppo2");
options.setPassword("funziona".toCharArray());
options.setCleanSession(false);
mqttClient.setCallback(new Subscriber(this, esec, sensM));
mqttClient.connect(options);
for(String t: topicsSub)
mqttClient.subscribe(t);
// query the antifurto microservice to set the SAME luceAntifurto
String req = "{\"request\":\"out\"}";
sendMqttMessage(Luci.getMqttTree("to", "antifurto/luceAntifurto"), req); //wat
}
*/
}
package code;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//import scenari.Automa;
//import scenari.Scenari;
public class Subscriber implements MqttCallback{
private Luci luci;
private Esecutore esec;
public String sensM;
public Subscriber(Luci luci, Esecutore esec, String sensm) {
this.luci=luci;
this.esec = esec;
this.sensM = sensm;
}
@Override
public void connectionLost(Throwable arg0) {
Helper.print("connessione persa\t"+arg0);
final Date d = new Date();
Date d2 = new Date();
long time = Math.abs(d2.getTime()-d.getTime());
while (time<600000) {
try {
Helper.print("retrying...");
Luci.main(null);
return;
} catch (MqttException | JSONException | IOException e) {
Helper.print("non sono riusciuto");
d2 = new Date();
time = Math.abs(d2.getTime()-d.getTime());
}
}
Helper.print("fuori dal while");
if(time>=600000) {
Helper.print("Tentativo di riconnessione fallito");
System.exit(1);
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
Helper.print("inviato");
}
@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("invio la mia configurazione");
sendRequested(Luci.getMqttTree("from/","luci"),true);
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"))){
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
System.out.println("Nome gia' presente, inserimento annullato\n");
return;
}
}
int k=Luci.luciList.size();
config.put("lamp"+k, msgJson);
Luci.luciList.add(new Luce(msgJson));//,"lamp"+k
Helper.scriviFile(config, Luci.FILE_ZONA);
}
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);
}//gruppo2/luci/luci/sensore
//controllo i topic su cui mi arrivano gli on/off
if(topic.startsWith(Luci.getMqttTree("from", "luci/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
Luci.luciList.get(i).setStato(!Luci.luciList.get(i).getStato());
JSONObject config = new JSONObject(Helper.leggiFile(Luci.FILE_ZONA));
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);
}
}
//sensM tempo
if(topic.startsWith(Luci.getMqttTree("from", "luci/gpio/IN"))){
//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);
es.run();
}
}
}//gruppo2/luci/luci/sensore
Helper.print("Impossibile");
}
private void sendRequested(String topic,boolean moreInfo) throws MqttException, JSONException, IOException {
JSONObject j = new JSONObject(luci.FILE_ZONA);
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