alter mqttservice to gradle

This commit is contained in:
lukas-heiligenbrunner 2020-01-31 09:37:06 +01:00
parent 5e42eeb2ae
commit 02dff914ca
3 changed files with 186 additions and 208 deletions

View File

@ -8,31 +8,31 @@ import com.wasteinformationserver.website.Webserver
import java.io.IOException import java.io.IOException
fun main() { fun main() {
Log.Log.setLevel(Log.Log.DEBUG) Log.setLevel(Log.DEBUG)
Info.init() Info.init()
Log.Log.info("startup of WasteInformationServer") Log.info("startup of WasteInformationServer")
Runtime.getRuntime().addShutdownHook(Thread(Runnable { Runtime.getRuntime().addShutdownHook(Thread(Runnable {
try { try {
Thread.sleep(200) Thread.sleep(200)
Log.Log.warning("Shutting down ...") Log.warning("Shutting down ...")
//shutdown routine //shutdown routine
} catch (e: InterruptedException) { } catch (e: InterruptedException) {
e.printStackTrace() e.printStackTrace()
} }
})) }))
Log.Log.info("Server version: " + Info.getVersion()) Log.info("Server version: " + Info.getVersion())
Log.Log.debug("Build date: " + Info.getBuilddate()) Log.debug("Build date: " + Info.getBuilddate())
//initial connect to db //initial connect to db
Log.Log.message("initial login to db") Log.message("initial login to db")
try { try {
JDBC.init("ingproject", "Kb9Dxklumt76ieq6", "ingproject", "db.power4future.at", 3306) JDBC.init("ingproject", "Kb9Dxklumt76ieq6", "ingproject", "db.power4future.at", 3306)
//JDBC.init("users", "kOpaIJUjkgb9ur6S", "wasteinformation", "192.168.65.15", 3306); //JDBC.init("users", "kOpaIJUjkgb9ur6S", "wasteinformation", "192.168.65.15", 3306);
} catch (e: IOException) { //e.printStackTrace(); } catch (e: IOException) { //e.printStackTrace();
Log.Log.error("no connection to db") Log.error("no connection to db")
} }
@ -42,7 +42,7 @@ fun main() {
//startup mqtt service //startup mqtt service
Log.Log.message("starting mqtt service") Log.message("starting mqtt service")
val m = MqttService("mqtt.heili.eu", "1883") val m = MqttService("mqtt.heili.eu", "1883")
m.startupService() m.startupService()

View File

@ -1,200 +0,0 @@
package com.wasteinformationserver.mqtt;
import com.wasteinformationserver.basicutils.Log;
import com.wasteinformationserver.db.JDBC;
import org.eclipse.paho.client.mqttv3.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Mqtt Service to receive and send back messages to the Hardware
* todo
*
* @author Lukas Heiligenbrunner
* @author Gregor Dutzler
*/
public class MqttService {
private MqttClient client = null;
private String serveruri;
private JDBC db;
/**
* init mqtt service
* JDBC has to be inited before
*
* @param serverurl mqtt server ip or hostname
* @param port mqtt server port
*/
public MqttService(String serverurl, String port) {
serveruri = "tcp://" + serverurl + ":" + port;
try {
db = JDBC.getInstance();
} catch (IOException e) {
Log.Log.error("no connetion to db");
}
}
/**
* startup of the mqtt service
*/
public void startupService() {
try {
client = new MqttClient(serveruri, "JavaSample42");
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
client.connect(connOpts);
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
Log.Log.error("connection lost");
// TODO: 12.01.20 reconnect
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) {
String deviceid = new String(mqttMessage.getPayload());
Log.Log.message("received Request from PCB");
ResultSet res = db.executeQuery("SELECT * from devices WHERE DeviceID=" + deviceid);
try {
res.last();
if (res.getRow() != 0) {
//existing device
res.first();
ResultSet devicecities = db.executeQuery("SELECT * from device_city WHERE DeviceID='" + deviceid + "'");
devicecities.last();
if (devicecities.getRow() == 0) {
//not configured
tramsmitMessage(deviceid + ",-1");
} else {
devicecities.first();
devicecities.previous();
// TODO: 23.01.20 Test this stuff
while (devicecities.next()) {
int cityid = devicecities.getInt("CityID");
checkDatabase(cityid, Integer.parseInt(deviceid));
}
}
} else {
//new device
db.executeUpdate("INSERT INTO devices (DeviceID) VALUES (" + deviceid + ")");
Log.Log.info("new device registered to server");
tramsmitMessage(deviceid + ",-1");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
client.subscribe("TopicIn");
} catch (MqttException e) {
Log.Log.error("Connection to the Broker failed");
}
}
private void checkDatabase(int citywastezoneid, int deviceid) {
int wastetype = -1;
ResultSet set2 = db.executeQuery("SELECT * FROM cities WHERE `id`='" + citywastezoneid + "'");
try {
set2.last();
if (set2.getRow() != 1) {
//error
} else {
String typ = set2.getString("wastetype");
wastetype = getIntTyp(typ);
}
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet result = db.executeQuery("SELECT pickupdates.pickupdate FROM pickupdates WHERE pickupdates.citywastezoneid=" + citywastezoneid);
try {
result.last();
if (result.getRow() == 0) {
//if not found in db --> send zero
Log.Log.debug("not found in db");
tramsmitMessage(deviceid + "," + wastetype + "," + 0);
} else {
Log.Log.debug(result.getString("pickupdate"));
result.first();
do {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
long timestamp = formatter.parse(result.getString("pickupdate")).getTime();
long timestampnow = formatter.parse(formatter.format(new Date())).getTime();
Log.Log.debug("timestamp is :" + timestamp);
if (timestamp == timestampnow || timestamp == timestampnow + 86400000) { // 86400000 == one day
// valid time
tramsmitMessage(deviceid + "," + wastetype + "," + 1);
Log.Log.debug("valid time");
return;
}
} while (result.next());
tramsmitMessage(deviceid + "," + wastetype + "," + 0); //transmit zero if not returned before
}
} catch (SQLException | ParseException e) {
e.printStackTrace();
}
}
private void tramsmitMessage(String temp) {
Log.Log.debug("sending message >>>" + temp);
MqttMessage message = new MqttMessage(temp.getBytes());
message.setQos(2);
try {
client.publish("TopicOut", message);
} catch (MqttException e) {
e.printStackTrace();
}
}
private String getTyp(int number) {
if (number == 1) {
return "Plastic";
} else if (number == 2) {
return "Metal";
} else if (number == 3) {
return "Residual waste";
} else if (number == 4) {
return "Biowaste";
}
return null;
}
private int getIntTyp(String temp) {
int number = 0;
switch (temp) {
case "Plastic":
number = 1;
break;
case "Metal":
number = 2;
break;
case "Residual waste":
number = 3;
break;
case "Biowaste":
number = 4;
break;
}
return number;
}
}

View File

@ -0,0 +1,178 @@
package com.wasteinformationserver.mqtt
import com.wasteinformationserver.basicutils.Log.Log.debug
import com.wasteinformationserver.basicutils.Log.Log.error
import com.wasteinformationserver.basicutils.Log.Log.info
import com.wasteinformationserver.basicutils.Log.Log.message
import com.wasteinformationserver.db.JDBC
import org.eclipse.paho.client.mqttv3.*
import java.io.IOException
import java.sql.SQLException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Mqtt Service to receive and send back messages to the Hardware
* todo
*
* @author Lukas Heiligenbrunner
* @author Gregor Dutzler
*/
class MqttService(serverurl: String, port: String) {
private var client: MqttClient? = null
private val serveruri: String
private var db: JDBC? = null
/**
* init mqtt service
* JDBC has to be inited before
*
* @param serverurl mqtt server ip or hostname
* @param port mqtt server port
*/
init {
serveruri = "tcp://$serverurl:$port"
connect()
}
/**
* startup of the mqtt service
*/
fun startupService() {
try {
client = MqttClient(serveruri, "JavaSample42")
val connOpts = MqttConnectOptions()
connOpts.isCleanSession = true
client!!.connect(connOpts)
client!!.setCallback(object : MqttCallback {
override fun connectionLost(throwable: Throwable) {
error("connection lost")
connect()
}
override fun messageArrived(s: String, mqttMessage: MqttMessage) {
val deviceid = String(mqttMessage.payload)
message("received Request from PCB")
val res = db!!.executeQuery("SELECT * from devices WHERE DeviceID=$deviceid")
try {
res.last()
if (res.row != 0) { //existing device
res.first()
val devicecities = db!!.executeQuery("SELECT * from device_city WHERE DeviceID='$deviceid'")
devicecities.last()
if (devicecities.row == 0) { //not configured
tramsmitMessage("$deviceid,-1")
} else {
devicecities.first()
devicecities.previous()
while (devicecities.next()) {
val cityid = devicecities.getInt("CityID")
checkDatabase(cityid, deviceid.toInt())
}
}
} else { //new device
db!!.executeUpdate("INSERT INTO devices (DeviceID) VALUES ($deviceid)")
info("new device registered to server")
tramsmitMessage("$deviceid,-1")
}
} catch (e: SQLException) {
e.printStackTrace()
}
}
override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) {}
})
client!!.subscribe("TopicIn")
} catch (e: MqttException) {
error("Connection to the Broker failed")
}
}
private fun checkDatabase(citywastezoneid: Int, deviceid: Int) {
var wastetype = -1
val set2 = db!!.executeQuery("SELECT * FROM cities WHERE `id`='$citywastezoneid'")
try {
set2.last()
if (set2.row != 1) { //error
} else {
val typ = set2.getString("wastetype")
wastetype = getIntTyp(typ)
}
} catch (e: SQLException) {
e.printStackTrace()
}
val result = db!!.executeQuery("SELECT pickupdates.pickupdate FROM pickupdates WHERE pickupdates.citywastezoneid=$citywastezoneid")
try {
result.last()
if (result.row == 0) { //if not found in db --> send zero
debug("not found in db")
tramsmitMessage("$deviceid,$wastetype,0")
} else {
debug(result.getString("pickupdate"))
result.first()
do {
val formatter = SimpleDateFormat("yyyy-MM-dd")
val timestamp = formatter.parse(result.getString("pickupdate")).time
val timestampnow = formatter.parse(formatter.format(Date())).time
debug("timestamp is :$timestamp")
if (timestamp == timestampnow || timestamp == timestampnow + 86400000) { // 86400000 == one day
// valid time
tramsmitMessage("$deviceid,$wastetype,1")
debug("valid time")
return
}
} while (result.next())
tramsmitMessage("$deviceid,$wastetype,0") //transmit zero if not returned before
}
} catch (e: SQLException) {
e.printStackTrace()
} catch (e: ParseException) {
e.printStackTrace()
}
}
private fun tramsmitMessage(temp: String) {
debug("sending message >>>$temp")
val message = MqttMessage(temp.toByteArray())
message.qos = 2
try {
client!!.publish("TopicOut", message)
} catch (e: MqttException) {
e.printStackTrace()
}
}
private fun getTyp(number: Int): String? {
if (number == 1) {
return "Plastic"
} else if (number == 2) {
return "Metal"
} else if (number == 3) {
return "Residual waste"
} else if (number == 4) {
return "Biowaste"
}
return null
}
private fun getIntTyp(temp: String): Int {
var number = 0
when (temp) {
"Plastic" -> number = 1
"Metal" -> number = 2
"Residual waste" -> number = 3
"Biowaste" -> number = 4
}
return number
}
private fun connect() {
try {
db = JDBC.getInstance()
} catch (e: IOException) {
error("no connetion to db")
}
}
}