NEW : REBASE THE ENTIRE WORKING PROJECT

This commit is contained in:
2022-02-09 19:19:09 +01:00
parent ddad60988e
commit ae93015aa8
1338 changed files with 286867 additions and 0 deletions

View File

@@ -0,0 +1 @@
70B3D57050004223,70B3D570500042D7,70B3D57050004EF4,70B3D57050006223,70B3D5705000623C

View File

@@ -0,0 +1 @@
70B3D57050004682,70B3D57050004D14

View File

@@ -0,0 +1 @@
0004A30B00227D68,70B3D5705000E019

View File

@@ -0,0 +1 @@
70B3D5705000E030,70B3D5705000E05E,70B3D5705000E386

View File

@@ -0,0 +1 @@
0Q6cHVQo9umiVSiZVf4DnsFMO4CgSv7RvpFiNMFTvZF1qiKDEVzSNpUOHegBv8wP

View File

@@ -0,0 +1,26 @@
package Files;
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public String data;
public String ReadFromFile(String path) {
try {
File myObj = new File(path);
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return data;
}
}

View File

@@ -0,0 +1,34 @@
package Files;
import java.io.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public class WriteFile {
BufferedWriter buffer = null;
public void WriteFile(String path, String input) throws Exception {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(path);
buffer = new BufferedWriter(fileWriter);
buffer.write(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (buffer != null) buffer.flush();
// buffer.close();
} catch (Exception ex) {
System.out.println("Error in closing the BufferedWriter" + ex);
}
}
}
}

View File

@@ -0,0 +1,46 @@
package HttpCall;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class HttpGet {
public String HttpGetCall(String baseURL, String token)
throws InterruptedException, ExecutionException, TimeoutException {
var client = HttpClient
.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
HttpRequest request = null;
try {
request =
HttpRequest
.newBuilder(new URI(baseURL))
.setHeader("Authorization", token)
// .setHeader("access_token", token)
.setHeader("Content-Type", "application/json")
.setHeader("Accept", "application/json")
.header("Authority", "https://api.dev.whysor.com/")
.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
CompletableFuture<HttpResponse<String>> response = client.sendAsync(
request,
HttpResponse.BodyHandlers.ofString()
);
String result = response
.thenApply(HttpResponse::body)
.get(5, TimeUnit.SECONDS);
return result;
}
}

View File

@@ -0,0 +1,41 @@
package HttpCall;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class HttpPost {
public String HttpCallPost(String baseUrl, String body) throws Exception {
var client = HttpClient
.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
HttpRequest request = null;
try {
request =
HttpRequest
.newBuilder(new URI(baseUrl))
.POST(HttpRequest.BodyPublishers.ofString(body))
.setHeader("Content-Type", "application/json")
.setHeader("Accept", "application/json")
.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
CompletableFuture<HttpResponse<String>> response = client.sendAsync(
request,
HttpResponse.BodyHandlers.ofString()
);
String result = response
.thenApply(HttpResponse::body)
.get(5, TimeUnit.SECONDS);
return result;
}
}

View File

@@ -0,0 +1,77 @@
//package JSON2RDF;
//
//import java.io.*;
//import java.net.URI;
//import java.net.URISyntaxException;
//import java.nio.charset.Charset;
//import java.nio.charset.StandardCharsets;
//
//
//import org.json.simple.JSONArray;
//import org.json.simple.parser.JSONParser;
//import org.json.simple.parser.ParseException;
//
//import org.apache.jena.riot.system.StreamRDF;
//import org.apache.jena.riot.system.StreamRDFLib;
//import picocli.CommandLine;
//
//@CommandLine.Command(name = "json2rdf")
//public class JSON2RDF {
// private final InputStream jsonIn;
// private final OutputStream rdfOut;
//
//
// @CommandLine.Parameters(paramLabel = "https://localhost/" , index = "0", description = "Base URI of the RDF output data")
// private URI baseURI;
//
// {
// try {
// baseURI = new URI("https://localhost/");
// } catch (URISyntaxException e) {
// e.printStackTrace();
// }
// }
//
//// @CommandLine.Parameters(paramLabel = "D:\\WORK\\GGD\\src\\eu.hsrw.ias.ggd.MainExe\\java\\Data", description = "json file")
// @CommandLine.Option(names = { "--input-charset" }, description = "Input charset (default: ${DEFAULT-VALUE})")
// private final Charset inputCharset = StandardCharsets.UTF_8;
//
// @CommandLine.Option(names = { "--output-charset" }, description = "Output charset (default: ${DEFAULT-VALUE})")
// private final Charset outputCharset = StandardCharsets.UTF_8;
//
// public static void main(String[] args) throws IOException
// {
// JSON2RDF json2rdf = new JSON2RDF(System.in, System.out);
//
// try
// {
// CommandLine.ParseResult parseResult = new CommandLine(json2rdf).parseArgs(args);
// if (!CommandLine.printHelpIfRequested(parseResult)) json2rdf.convert();
// }
// catch (CommandLine.ParameterException ex)
// { // command line arguments could not be parsed
// System.err.println(ex.getMessage());
// ex.getCommandLine().usage(System.err);
// }
// }
//
// public JSON2RDF(InputStream csvIn, OutputStream rdfOut) {
//
//
// this.jsonIn = csvIn;
// this.rdfOut = rdfOut;
// }
//
//
// public void convert() throws IOException {
// if (jsonIn.available() == 0) throw new IllegalStateException("JSON input not provided");
//
// try (Reader reader = new BufferedReader(new InputStreamReader(jsonIn, inputCharset)))
// {
// StreamRDF rdfStream = StreamRDFLib.writer(new BufferedWriter(new OutputStreamWriter(rdfOut, outputCharset)));
// new JsonStreamRDFWriter(reader, rdfStream, baseURI.toString()).convert();
// }
// }
//
//}
//

View File

@@ -0,0 +1,124 @@
//package JSON2RDF;
//
//import java.io.InputStream;
//import java.io.Reader;
//import java.util.ArrayDeque;
//import java.util.Deque;
//import java.util.HashMap;
//import java.util.Map;
//import javax.json.Json;
//import javax.json.stream.JsonParser;
//import org.apache.jena.datatypes.xsd.XSDDatatype;
//import org.apache.jena.graph.Node;
//import org.apache.jena.graph.NodeFactory;
//import org.apache.jena.graph.Triple;
//import org.apache.jena.riot.system.IRIResolver;
//import org.apache.jena.riot.system.StreamRDF;
//
//
//public class JsonStreamRDFWriter
//{
//
// private final JsonParser parser;
// private final StreamRDF rdfStream;
// private final IRIResolver iriResolver;
//
// public JsonStreamRDFWriter(Reader reader, StreamRDF rdfStream, String baseURI)
// {
// this(Json.createParser(reader), rdfStream, baseURI);
// }
//
// public JsonStreamRDFWriter(InputStream is, StreamRDF rdfStream, String baseURI)
// {
// this(Json.createParser(is), rdfStream, baseURI);
// }
//
// public JsonStreamRDFWriter(JsonParser parser, StreamRDF rdfStream, String baseURI)
// {
// this.parser = parser;
// this.rdfStream = rdfStream;
// this.iriResolver = IRIResolver.create(baseURI);
// }
//
// public void convert()
// {
// getStreamRDF().start();
//
// write(getParser(), getStreamRDF(), getIRIResolver());
//
// getStreamRDF().finish();
// }
//
// public static void write(JsonParser parser, StreamRDF rdfStream, IRIResolver iriResolver)
// {
// Deque<Node> subjectStack = new ArrayDeque<>();
// Map<Node, Node> arrayProperties = new HashMap<>();
//
// Node property = null;
// while (parser.hasNext())
// {
// JsonParser.Event event = parser.next();
//
// switch (event)
// {
// case START_ARRAY:
// if (!subjectStack.isEmpty() && property != null) arrayProperties.put(subjectStack.getLast(), property);
// break;
// case END_ARRAY:
// if (!subjectStack.isEmpty()) arrayProperties.remove(subjectStack.getLast());
// break;
// case START_OBJECT:
// Node subject = NodeFactory.createBlankNode();
// // add triple with current array property, if any
// if (property != null && !subjectStack.isEmpty()) rdfStream.triple(new Triple(subjectStack.getLast(), property, subject));
// subjectStack.addLast(subject);
// break;
// case END_OBJECT:
// subjectStack.removeLast();
// // restore previous array property, if there was any
// if (!subjectStack.isEmpty() && arrayProperties.containsKey(subjectStack.getLast())) property = arrayProperties.get(subjectStack.getLast());
// break;
// case VALUE_FALSE:
// rdfStream.triple(new Triple(subjectStack.getLast(), property, NodeFactory.createLiteralByValue(Boolean.FALSE, XSDDatatype.XSDboolean)));
// break;
// case VALUE_TRUE:
// rdfStream.triple(new Triple(subjectStack.getLast(), property, NodeFactory.createLiteralByValue(Boolean.TRUE, XSDDatatype.XSDboolean)));
// break;
// case KEY_NAME:
// property = NodeFactory.createURI(iriResolver.resolveToString("#" + parser.getString()));
// break;
// case VALUE_STRING:
// if (property != null) rdfStream.triple(new Triple(subjectStack.getLast(), property, NodeFactory.createLiteral(parser.getString())));
// break;
// case VALUE_NUMBER:
// try
// {
// rdfStream.triple(new Triple(subjectStack.getLast(), property,NodeFactory.createLiteralByValue(Integer.valueOf(parser.getString()), XSDDatatype.XSDint)));
// }
// catch (NumberFormatException ex)
// {
// rdfStream.triple(new Triple(subjectStack.getLast(), property,NodeFactory.createLiteralByValue(Float.valueOf(parser.getString()), XSDDatatype.XSDfloat)));
// }
// break;
// case VALUE_NULL:
// break;
// }
// }
// }
//
// protected JsonParser getParser()
// {
// return parser;
// }
//
// protected StreamRDF getStreamRDF()
// {
// return rdfStream;
// }
//
// protected IRIResolver getIRIResolver()
// {
// return iriResolver;
// }
//
//}

View File

@@ -0,0 +1,29 @@
package JSON_Unpack;
import Credentials.UserCredentials;
import Files.WriteFile;
import HttpCall.HttpGet;
import org.json.JSONArray;
//Get a list of all devices
public class GeneralCall4AllDevices {
public static String FetchAll(String token) throws Exception {
String extension = "devices";
UserCredentials userCredentials = new UserCredentials();
WriteFile writingIntoFile = new WriteFile();
String baseURL = userCredentials.getBaseURL();
String homeRoot = UserCredentials.getHomeRoot();
String devUrl = userCredentials.getDevUrl();
HttpGet httpCall = new HttpGet();
String fetchAll = httpCall.HttpGetCall(
devUrl + extension + "?access_token=" + token,
token
);
writingIntoFile.WriteFile(homeRoot + extension + "Output.json", fetchAll);
return fetchAll;
}
}

View File

@@ -0,0 +1,87 @@
package JSON_Unpack;
import Credentials.UserCredentials;
import Files.WriteFile;
import HttpCall.HttpGet;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
///url/sensors/id/read
public class ReadSensors4Partner {
public ArrayList<String> FetchSensor4Box(String companyName, String token)
throws Exception {
switch (companyName) {
case "Germes":
return SensorRead("Germes", token);
case "Heufs":
return SensorRead("Heufs", token);
case "Jacobs":
return SensorRead("Jacobs", token);
case "Nica":
return SensorRead("Nica", token);
}
return null;
}
protected ArrayList<String> SensorRead(String cName, String token)
throws Exception {
UserCredentials userCredentials = new UserCredentials();
HttpGet httpCall = new HttpGet();
WriteFile writingIntoFile = new WriteFile();
String baseURL = userCredentials.getBaseURL();
String devUrl = userCredentials.getDevUrl();
String homeRoot = UserCredentials.getHomeRoot();
ArrayList<String> list = new ArrayList<String>();
char par = '"';
BoxCall4Partner boxCall4Partner = new BoxCall4Partner();
ArrayList<String> outputBox = boxCall4Partner.FetchBox(cName, token);
for (int i = 0; i < outputBox.size(); i++) {
JSONArray jsonArray = new JSONArray(outputBox.get(i));
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonobject = jsonArray.getJSONObject(j);
String jsonID = jsonobject.getString("id");
String jsonTag = jsonobject.getString("tag");
String deviceID = jsonobject.getString("deviceId");
String finalTag =
"," +
par +
"deviceId" +
par +
":" +
deviceID +
"," +
par +
"sensorTag" +
par +
":" +
jsonTag +
"}]";
String sensorOutput = httpCall.HttpGetCall(
devUrl + "sensors/" + jsonID + "/read" + "?access_token=" + token,
token
);
if (sensorOutput.contains("error")) {
System.out.println(sensorOutput);
} else {
String modification = sensorOutput.replace("}]", "");
String finalSensorOutput = modification + finalTag;
list.add(finalSensorOutput);
writingIntoFile.WriteFile(
homeRoot + jsonID + ".json",
sensorOutput + jsonTag + "," + deviceID
);
}
}
}
return list;
}
}

View File

@@ -0,0 +1,53 @@
//package Knowledgebase;
//
//import org.json.JSONArray;
//import org.kie.api.KieServices;
//import org.kie.api.KieServices.Factory;
//import org.kie.api.runtime.KieContainer;
//import org.kie.api.runtime.KieSession;
//import org.kie.api.runtime.rule.FactHandle;
//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Map;
//
//public class DroolsTest {
// private Map<String, Double> currMap= new HashMap<>();
//
// public static final void main(String[] args) {
// try {
// KieServices ks = KieServices.Factory.get();
// KieContainer kContainer = ks.getKieClasspathContainer();
////Get the session named kseesion-rule that we defined in kmodule.xml above.
////Also by default the session returned is always stateful.
// KieSession kSession = kContainer.newKieSession("ksession-rule");
//
// currMap.put("asd",12.2);
// setCurrMap("soilMoisture",10.1);
// currMap.put("soilConductivity",0.14);
// setCurrMap set= new SetCurrMap();
// se
//
//
// FactHandle fact1;
//
// fact1 = kSession.insert(currMap);
// System.out.println(fact1);
// kSession.fireAllRules();
//
//// System.out.println("The discount for the jewellery product "
//// + sensorReadings.getSensorTag() + " is " + sensorReadings.getValue());
//
// } catch (Throwable t) {
// t.printStackTrace();
// }
// }
// public Map<String, Double> getCurrMap() {
// return currMap;
// }
//
// public void setCurrMap(Map<String, Double> currMap) {
// this.currMap = currMap;
// }
//
//}

View File

@@ -0,0 +1,78 @@
package eu.hsrw.ias.ggd;
import Credentials.UserCredentials;
import Files.WriteFile;
import JSON_Unpack.ReadSensors4Partner;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
public class ApiCall {
private static String token = "0";
private static String oldId = "1";
public static Greenhouse FetchDataFromApi() throws Exception {
UserCredentials userCredentials = new UserCredentials();
final String username = userCredentials.getUsername();
final String password = userCredentials.getPassword();
final String homeRoot = UserCredentials.getHomeRoot();
String outputToken;
WriteFile writingIntoFile = new WriteFile();
Date now; // to display current time
now = new Date();
HashMap<String, Device> devices = new HashMap();
if (token.equals(oldId)) {
//do nothing
} else {
try {
outputToken = SecurityToken.OnCallMethod(username, password);
JSONObject obj = new JSONObject(outputToken);
token = obj.getString("id");
writingIntoFile.WriteFile(homeRoot + "securityToken.txt", token);
oldId = token;
} catch (Exception e) {
e.printStackTrace();
}
}
ReadSensors4Partner readSensors4Partner = new ReadSensors4Partner();
ArrayList<String> outputValue =
(readSensors4Partner.FetchSensor4Box("Germes", token));
for (int i = 0; i < outputValue.size(); i++) {
Device device;
JSONArray sensorDatas = new JSONArray(outputValue.get(i));
for (int j = 0; j < sensorDatas.length(); j++) { //15
JSONObject sensorData = sensorDatas.getJSONObject(j);
String deviceId = sensorData.getString("deviceId");
double value = sensorData.getDouble("value");
String sensorTag = sensorData.getString("sensorTag");
String sensorId = sensorData.getString("sensorId");
SensorData sd = new SensorData(sensorId, value, sensorTag);
if (devices.containsKey(deviceId)) {
device = devices.get(deviceId);
device.addSensorData(sd);
} else {
device = new Device(deviceId);
device.addSensorData(sd);
devices.put(deviceId, device);
}
}
}
Greenhouse greenhouse = new Greenhouse();
for (Device device : devices.values()) {
greenhouse.addDevice(device);
}
return greenhouse;
}
}

View File

@@ -0,0 +1,105 @@
package eu.hsrw.ias.ggd;
import java.util.LinkedList;
import java.util.List;
public class Device {
private String id;
private String externalID;
private List<SensorData> data;
private Severity state = Severity.Unknown;
public Device(String identifier) {
this.id = identifier;
this.data = new LinkedList<SensorData>();
}
public void addSensorData(SensorData d) {
this.data.add(d);
}
public List<SensorData> getSensorData() {
return data;
}
public String getId() {
return id;
}
public String setId(String id) {
this.id = id;
return id;
}
public void setExternalID(String externalID) {
this.externalID = externalID;
}
public String getExternalID() {
return externalID;
}
public String IdMapper(String id) {
switch (id) {
case "fd694041-581e-4c2c-9810-505e62b762e6":
return setId("70B3D570500042D7");
case "e8c3fca3-c5cd-48e7-9224-0f8c294fa3c0":
return setId("70B3D57050004EF4");
case "f9bb4a5c-f783-4bcf-8c34-0a7c3dd5a632":
return setId("70B3D57050006223");
case "6c9efd4a-db04-453d-8ab8-d480ec97dd26":
return setId("70B3D5705000623C");
default:
return "NO Working id was found";
}
}
public Boolean hasTag(String tag) {
for (SensorData sensorData : data) {
if (sensorData.getTag() == tag) return true;
}
return false;
}
public SensorData getSensorDataByTag(String tag) {
for (SensorData sd : data) {
if (sd.getTag() == tag) return sd;
}
return null;
}
public SensorData getSensorDataById(String id) {
for (SensorData sd : data) {
if (sd.getSensorId() == id) return sd;
}
return null;
}
public String toString() {
String str = "Device: '" + id + "', data: [";
for (SensorData sd : data) {
str += "SensorData(id: '" + sd.getSensorId() + "',";
str += " tag: '" + sd.getTag() + "',";
str += " value: " + sd.getValue() + ")";
}
return str + "]";
}
public Device(String id, List<SensorData> data) {
this.id = id;
this.data = data;
}
public void setState(Severity state) {
if (this.state != Severity.Critical) {
this.state = state;
}
}
public Severity getState() {
return state;
}
}

View File

@@ -0,0 +1,50 @@
package eu.hsrw.ias.ggd;
import java.util.ArrayList;
import java.util.List;
public class Greenhouse {
private String id = "8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
private Severity state = Severity.Unknown;
public Greenhouse() {
this.devices = new ArrayList<>();
}
public Greenhouse(List<Device> devices) {
this.devices = devices;
}
public void addDevice(Device device) {
this.devices.add(device);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Severity getState() {
return state;
}
public void setState(Severity state) {
if (this.state != Severity.Critical) {
this.state = state;
}
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
private List<Device> devices;
}

View File

@@ -0,0 +1,32 @@
package eu.hsrw.ias.ggd;
import HttpCall.HttpPost;
public class Isis {
public static String OnCallMethod(String deviceName, String sensorName)
throws Exception {
//CONFIG PARAMETERS:
//BEGIN------------CONFIG PARAMETERS BELOW TO YOUR ENVIRONMENT---------------------------------------
String baseURL =
"https://api.dev.whysor.com/devices/readValueFromSpeech?access_token=2MreqC9fqXxFHJBEcrCL38LKhEaVcEHmEi6o45CwTV9SSgTAuZ93oiMfY3HVc2fj";
final String body = String.format(
"{\"deviceName\": \"%s\", \"sensorName\": \"%s\", \"domain\": \"my.yookr.org\"}",
deviceName,
sensorName
);
HttpPost httpMethodPost = new HttpPost();
httpMethodPost.HttpCallPost(baseURL, body);
return httpMethodPost.HttpCallPost(baseURL, body);
}
public static void main(String[] args) {
try {
String output = OnCallMethod("Greenhouse 1", "status");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,12 @@
package eu.hsrw.ias.ggd;
import java.util.Timer;
//Before pushing files to the git run : npx prettier --write "**/*.java"
public class MainExe {
public static void main(String[] args) {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask scheduledTask = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(scheduledTask, 0, 1000 * 60 * 1); // Create Repetitively task for every 2 min
}
}

View File

@@ -0,0 +1,38 @@
package eu.hsrw.ias.ggd;
public class Notification {
private Severity severity = Severity.Optimal;
private String type;
private SensorData cause;
public Notification(String t, SensorData d, Severity s) {
this.type = t;
this.cause = d;
this.severity = s;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public SensorData getCause() {
return cause;
}
public void setCause(SensorData cause) {
this.cause = cause;
}
public Severity getSeverity() {
return this.severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
}

View File

@@ -0,0 +1,65 @@
package eu.hsrw.ias.ggd;
import java.util.Date;
import java.util.HashMap;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {
Date now; // to display current time
// Add your task here
public void run() {
// Display current time
now = new Date(); // initialize date
System.out.println("Time is :" + now);
try {
Greenhouse greenhouse = ApiCall.FetchDataFromApi();
System.out.println(
"Final Size " +
greenhouse.getDevices().size() +
" Devices: " +
greenhouse.getDevices()
);
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
//Get the session named kseesion-rule that we defined in kmodule.xml above.
//Also by default the session returned is always stateful.
KieSession kSession = kContainer.newKieSession("ksession-rule");
FactHandle g = kSession.insert(greenhouse);
kSession.insert(g);
// FactHandle x = kSession.insert(Severity.Unknown);
// kSession.insert(x);
for (Device d : greenhouse.getDevices()) {
FactHandle f = kSession.insert(d);
kSession.insert(f);
}
//FactHandle fact1;
//fact1 = kSession.insert(outputDevices);
// System.out.println(fact1);
// kSession.insert(fact1);
kSession.fireAllRules();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,23 @@
package eu.hsrw.ias.ggd;
import HttpCall.HttpPost;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public class SecurityToken {
public static String OnCallMethod(String username, String password)
throws Exception {
//CONFIG PARAMETERS:
//BEGIN------------CONFIG PARAMETERS BELOW TO YOUR ENVIRONMENT---------------------------------------
String baseURL = "https://api.whysor.com/users/login";
String devURL = "https://api.dev.whysor.com/users/login";
final String body = String.format(
"{\"email\": \"%s\", \"password\": \"%s\", \"domain\": \"my.dev.yookr.org\"}",
username,
password
);
HttpPost httpMethodPost = new HttpPost();
return httpMethodPost.HttpCallPost(devURL, body);
}
}

View File

@@ -0,0 +1,16 @@
package eu.hsrw.ias.ggd;
import java.util.HashMap;
public class SensorMap {
private HashMap<String, Double> sensors = new HashMap<String, Double>();
public HashMap<String, Double> getSensors() {
return sensors;
}
public void setSensors(HashMap<String, Double> sensors) {
this.sensors = sensors;
}
}

View File

@@ -0,0 +1,10 @@
package eu.hsrw.ias.ggd;
public enum Severity {
Optimal,
Info,
Warning,
Error,
Critical,
Unknown,
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
<kbase name="rules" packages="rules">
<ksession name="ksession-rule"/>
</kbase>
</kmodule>

View File

@@ -0,0 +1,3 @@
groupId=com.javainuse
artifactId=drools-hello-world
version=0.0.1-SNAPSHOT

View File

@@ -0,0 +1,126 @@
import java.util.HashMap;
import java.util.Map;
import eu.hsrw.ias.ggd.SensorData
import javax.swing.JOptionPane
import HttpCall.HttpPost
import eu.hsrw.ias.ggd.Notification
import eu.hsrw.ias.ggd.Severity;
import eu.hsrw.ias.ggd.Device;
rule "CriticalBattery"
when
device: Device(sensorDatas: sensorData)
sensorData: SensorData(tag == "battery", value < 4.0) from sensorDatas
then
String greenhouse1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
final String criticalBatteryOutput = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical Battery %s in the following sensor %s \", \"battery\": %s}]}}",greenhouse1, sensorData.getValue(),sensorData.getTag(),sensorData.getValue());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",criticalBatteryOutput);
insert(new Notification("battery", sensorData, Severity.Critical));
// modify(sensorData){
// setState(Severity.Critical)
// }
end
rule "OptimalBattery"
when
device: Device(sensorDatas: sensorData)
sensorData: SensorData(tag == "battery", value > 4.0) from sensorDatas
then
String greenhouse1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
final String optimalBatteryOutput = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Optimal Battery %s in the following sensor %s \", \"battery\": %s}]}}",greenhouse1, sensorData.getValue(),sensorData.getTag(),sensorData.getValue());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",optimalBatteryOutput);
insert(new Notification("battery", sensorData, Severity.Optimal));
// modify(sensorData){
// setState(Severity.Optimal)
// }
end
// System.out.println(sensorData.getTag()+" "+sensorData.getValue());
// System.out.println(device);
/*String fixedIdG1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
// System.out.println("Tag: '"+tag+"' has low battery with value: '"+level+"'");
final String battery = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical! Low Battery %s \", \"battery\": %s}]}}", fixedIdG1,level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",battery);
System.out.println("Low Battery"+level+"in the following sensor"+tag);
*/
/*HttpPost httpPost = new HttpPost();
final String finalOutput;
boolean critical = false;
HashMap<String,Double> test = new HashMap<>();
if (tag.equals("fd694041-581e-4c2c-9810-505e62b762e6")){ // This matches 70B3D570500042D7
if (level < 7.2 && k.equals("battery") ) {
JOptionPane.showMessageDialog(null,"Low Battery : "+level+"! Please swap the battery soon of the following sensor:"+tag,"Low Battery Level",JOptionPane.INFORMATION_MESSAGE);
final String battery = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical! Low Battery %s \", \"battery\": %s}]}}", fixedIdG1,level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",battery);
System.out.println("Low Battery"+level+"in the following sensor"+tag);
critical = true;
test.put("battery",level);
}
if (level > 80 && k.equals("temperature") ) {
JOptionPane.showMessageDialog(null,"High Temperature : "+level+" in the following sensor: "+tag+"in the following device id: "+id,"Temperature",JOptionPane.INFORMATION_MESSAGE);
final String temperature = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical!High Temperature %s \", \"temperature\": %s}]}}", fixedIdG1,level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",temperature);
System.out.println("High Temp");
critical = true;
}
if (level > 14.5 && k.equals("precipitation") ) {
JOptionPane.showMessageDialog(null,"High water level : "+level+" in the following sensor"+tag,"Precipitation",JOptionPane.INFORMATION_MESSAGE);
final String precipitation = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"High water level %s\", \"precipitation\": %s}]}}", fixedIdG1, level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",precipitation);
System.out.println("High water level"+level +" in the following sensor:"+tag);
critical = true;
}
if (level < 22 && k.equals("soilTemperature") ) {
JOptionPane.showMessageDialog(null,"Low soil temperature : "+level+" in the following sensor: "+tag+"in the following device id: "+id,"soil Temperature",JOptionPane.INFORMATION_MESSAGE);
final String soilTemperature = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Low soil temperature %s in the following sensor: %s \", \"soilTemperature\": %s}]}}", fixedIdG1,level, tag,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",soilTemperature);
System.out.println("Low soil Temperature"+level+" in the following sensor "+tag);
critical = true;
test.put("soilTemperature",level);
}
if (level <= 30 && k.equals("soilMoisture") ) {
JOptionPane.showMessageDialog(null,"Be Careful the soil is dry : "+level+" in the following sensor :"+tag +"in the device:"+id,"Soil Moisture",JOptionPane.INFORMATION_MESSAGE);
final String soilMoisture = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Be Careful the soil sensor %s is dry: %s \", \"soilMoisture\": %s}]}}", fixedIdG1,tag,level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",soilMoisture);
System.out.println("Soil is dry"+level+" in the following sensor"+tag);
critical = true;
}
if (level <= 0.57 && level >= 0.11 && k.equals("soilConductivity") ) {
JOptionPane.showMessageDialog(null,"Optimal EC levels in the soil : "+level+" in the following sensor"+tag,"Soil Conductivity",JOptionPane.INFORMATION_MESSAGE);
final String soilConductivity = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Optimal EC levels in the soil %s\", \"soilConductivity\": %s}]}}", fixedIdG1, level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",soilConductivity);
System.out.println("Optimal EC levels in the soil"+level +" in the following sensor:"+tag);
critical = true;
}
if (level > 20 && k.equals("dielectricPermittivity") ) {
JOptionPane.showMessageDialog(null,"High dielectricPermittivity : "+level+" in the following sensor"+tag,"dielectricPermittivity",JOptionPane.INFORMATION_MESSAGE);
final String dielectricPermittivity = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"High dielectricPermittivity %s\", \"dielectricPermittivity\": %s}]}}", fixedIdG1, level,level);
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",dielectricPermittivity);
System.out.println("High dielectricPermittivity"+level +" in the following sensor:"+tag);
critical = true;
}
// if(critical == true){
// finalOutput
// }
finalOutput = String.format("{\"id\":\"70B3D570500042D7-status\",\"data\":{\"measured\":[{ \"status\": \"The status of the device 1 is critical\",}]}}");
System.out.println(finalOutput);
}*/

View File

@@ -0,0 +1,24 @@
import java.util.HashMap;
import java.util.Map;
import eu.hsrw.ias.ggd.SensorData
import javax.swing.JOptionPane
import HttpCall.HttpPost
import eu.hsrw.ias.ggd.Notification
import eu.hsrw.ias.ggd.Severity;
import eu.hsrw.ias.ggd.Device;
rule "CriticalPrecipitation"
when
device: Device(sensorDatas: sensorData)
sensorData: SensorData(tag == "precipitation", value > 15.5) from sensorDatas
then
String greenhouse1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
final String criticalPrecipitationOutput = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical Precipitation %s in the following sensor %s \", \"precipitation\": %s}]}}",greenhouse1, sensorData.getValue(),sensorData.getTag(),sensorData.getValue());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",criticalPrecipitationOutput);
insert(new Notification("precipitation", sensorData, Severity.Warning));
// modify(sensorData){
// setState(Severity.Critical)
// }
end

View File

@@ -0,0 +1,7 @@
package rules;
dialect "mvel"
rule "CriticalSoilConductivity"
when
then
end

View File

@@ -0,0 +1,7 @@
package rules;
dialect "mvel"
rule "CriticalSoilTemperature"
when
then
end

View File

@@ -0,0 +1,47 @@
import java.util.HashMap;
import java.util.Map;
import eu.hsrw.ias.ggd.SensorData
import javax.swing.JOptionPane
import HttpCall.HttpPost
import eu.hsrw.ias.ggd.Notification
import eu.hsrw.ias.ggd.Severity;
import eu.hsrw.ias.ggd.Device;
rule "CriticalTemperature"
when
device: Device(sensorDatas: sensorData)
sensorData: SensorData(tag == "temperature", value < 10.0 || value > 30.0) from sensorDatas
then
String greenhouse1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
final String criticalTemperatureOutput = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical Temperature %s in the following device %s \", \"temperature\": %s}]}}",greenhouse1, sensorData.getValue(),sensorData.getTag(),sensorData.getValue());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",criticalTemperatureOutput);
final String deviceCritical = String.format("{\"id\":\"%s-status\",\"data\":{\"measured\":[{ \"criticalStatus\": \"The status of %s device is critical\"}]}}",device.IdMapper(device.getId()),device.getId());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",deviceCritical);
System.out.println(deviceCritical);
insert(new Notification("temperature", sensorData, Severity.Critical));
// modify(device){
// setState(Severity.Critical)
// }
end
rule "OptimalTemperature"
when
device: Device(sensorDatas: sensorData)
sensorData: SensorData(tag == "temperature", value > 10.0 && value < 30.0) from sensorDatas
then
String greenhouse1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
final String optimalTemperatureOutput = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Optimal Temperature %s in the following device %s \", \"temperature\": %s}]}}",greenhouse1, sensorData.getValue(),sensorData.getTag(),sensorData.getValue());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",optimalTemperatureOutput);
insert(new Notification("temperature", sensorData, Severity.Optimal));
System.out.println("Optimal");
// modify(sensorData){
// setState(Severity.Optimal)
// }
end

View File

@@ -0,0 +1,20 @@
import java.util.HashMap;
import java.util.Map;
import eu.hsrw.ias.ggd.SensorData
import javax.swing.JOptionPane
import HttpCall.HttpPost
import eu.hsrw.ias.ggd.Notification
import eu.hsrw.ias.ggd.Severity;
import eu.hsrw.ias.ggd.Device;
rule "DielectricPermittivity"
when
device: Device(sensorDatas: sensorData)
sensorData: SensorData(tag == "dielectricPermittivity", value > 20.0) from sensorDatas
then
String greenhouse1="8bdbe6ae-eafb-4e99-bb01-db8784dd9633";
HttpPost httpPost = new HttpPost();
final String dielectricPermittivityOutput = String.format("{\"id\":\"%s\",\"data\":{\"measured\":[{ \"status\": \"Critical dielectricPermittivity %s in the following sensor %s \", \"dielectricPermittivityOutput\": %s}]}}",greenhouse1, sensorData.getValue(),sensorData.getTag(),sensorData.getValue());
httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",dielectricPermittivityOutput);
insert(new Notification("dielectricPermittivity", sensorData, Severity.Warning));
end

View File

@@ -0,0 +1,31 @@
import eu.hsrw.ias.ggd.Device;
import eu.hsrw.ias.ggd.Severity;
import eu.hsrw.ias.ggd.SensorData;
rule "Sensor of device gone critical"
when
sensorData: SensorData(state == Severity.Critical)
device: Device(sensorData contains(sensorData))
then
modify(device){
setState(Severity.Critical)
}
System.out.println("Device: \n" +
"\tID: '" + device.getId() + "'" +
"\tState: '" + device.getState().toString() + "'"
);
// Do something the info that a device is gone critical
end
rule "Sensor of device gone optimal"
when
sensorData: SensorData(state == Severity.Optimal)
device: Device(sensorData contains(sensorData))
then
modify(device){
setState(Severity.Optimal)
}
// Device is gone optimal
end

View File

@@ -0,0 +1,25 @@
import eu.hsrw.ias.ggd.Greenhouse;
import eu.hsrw.ias.ggd.Device;
import eu.hsrw.ias.ggd.Severity;
rule "Device of greenhouse gone critical"
when
device: Device(state == Severity.Critical)
greenhouse: Greenhouse(devices contains(device))
//greenhouse: Greenhouse(devices contains(Device(state == Severity.Critical)))
then
modify(greenhouse){
setState(Severity.Critical)
}
System.out.println("Greenhouse: '" + greenhouse.getId() + "' is '" + greenhouse.getState().toString() + "'");
end
rule "Device of greenhouse has gone optimal"
when
device: Device(state == Severity.Optimal)
greenhouse: Greenhouse(devices contains(device))
then
modify(greenhouse){
setState(Severity.Optimal)
}
end

View File

@@ -0,0 +1,15 @@
import eu.hsrw.ias.ggd.Notification;
import eu.hsrw.ias.ggd.Severity
import HttpCall.HttpPost;
import eu.hsrw.ias.ggd.Device;
rule "Green House Optimal"
when
warning: Notification(severity == Severity.Optimal)
then
HttpPost httpPost = new HttpPost();
final String optimalGreenhouse = String.format("{\"id\":\"germes-greenhouse-status\",\"data\":{\"measured\":[{ \"status\": \"The status of the greenhouse is optimal\"}]}}");
// httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",optimalGreenhouse);
System.out.println("Green House optimal, because of: '"+warning.getType()+"'");
end

View File

@@ -0,0 +1,15 @@
import eu.hsrw.ias.ggd.Notification;
import eu.hsrw.ias.ggd.Severity
import HttpCall.HttpPost;
//rule "Green House Critical"
//when
// warning: Notification(severity > Severity.Warning)
//then
// HttpPost httpPost = new HttpPost();
// final String criticalGreenhouse = String.format("{\"id\":\"germes-greenhouse-status\",\"data\":{\"measured\":[{ \"status\": \"The status of the greenhouse is critical\"}]}}");
// httpPost.HttpCallPost("http://connector.dev.whysor.com/default/insert?access_token=3hosOhAeh4k0XmcuAMQGfYldvTuQDvtAj2PJJ4irKPBefD5Ijij6gnUkLtVLd4fW",criticalGreenhouse);
// System.out.println(criticalGreenhouse);
// System.out.println("Green House critical, because of: '"+warning.getType()+"'");
//
//end