Main Refactor
- Main now is called SeniorAssistant - Moved all threads methods of main in VariousThreads - Added class VariousThreads - Handled rest exception better
This commit is contained in:
@@ -1,19 +1,3 @@
|
|||||||
Manifest-Version: 1.0
|
Manifest-Version: 1.0
|
||||||
Class-Path: jackson-annotations-2.9.0.jar jetty-server-9.4.8.v20171121
|
Main-Class: main.SeniorAssistant
|
||||||
.jar google-oauth-client-jetty-1.23.0.jar httpcore-4.4.10.jar google-
|
|
||||||
http-client-1.23.0.jar jetty-xml-9.4.8.v20171121.jar jetty-client-9.4
|
|
||||||
.8.v20171121.jar commons-logging-1.2.jar jetty-util-9.4.8.v20171121.j
|
|
||||||
ar google-http-client-jackson2-1.23.0.jar google-oauth-client-java6-1
|
|
||||||
.23.0.jar jackson-databind-2.9.5.jar zway-lib-0.2.9-SNAPSHOT.jar jett
|
|
||||||
y-security-9.4.8.v20171121.jar guava-jdk5-17.0.jar gson-2.8.1.jar slf
|
|
||||||
4j-simple-1.7.25.jar javax.servlet-api-3.1.0.jar jetty-webapp-9.4.8.v
|
|
||||||
20171121.jar jsr305-1.3.9.jar jetty-io-9.4.8.v20171121.jar websocket-
|
|
||||||
client-9.4.8.v20171121.jar sqlite-jdbc-3.21.0.1.jar websocket-api-9.4
|
|
||||||
.8.v20171121.jar spark-core-2.7.2.jar httpclient-4.5.6.jar libai-1.6.
|
|
||||||
12.jar google-oauth-client-1.23.0.jar websocket-server-9.4.8.v2017112
|
|
||||||
1.jar jetty-servlet-9.4.8.v20171121.jar google-api-client-1.23.0.jar
|
|
||||||
jetty-http-9.4.8.v20171121.jar websocket-common-9.4.8.v20171121.jar w
|
|
||||||
ebsocket-servlet-9.4.8.v20171121.jar commons-codec-1.10.jar jackson-c
|
|
||||||
ore-2.9.5.jar slf4j-api-1.7.25.jar
|
|
||||||
Main-Class: main.Main
|
|
||||||
|
|
||||||
|
|||||||
@@ -53,8 +53,8 @@ dependencies {
|
|||||||
//compile 'org.eclipse.swt:org.eclipse.swt.win32.win32.x86_64:4.3' //Winzozz 64
|
//compile 'org.eclipse.swt:org.eclipse.swt.win32.win32.x86_64:4.3' //Winzozz 64
|
||||||
//compile 'org.eclipse.swt:org.eclipse.swt.gtk.linux.x86:4.3' //Linuzuzz 32
|
//compile 'org.eclipse.swt:org.eclipse.swt.gtk.linux.x86:4.3' //Linuzuzz 32
|
||||||
//compile files('lib/SWT_linux32.jar')
|
//compile files('lib/SWT_linux32.jar')
|
||||||
compile files('lib/SWT_linux64.jar')
|
//compile files('lib/SWT_linux64.jar')
|
||||||
//compile files('lib/SWT_win64.jar')
|
compile files('lib/SWT_win64.jar')
|
||||||
compile group: 'com.hynnet', name: 'DJNativeSwing', version: '1.0.0'
|
compile group: 'com.hynnet', name: 'DJNativeSwing', version: '1.0.0'
|
||||||
compile group: 'com.hynnet', name: 'DJNativeSwing-SWT', version: '1.0.0'
|
compile group: 'com.hynnet', name: 'DJNativeSwing-SWT', version: '1.0.0'
|
||||||
}
|
}
|
||||||
|
|||||||
136
src/main/java/main/SeniorAssistant.java
Normal file
136
src/main/java/main/SeniorAssistant.java
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
package main;
|
||||||
|
|
||||||
|
import device.*;
|
||||||
|
import support.database.Database;
|
||||||
|
import support.database.LocalDB;
|
||||||
|
import support.database.RemoteDB;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by 20015159 on 28/08/2018.
|
||||||
|
* Ci si puo' interfacciare con l'assistente tramite Telegram o dal sito di ngrok.
|
||||||
|
*/
|
||||||
|
public class SeniorAssistant {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Funzione principale, qui si creano tutte le classi che verranno utilizzate.<br>
|
||||||
|
* Si possono passare dei parametri usando -(nome parametro)::(valore parametro)<br>
|
||||||
|
* Ogni parametro deve esser separato da uno o piu spazi<br>
|
||||||
|
* Parametri possibili:<br>
|
||||||
|
* <ul>
|
||||||
|
* <li>hueAddress</li>
|
||||||
|
* <li>hueUser</li>
|
||||||
|
* <li>sensorAddress</li>
|
||||||
|
* <li>sensorNode</li>
|
||||||
|
* <li>remoteDbUser</li>
|
||||||
|
* </ul>
|
||||||
|
* @param args i possibili argomenti da passare al programma
|
||||||
|
*/
|
||||||
|
public static void main(String[] args) {
|
||||||
|
VariousThreads threads = new VariousThreads(); // this should be the first action of the main
|
||||||
|
Map<String, String> arguments = getArgsMap(args);
|
||||||
|
|
||||||
|
// list of arguments to use in the classes
|
||||||
|
String hueAddress = arguments.get("hueAddress");
|
||||||
|
String hueUser = arguments.get("hueUser");
|
||||||
|
//TODO String sensorAddress = arguments.get("sensorAddress");
|
||||||
|
Integer sensorNode = getInt(arguments.get("sensorNode"));
|
||||||
|
String remoteDbUser = arguments.get("remoteDbUser");
|
||||||
|
|
||||||
|
try {
|
||||||
|
VariousThreads.LOG.info("Connessione alle Philips Hue...");
|
||||||
|
Hue lights = new Hue(hueAddress, hueUser);
|
||||||
|
|
||||||
|
try {
|
||||||
|
VariousThreads.LOG.info("Connessione ai sensori...");
|
||||||
|
Sensor sensor = new Sensor(sensorNode);
|
||||||
|
|
||||||
|
threads.startHueAutoBrightness(lights, sensor);
|
||||||
|
} catch (Exception e) {
|
||||||
|
VariousThreads.LOG.warn(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
VariousThreads.LOG.info("Connessione al Fitbit, ignorare eventuale errore per setPermissionsToOwnerOnly...");
|
||||||
|
Fitbit fitbit = new Fitbit();
|
||||||
|
|
||||||
|
VariousThreads.LOG.info("Connessione al database...");
|
||||||
|
Database database = remoteDbUser == null ? new LocalDB() : new RemoteDB(remoteDbUser);
|
||||||
|
|
||||||
|
threads.startInsertData(database, fitbit);
|
||||||
|
threads.startHueControlledByHeartBeat(lights, fitbit, database);
|
||||||
|
threads.startCheckSteps(fitbit);
|
||||||
|
} catch (Exception e) {
|
||||||
|
VariousThreads.LOG.warn("Non e' stato possibile collegarsi al fitbit");
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
threads.startWebhook(lights);
|
||||||
|
} catch (Exception e) {
|
||||||
|
VariousThreads.LOG.error(e.getMessage());
|
||||||
|
}
|
||||||
|
VariousThreads.LOG.info("FINE MAIN");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
TODO AUTOMATIC: {B}, {D}
|
||||||
|
|
||||||
|
XXX Gestione DB in modo che si aggiorni ogni ora
|
||||||
|
/B/ Gestione luci in modo che la luminosità sia sempre la stessa
|
||||||
|
XXX Gestione luci a seconda del battito cardiaco
|
||||||
|
/D/ Ad una certa ora guarda i passi e se sono pochi dillo
|
||||||
|
XXX Se i battiti sono troppo bassi/alti avvisare il tizio
|
||||||
|
|
||||||
|
TODO USER-INTERACTION {A}, {C}
|
||||||
|
|
||||||
|
/A/ Dati del sonno/battito/passi che l'utente puo' richiedere
|
||||||
|
XXX Gestione luci secondo le esigenze dell'utente ( settare Dialogflow e server + risolvere bug )
|
||||||
|
XXX Gestione musica tramite comando vocale
|
||||||
|
TODO la musica non funzia su linux, ma forse
|
||||||
|
provando ad installare tramite comando: sudo apt-get install ia32-libs-gtk
|
||||||
|
oppure con: sudo apt-get install libgtk-3-dev
|
||||||
|
oppure con: sudo apt-get install libgnomeui-dev libxtst-dev freeglut3-dev libgtk-3-dev libgtk2.0-dev
|
||||||
|
|
||||||
|
guardare qui: http://www.eclipse.org/swt/faq.php#gtkstartup
|
||||||
|
|
||||||
|
|
||||||
|
// Randomly at night heavy metal start
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------------------------
|
||||||
|
Le funzioni qui sotto servono solamente per gli argomenti passati al main
|
||||||
|
------------------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prende gli argomenti nel formato "-(.+)::(.+)" e li inserisce in una mappa.
|
||||||
|
* Se l'argomento non e' nel formato giusto lo ignora.
|
||||||
|
* @param args un'array di stringhe contente i vari argomenti
|
||||||
|
* @return una mappa con key il nome dell'argomento (la parte prima del :: e dopo il meno) e come valore il valore di esso (la parte dopo ::)
|
||||||
|
*/
|
||||||
|
private static Map<String, String> getArgsMap(String[] args) {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
Pattern pattern = Pattern.compile("-(.+)::(.+)");
|
||||||
|
|
||||||
|
for (String arg: args) {
|
||||||
|
Matcher matcher = pattern.matcher(arg);
|
||||||
|
if (matcher.find())
|
||||||
|
map.put(matcher.group(1), matcher.group(2));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Funzione creata per gli argomenti che vengono passati in modo da evitare millemila try and catch
|
||||||
|
* @param num la stringa da trasformare in numero
|
||||||
|
* @return il numero trasformato, null se fallisce
|
||||||
|
*/
|
||||||
|
private static Integer getInt(String num) {
|
||||||
|
Integer returnNum = null;
|
||||||
|
try { returnNum = Integer.parseInt(num); } catch (Exception e) {}
|
||||||
|
return returnNum;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,104 +1,50 @@
|
|||||||
package main;
|
package main;
|
||||||
|
|
||||||
import device.*;
|
import device.DialogFlowWebHook;
|
||||||
|
import device.Fitbit;
|
||||||
|
import device.Hue;
|
||||||
|
import device.Sensor;
|
||||||
import device.fitbitdata.HeartRate;
|
import device.fitbitdata.HeartRate;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import support.Musich;
|
import support.Musich;
|
||||||
import support.database.Database;
|
import support.database.Database;
|
||||||
import support.database.LocalDB;
|
|
||||||
import support.database.RemoteDB;
|
|
||||||
|
|
||||||
|
import java.sql.Timestamp;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
/**
|
public class VariousThreads {
|
||||||
* Created by 20015159 on 28/08/2018.
|
|
||||||
* Ci si puo' interfacciare con l'assistente tramite Telegram o dal sito di ngrok.
|
|
||||||
*/
|
|
||||||
public class Main {
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Un Logger per capire meglio quali pezzi vengono eseguiti e quali no.
|
* Un Logger per capire meglio quali pezzi vengono eseguiti e quali no.
|
||||||
*/
|
*/
|
||||||
private static final Logger LOG = LoggerFactory.getLogger("SeniorAssistant");
|
public static final Logger LOG = LoggerFactory.getLogger("SeniorAssistant");
|
||||||
|
|
||||||
private static Hue lights = null;
|
|
||||||
private static Fitbit fitbit = null;
|
|
||||||
private static Sensor sensor = null;
|
|
||||||
private static Database database = null;
|
|
||||||
private static Musich musich = new Musich();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Funzione principale, qui si creano tutte le classi che verranno utilizzate.<br>
|
* Una costante che indica quanti millisecondi ci sono in un minuto (utile per le conversioni)
|
||||||
* Si possono passare dei parametri usando -(nome parametro)::(valore parametro)<br>
|
|
||||||
* Ogni parametro deve esser separato da uno o piu spazi<br>
|
|
||||||
* Parametri possibili:<br>
|
|
||||||
* <ul>
|
|
||||||
* <li>hueAddress</li>
|
|
||||||
* <li>hueUser</li>
|
|
||||||
* <li>sensorNode</li>
|
|
||||||
* <li>sensorLog</li>
|
|
||||||
* <li>remoteDbUser</li>
|
|
||||||
* </ul>
|
|
||||||
* @param args
|
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args) {
|
public static final int MILLISEC_IN_MINUTE = 60000;
|
||||||
System.getProperty("sun.arch.data.model");
|
|
||||||
Map<String, String> arguments = getArgsMap(args);
|
|
||||||
|
|
||||||
// list of arguments to use in the classes
|
|
||||||
String hueAddress = arguments.get("hueAddress");
|
|
||||||
String hueUser = arguments.get("hueUser");
|
|
||||||
Integer sensorLog = getInt(arguments.get("sensorLog"));
|
|
||||||
Integer sensorNode = getInt(arguments.get("sensorNode"));
|
|
||||||
String remoteDbUser = arguments.get("remoteDbUser");
|
|
||||||
|
|
||||||
try {
|
/**
|
||||||
LOG.info("Connessione alle Philips Hue...");
|
* La variabile per far partire della musica da Youtube
|
||||||
lights = new Hue(hueAddress, hueUser);
|
*/
|
||||||
|
private final Musich musich;
|
||||||
|
|
||||||
try {
|
/**
|
||||||
LOG.info("Connessione ai sensori...");
|
* Costruttore
|
||||||
sensor = new Sensor(sensorNode);
|
*/
|
||||||
|
public VariousThreads() {
|
||||||
if(sensorLog>0)
|
musich = new Musich();
|
||||||
startSensorLog(sensorLog);
|
|
||||||
startHueAutoBrightness();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.warn(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
LOG.info("Connessione al Fitbit, ignorare eventuale errore per setPermissionsToOwnerOnly...");
|
|
||||||
fitbit = new Fitbit();
|
|
||||||
|
|
||||||
LOG.info("Connessione al database...");
|
|
||||||
database = remoteDbUser==null? new LocalDB():new RemoteDB(remoteDbUser);
|
|
||||||
|
|
||||||
startInsertData();
|
|
||||||
startCheckSteps();
|
|
||||||
startHueControlledByHeartBeat();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.warn("Non e' stato possibile collegarsi al fitbit");
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
startWebhook();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage());
|
|
||||||
}
|
|
||||||
LOG.info("FINE MAIN");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO aggingere il fitbit per la richiesta dei dati
|
||||||
/**
|
/**
|
||||||
* Fa partire il server Webhook per DialogFlow e continua l'esecuzione
|
* Fa partire il server Webhook per DialogFlow e continua l'esecuzione
|
||||||
|
* @param lights le luci che deve controllare
|
||||||
*/
|
*/
|
||||||
private static void startWebhook() {
|
public void startWebhook(final Hue lights) {
|
||||||
DialogFlowWebHook df = new DialogFlowWebHook();
|
DialogFlowWebHook df = new DialogFlowWebHook();
|
||||||
|
|
||||||
df.addOnAction("LightsON", (params) -> { lights.turnOn(); return null; });
|
df.addOnAction("LightsON", (params) -> { lights.turnOn(); return null; });
|
||||||
@@ -135,46 +81,38 @@ public class Main {
|
|||||||
//TODO aggiungere una azione che faccia in modo di richiedere dei dati in particolare
|
//TODO aggiungere una azione che faccia in modo di richiedere dei dati in particolare
|
||||||
//TODO aggiungere una azione su DialogFlow che riconosca di impostare una playlist (Rilassante, Antica...)
|
//TODO aggiungere una azione su DialogFlow che riconosca di impostare una playlist (Rilassante, Antica...)
|
||||||
|
|
||||||
LOG.info("Starting Webhook");
|
|
||||||
df.startServer();
|
df.startServer();
|
||||||
|
LOG.info("Webhook partito");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gestione DB in modo che si aggiorni ogni ora
|
* Gestione DB in modo che si aggiorni ogni ora e ogni giorno.<br>
|
||||||
|
* Da quando viene fatto partire aspetta un giorno e poi aggiorna i dati sul DB; ripete.<br>
|
||||||
|
* Da quando viene fatto partire aspetta un'ora e poi aggiorna i dati sul DB; ripete.
|
||||||
|
* @param database il database a cui inviare i dati
|
||||||
|
* @param fitbit la sorgente di dati
|
||||||
*/
|
*/
|
||||||
private static void startInsertData() {
|
public void startInsertData(final Database database, final Fitbit fitbit) {
|
||||||
try {
|
try {
|
||||||
Thread hourlyData = Database.insertHourlyDataIn(database, fitbit, 5);
|
Thread hourlyData = Database.insertHourlyDataIn(database, fitbit, 5);
|
||||||
Thread dailyData = Database.insertDailyData(database, fitbit, 5);
|
Thread dailyData = Database.insertDailyData(database, fitbit, 5);
|
||||||
|
|
||||||
LOG.info("Starting threads for automatic update");
|
|
||||||
hourlyData.start();
|
hourlyData.start();
|
||||||
dailyData.start();
|
dailyData.start();
|
||||||
|
LOG.info("Thread per gli aggiornamenti automatici partiti");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO fare auto-brightness
|
||||||
/**
|
/**
|
||||||
* funzione che logga periodicalmente i valori ricevuti dal sensore
|
* Gestione delle luci in modo che cambiano la luminosita' in base ai dati ricevuti dal sensore<br>
|
||||||
|
* Se l'utente pero' cambia il valore delle luci di sua volonta', il processo non modifichera' le luci per almeno un'ora.
|
||||||
|
* @param lights le luci da controllare
|
||||||
|
* @param sensor i sensori da cui porendere i dati
|
||||||
*/
|
*/
|
||||||
private static void startSensorLog(int minutes) {
|
public void startHueAutoBrightness(final Hue lights, final Sensor sensor) {
|
||||||
LOG.info("Starting thread for logging sensor data");
|
|
||||||
|
|
||||||
Runnable runnable = new Runnable() {
|
|
||||||
@Override
|
|
||||||
public synchronized void run() {
|
|
||||||
sensor.update(0);
|
|
||||||
LOG.info("Luminosita' rilevata: " + sensor.getBrightnessLevel());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Database.getThreadStartingEach(runnable, "sensor", minutes).start();
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO AUTO:{B} Gestione luci in modo che la luminosità sia sempre la stessa
|
|
||||||
private static void startHueAutoBrightness() {
|
|
||||||
// controllare la luminosita' arrivata dal sensore
|
// controllare la luminosita' arrivata dal sensore
|
||||||
// trovare un valore di default per ogni ora
|
// trovare un valore di default per ogni ora
|
||||||
// se troppo bassa alzare la luci di poco
|
// se troppo bassa alzare la luci di poco
|
||||||
@@ -226,8 +164,14 @@ public class Main {
|
|||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void startHueControlledByHeartBeat() {
|
/**
|
||||||
LOG.info("Starting thread lights for heartbeat");
|
* Permette di far partire un thread che controlla le Hue in base al battito cardiaco.<br>
|
||||||
|
* Il battito e' preso sia in tempo reale dal fitbit, che dal databse, che permette di fare una analisi statistica.
|
||||||
|
* @param lights le luci da controllare
|
||||||
|
* @param fitbit da dove ricevo i dati in tempo reale
|
||||||
|
* @param database da dove posso analizzare i vecchi dati
|
||||||
|
*/
|
||||||
|
public void startHueControlledByHeartBeat(final Hue lights, final Fitbit fitbit, final Database database) {
|
||||||
final int minutes = 30;
|
final int minutes = 30;
|
||||||
final int delta = 15;
|
final int delta = 15;
|
||||||
Runnable runnable = new Runnable() {
|
Runnable runnable = new Runnable() {
|
||||||
@@ -263,65 +207,54 @@ public class Main {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Database.getThreadStartingEach(runnable, "lights-with-heartbeat", minutes).start();
|
getThreadStartingEach(runnable, minutes, "lights-with-heartbeat").start();
|
||||||
|
LOG.info("Thread per il controllo delle luci tramite il battito cardiaco partito");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO AUTO:{D} Ad una certa ora guarda i passi e se sono pochi dillo
|
// TODO Ad una certa ora guarda i passi e se sono pochi dillo
|
||||||
private static void startCheckSteps() {
|
/**
|
||||||
|
* Controlla che ad una certa ora si siano fatti abbastanza passi, ed in caso contrario avvisa tramite un messaggio vocale.<br>
|
||||||
|
* E' possibile trasformarlo in controlla ogni X se si sono fatti dei movimenti o meno.
|
||||||
|
* @param fitbit da dove vediamo se si sono fatti abbastanza passi
|
||||||
|
*/
|
||||||
|
public void startCheckSteps(final Fitbit fitbit) {
|
||||||
// trovare un orario (magari inserirlo tramite arg)
|
// trovare un orario (magari inserirlo tramite arg)
|
||||||
// a quell'ora controllare i passi fatti durante la giornata
|
// a quell'ora controllare i passi fatti durante la giornata
|
||||||
// se pochi mandare un avviso tramite dialogFlow(?)
|
// se pochi mandare un avviso tramite dialogFlow(?)
|
||||||
// (secondo me si puo' evitare)
|
// (secondo me si puo' evitare)
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
TODO AUTOMATIC: {B}, {D}
|
|
||||||
|
|
||||||
XXX Gestione DB in modo che si aggiorni ogni ora
|
|
||||||
/B/ Gestione luci in modo che la luminosità sia sempre la stessa
|
|
||||||
XXX Gestione luci a seconda del battito cardiaco
|
|
||||||
/D/ Ad una certa ora guarda i passi e se sono pochi dillo
|
|
||||||
XXX Se i battiti sono troppo bassi/alti avvisare il tizio
|
|
||||||
|
|
||||||
TODO USER-INTERACTION {A}, {C}
|
|
||||||
|
|
||||||
/A/ Dati del sonno/battito/passi che l'utente puo' richiedere
|
|
||||||
XXX Gestione luci secondo le esigenze dell'utente ( settare Dialogflow e server + risolvere bug )
|
|
||||||
/C/ Gestione musica tramite comando vocale
|
|
||||||
|
|
||||||
// Randomly at night heavy metal start
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------------------------
|
|
||||||
Le funzioni qui sotto servono solamente per gli argomenti passati al main
|
|
||||||
------------------------------------------------------------------------------------ */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prende gli argomenti nel formato "-(.+)::(.+)" e li inserisce in una mappa.
|
* Restuisce un thread che se fatto partire, esegue il runnable in un sub-thread ogni X minuti<br>
|
||||||
* Se l'argomento non e' nel formato giusto lo ignora.
|
* Il sotto thread lanciato avra' lo stesso nome, ma con un trattino e la data di lancio a seguito<br>
|
||||||
* @param args un'array di stringhe contente i vari argomenti
|
* Se il thread viene interrotto non fa piu' partire il runnable e si ferma
|
||||||
* @return una mappa con key il nome dell'argomento (la parte prima del :: e dopo il meno) e come valore il valore di esso (la parte dopo ::)
|
* @param runnable il runnable da lanciare
|
||||||
|
* @param minutes i minuti da aspettare, se negativi o 0 ritorna null
|
||||||
|
* @param threadName il nome da dare al thread
|
||||||
*/
|
*/
|
||||||
private static Map<String, String> getArgsMap(String[] args) {
|
public static Thread getThreadStartingEach(final Runnable runnable, int minutes, String threadName) {
|
||||||
Map<String, String> map = new HashMap<>();
|
if(minutes<1)
|
||||||
Pattern pattern = Pattern.compile("-(.+)::(.+)");
|
return null;
|
||||||
|
|
||||||
for (String arg: args) {
|
return new Thread(new Runnable() {
|
||||||
Matcher matcher = pattern.matcher(arg);
|
@Override
|
||||||
if (matcher.find())
|
public synchronized void run() {
|
||||||
map.put(matcher.group(1), matcher.group(2));
|
boolean notInterrupted = true;
|
||||||
}
|
do {
|
||||||
return map;
|
try {
|
||||||
}
|
wait(minutes * MILLISEC_IN_MINUTE);
|
||||||
|
Thread thread = new Thread(runnable, threadName + "-" + new Timestamp(System.currentTimeMillis()));
|
||||||
/**
|
thread.start();
|
||||||
* Funzione creata per gli argomenti che vengono passati in modo da evitare millemila try and catch
|
} catch (Exception e) {
|
||||||
* @param num la stringa da trasformare in numero
|
e.printStackTrace();
|
||||||
* @return il numero trasformato, null se fallisce
|
notInterrupted = false;
|
||||||
*/
|
}
|
||||||
private static Integer getInt(String num) {
|
} while (notInterrupted);
|
||||||
Integer returnNum = null;
|
}
|
||||||
try { returnNum = Integer.parseInt(num); } catch (Exception e) {}
|
}, threadName);
|
||||||
return returnNum;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,7 +94,8 @@ public class Musich {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dato l'id di un video viene fatta partire un frame contenente il video richiesto
|
* Dato l'id di un video viene fatta partire un frame contenente il video richiesto<br>
|
||||||
|
* Come al solito, youtube potrebbe far partire una pubblicita'... eh beh.
|
||||||
* @param videoId l'id del video da far vedere
|
* @param videoId l'id del video da far vedere
|
||||||
* @param seconds da quanti secondi bisogna far partire il video
|
* @param seconds da quanti secondi bisogna far partire il video
|
||||||
*/
|
*/
|
||||||
@@ -123,7 +124,8 @@ public class Musich {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dato l'id di un video viene fatta partire un frame contenente il video richiesto
|
* Dato l'id di un video viene fatta partire un frame contenente il video richiesto<br>
|
||||||
|
* Come al solito, youtube potrebbe far partire una pubblicita'... eh beh.
|
||||||
* @param videoId l'id del video da far vedere
|
* @param videoId l'id del video da far vedere
|
||||||
*/
|
*/
|
||||||
public void play(final String videoId) {
|
public void play(final String videoId) {
|
||||||
@@ -131,7 +133,8 @@ public class Musich {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serve a far partire un video a caso tra quelli che corrispondono alle keyword indicate nella ricerca
|
* Serve a far partire un video a caso tra quelli che corrispondono alle keyword indicate nella ricerca<br>
|
||||||
|
* Come al solito, youtube potrebbe far partire una pubblicita'... eh beh.
|
||||||
* @param search la ricerca da fare su youtube
|
* @param search la ricerca da fare su youtube
|
||||||
* @param maxResult fra quanti risultati deve scegliere
|
* @param maxResult fra quanti risultati deve scegliere
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -41,23 +41,22 @@ public class Rest {
|
|||||||
public static Map<String, ?> get(String URL) {
|
public static Map<String, ?> get(String URL) {
|
||||||
Map<String, ?> response = new HashMap<>();
|
Map<String, ?> response = new HashMap<>();
|
||||||
|
|
||||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
|
||||||
HttpGet request = new HttpGet(URL);
|
|
||||||
|
|
||||||
CloseableHttpResponse result;
|
|
||||||
try {
|
try {
|
||||||
result = httpclient.execute(request);
|
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||||
|
HttpGet request = new HttpGet(URL);
|
||||||
|
CloseableHttpResponse result = httpclient.execute(request);
|
||||||
String json = EntityUtils.toString(result.getEntity());
|
String json = EntityUtils.toString(result.getEntity());
|
||||||
// do something useful with the response body
|
|
||||||
response = gson.fromJson(json, Map.class);
|
response = gson.fromJson(json, Map.class);
|
||||||
// should be inside a finally...
|
|
||||||
result.close();
|
result.close();
|
||||||
|
|
||||||
httpclient.close();
|
httpclient.close();
|
||||||
LOG.debug("GET response: " + json);
|
LOG.debug("GET response: " + json);
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
LOG.error("GET: " + e.getMessage());
|
LOG.error("GET: " + e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,17 +68,16 @@ public class Rest {
|
|||||||
* @param contentType the content type of the request
|
* @param contentType the content type of the request
|
||||||
*/
|
*/
|
||||||
public static void put(String URL, String contentBody, String contentType) {
|
public static void put(String URL, String contentBody, String contentType) {
|
||||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
|
||||||
HttpPut request = new HttpPut(URL);
|
|
||||||
|
|
||||||
StringEntity params;
|
|
||||||
try {
|
try {
|
||||||
params = new StringEntity(contentBody);
|
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||||
|
HttpPut request = new HttpPut(URL);
|
||||||
|
StringEntity params = new StringEntity(contentBody);
|
||||||
|
|
||||||
request.addHeader("content-type", contentType);
|
request.addHeader("content-type", contentType);
|
||||||
request.setEntity(params);
|
request.setEntity(params);
|
||||||
// I don't really care about the response
|
|
||||||
HttpResponse result = httpclient.execute(request);
|
HttpResponse result = httpclient.execute(request);
|
||||||
// should be in finally...
|
|
||||||
httpclient.close();
|
httpclient.close();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error("PUT: " + e.getMessage());
|
LOG.error("PUT: " + e.getMessage());
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ import device.fitbitdata.Sleep;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.sql.Timestamp;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static main.VariousThreads.MILLISEC_IN_MINUTE;
|
||||||
|
import static main.VariousThreads.getThreadStartingEach;
|
||||||
|
|
||||||
public interface Database {
|
public interface Database {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,11 +18,6 @@ public interface Database {
|
|||||||
*/
|
*/
|
||||||
Logger LOG = LoggerFactory.getLogger("DB");
|
Logger LOG = LoggerFactory.getLogger("DB");
|
||||||
|
|
||||||
/**
|
|
||||||
* Una costante che indica quanti millisecondi ci sono in un minuto (utile per le conversioni)
|
|
||||||
*/
|
|
||||||
int MILLISEC_IN_MINUTE = 60000;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dice solamente se e' possibile collegarsi al database e se si possono fare delle query
|
* Dice solamente se e' possibile collegarsi al database e se si possono fare delle query
|
||||||
* @return vero se si pu' falso in altri casi.
|
* @return vero se si pu' falso in altri casi.
|
||||||
@@ -85,7 +82,7 @@ public interface Database {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return getThreadStartingEach(runnable, "update-hourly-data", 60);
|
return getThreadStartingEach(runnable, 60, "update-hourly-data");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -121,36 +118,6 @@ public interface Database {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return getThreadStartingEach(runnable, "update-daily-data", 24*60);
|
return getThreadStartingEach(runnable, 24*60, "update-daily-data");
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Restuisce un thread che se fatto partire, esegue il runnable in un sub-thread ogni X minuti<br>
|
|
||||||
* Il sotto thread lanciato avra' lo stesso nome, ma con un trattino e la data di lancio a seguito<br>
|
|
||||||
* Se il thread viene interrotto non fa piu' partire il runnable e si ferma
|
|
||||||
* @param runnable il runnable da lanciare
|
|
||||||
* @param threadName il nome da dare al thread
|
|
||||||
* @param minutes i minuti da aspettare, se negativi o 0 ritorna null
|
|
||||||
*/
|
|
||||||
static Thread getThreadStartingEach(final Runnable runnable, String threadName, int minutes) {
|
|
||||||
if(minutes<1)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
return new Thread(new Runnable() {
|
|
||||||
@Override
|
|
||||||
public synchronized void run() {
|
|
||||||
boolean notInterrupted = true;
|
|
||||||
do {
|
|
||||||
try {
|
|
||||||
wait(minutes * MILLISEC_IN_MINUTE);
|
|
||||||
Thread thread = new Thread(runnable, threadName + "-" + new Timestamp(System.currentTimeMillis()));
|
|
||||||
thread.start();
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
notInterrupted = false;
|
|
||||||
}
|
|
||||||
} while (notInterrupted);
|
|
||||||
}
|
|
||||||
}, threadName);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,31 @@
|
|||||||
package support.database;
|
package support.database;
|
||||||
|
|
||||||
import device.fitbitdata.HeartRate;
|
import device.fitbitdata.HeartRate;
|
||||||
|
import support.Rest;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
// TODO implement
|
// TODO implement
|
||||||
public class RemoteDB implements Database {
|
public class RemoteDB implements Database {
|
||||||
|
|
||||||
public static final String BASE_URL = "https://localhost:"; //TODO inserire il percorso giusto con la porta
|
private final String base_url;
|
||||||
|
|
||||||
private final String username;
|
private final String username;
|
||||||
|
|
||||||
public RemoteDB(String username) {
|
public RemoteDB(String username) {
|
||||||
|
this(username, "http://127.0.0.1:5001/api/");
|
||||||
|
}
|
||||||
|
|
||||||
|
public RemoteDB(String username, String base_url) {
|
||||||
this.username = username;
|
this.username = username;
|
||||||
|
this.base_url = base_url;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isReachable() {
|
public boolean isReachable() {
|
||||||
return false;
|
Map<String, ?> map = Rest.get(base_url+"user/");
|
||||||
|
LOG.info(map.toString());
|
||||||
|
return !map.isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
19
src/test/java/test/TestRemoteDB.java
Normal file
19
src/test/java/test/TestRemoteDB.java
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package test;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import support.database.Database;
|
||||||
|
import support.database.RemoteDB;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class TestRemoteDB {
|
||||||
|
|
||||||
|
private static final String REMOTE_URL = "http://127.0.0.1:5001/api/";
|
||||||
|
private static final String USERNAME = "vecchio";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
Database database = new RemoteDB(USERNAME, REMOTE_URL);
|
||||||
|
assertTrue(database.isReachable());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user