CHANGE: REDEFINING THE STRUCTURE

FIX: ApiCall.java
ADD: ISIS IC Server REQ
ADD: RULES
master
Kevin Shehu 2021-08-31 12:02:56 +02:00
parent a07efa82d3
commit cceac4d65d
20 changed files with 337 additions and 203 deletions

View File

@ -3,7 +3,7 @@
The service of decision support system is inferring knowledge from the available data of the greenhouse, the user input, and historical data what a user/the gardener should do & which action a gardener should execute to be successful with the growing process of the plants.
These actions are called goals.
The list of inferred active goals is offered to other services of the system.
The approach of the DSS is based on three MainExe concepts:
The approach of the DSS is based on three eu.hsrw.ias.ggd.MainExe concepts:
**Fact knowledge (Knowledgebase)**

View File

@ -1,64 +0,0 @@
import Credentials.UserCredentials;
import Files.WriteFile;
import JSON_Unpack.ReadSensors4Partner;
import Knowledgebase.SensorReadings;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class ApiCall {
private static String token = "0";
private static String oldId = "1";
public static String FetchDataFromApi(String extension) 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();
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();
SensorReadings sensorReadings = new SensorReadings();
String outputValue = (readSensors4Partner.FetchSensor4Box("Germes",token));
System.out.println(outputValue);
String outputValueFixed=outputValue.replace("[[","[") +outputValue.replace("[{","{")+outputValue.replace("}]","}")+ outputValue.replace("]]","]");
System.out.println(outputValueFixed);
JSONArray jsonArray = new JSONArray(outputValueFixed);
System.out.println(jsonArray.length());
for(int j=0; j<jsonArray.length(); j++) {
JSONObject jsonobject = jsonArray.getJSONObject(j);
String sensorTag = jsonobject.getString("sensortag");
int value = jsonobject.getInt("value");
System.out.println(sensorTag+":"+value);
sensorReadings.setSensorTag(sensorTag);
sensorReadings.setValue(value);
}
return null;
}
}

View File

@ -4,7 +4,7 @@ public class UserCredentials {
private String username = "kevin.shehu@hochschule-rhein-waal.de";
private String password = "DK7SxFkGJgnLhnU3";
private String baseURL = "https://api.whysor.com/";
private static String homeRoot = "D:\\WORK\\GGD\\src\\main\\java\\Data\\";
private static String homeRoot = "/Users/ksh/Documents/Work/GGD/src/main/java/Data/";

View File

@ -1 +1 @@
CyGrh8jKqXXZCBgLzG6gnI6lMWGdzCjGW3LP9sPrH6FEu2M19UcOBF9PZaTJH963
2YiUD7Tx2i8XO8q38cs5FsZMjzKbk4SUA5uJzUq68uaVXrps6z94Ve0R6SjgWeXw

View File

@ -32,7 +32,7 @@
// }
// }
//
//// @CommandLine.Parameters(paramLabel = "D:\\WORK\\GGD\\src\\MainExe\\java\\Data", description = "json file")
//// @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;
//

View File

@ -61,7 +61,7 @@ public class BoxCall4Partner {
}
if(loopTerminator == arrayOfCompany.length ){
System.out.println("Entered ");
System.out.println("Processing..... ");
return listOfCompanyOutputs;
}

View File

@ -12,17 +12,17 @@ import java.util.ArrayList;
///url/sensors/id/read
public class ReadSensors4Partner {
public String FetchSensor4Box(String companyName, String token) throws Exception {
public ArrayList<String> FetchSensor4Box(String companyName, String token) throws Exception {
switch (companyName) {
case "Germes":
return String.valueOf(SensorRead("Germes", token));
return SensorRead("Germes", token);
case "Heufs":
return String.valueOf(SensorRead("Heufs", token));
return SensorRead("Heufs", token);
case "Jacobs":
return String.valueOf(SensorRead("Jacobs", token));
return SensorRead("Jacobs", token);
case "Nica":
return String.valueOf(SensorRead("Nica", token));
return SensorRead("Nica", token);
}
return null;
}
@ -39,23 +39,27 @@ public class ReadSensors4Partner {
String outputBox = boxCall4Partner.FetchBox(cName,token);
String outputBoxFixed=outputBox.replace("[[","[") + outputBox.replace("]]","]");// To convert in Jsonarray we need to remove the array list brackets
JSONArray jsonArray = new JSONArray(outputBoxFixed);
System.out.println("The working array:"+jsonArray);
System.out.println("FINAL WORKING ARRAY:"+jsonArray);
ArrayList<String> list=new ArrayList<String>();
int loopTerminator = 0;
char par = '"';
for(int j=0; j<jsonArray.length(); j++){
JSONObject jsonobject = jsonArray.getJSONObject(j);
String jsonID = jsonobject.getString("id");
String jsonTag = jsonobject.getString("tag");
String finalTag = ","+par+"sensorTag"+par+":"+jsonTag+"}]";
String sensorOutput = httpCall.HttpGet(baseURL + "sensors/" + jsonID + "/read" + "?access_token=" + token, token);
String sensorTag= par+"sensortag"+par+":"+jsonTag+"}]";
String makingList=sensorOutput.replace("}]","") ;
list.add(makingList+","+sensorTag); // This modification of the list is done for the purpse of converting this list to a jsonarray.
String modification = sensorOutput.replace("}]","");
String finalSensorOutput = modification+finalTag;
list.add(finalSensorOutput);
writingIntoFile.WriteFile(homeRoot + jsonID + ".json", sensorOutput + jsonTag);
loopTerminator++;
if(loopTerminator == jsonArray.length()){
// System.out.println("L+++++++++++++"+list);
return list;
}
}

View File

@ -1,37 +1,53 @@
package Knowledgebase;
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;
public class DroolsTest {
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");
Product product = new Product();
product.setType("gold");
System.out.println(product.getDiscount());
FactHandle fact1;
fact1 = kSession.insert(product);
System.out.println(fact1);
kSession.fireAllRules();
System.out.println("The discount for the jewellery product "
+ product.getType() + " is " + product.getDiscount());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
//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,17 @@
package Knowledgebase;
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

@ -1,22 +0,0 @@
package Knowledgebase;
public class SensorReadings {
private String sensorTag;
private double value;
public String getSensorTag() {
return sensorTag;
}
public void setSensorTag(String sensorTag) {
this.sensorTag = sensorTag;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}

View File

@ -1,46 +0,0 @@
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
// 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);
String outputDevices = null;
String devicesExtension = "devices";
String sensorExtension = "sensors"; //read and readMultiple
try {
outputDevices = ApiCall.FetchDataFromApi(devicesExtension);
// outputDevices = ApiCall.FetchDataFromApi(sensorExtension);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Output :" + outputDevices); // Display current output
}
}

View File

@ -0,0 +1,98 @@
package eu.hsrw.ias.ggd;
import Credentials.UserCredentials;
import Files.WriteFile;
import JSON_Unpack.ReadSensors4Partner;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class ApiCall {
private static String token = "0";
private static String oldId = "1";
public static HashMap<String, Double> 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();
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));
String workingArray = String.valueOf(outputValue).replace("[{","{").replace("}]","}");
JSONArray jsonArray = new JSONArray(workingArray);
HashMap<String, Double> sensors = new HashMap<String, Double>();
for(int j = 0; j<jsonArray.length(); j++) {
JSONObject jsonobject = jsonArray.getJSONObject(j);
double value = jsonobject.getDouble("value");
String sensorTag = jsonobject.getString("sensorTag");
// System.out.println(value);
// System.out.println(sensorTag);
// sensorsMap.setSensors(sensorTag,value);
sensors.put(sensorTag,value);
}
// ArrayList<String> listOfCompanies = new ArrayList<>();
// String germesOutput = FetchData("Germes",token);
// listOfCompanies.add(FetchData(c1,token));
// listOfCompanies.add(FetchData("Heufs",token));
JOptionPane.showMessageDialog(null,sensors,"Germes sensors"+now,JOptionPane.INFORMATION_MESSAGE);
return sensors;
}
// public static void FetchData(String companyName, String token){
// ReadSensors4Partner readSensors4Partner = new ReadSensors4Partner();
// ArrayList<String> outputValue = null;
// try {
// outputValue = (readSensors4Partner.FetchSensor4Box(companyName,token));
// } catch (Exception e) {
// e.printStackTrace();
// }
// String workingArray = String.valueOf(outputValue).replace("[{","{").replace("}]","}");
// JSONArray jsonArray = new JSONArray(workingArray);
//
// HashMap<String, Double> sensors = new HashMap<String, Double>();
// for(int j = 0; j<jsonArray.length(); j++) {
// JSONObject jsonobject = jsonArray.getJSONObject(j);
// double value = jsonobject.getDouble("value");
// String sensorTag = jsonobject.getString("sensorTag");
//// System.out.println(value);
//// System.out.println(sensorTag);
//// sensorsMap.setSensors(sensorTag,value);
// sensors.put(sensorTag,value);
//
// }
//
//
// }
}

View File

@ -0,0 +1,25 @@
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("Climate", "humidity");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,13 +1,13 @@
package eu.hsrw.ias.ggd;
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
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 1 min
time.schedule(scheduledTask, 0, 1000 * 30 * 1 ); // Create Repetitively task for every 2 min
}
}

View File

@ -0,0 +1,53 @@
package eu.hsrw.ias.ggd;
import eu.hsrw.ias.ggd.ApiCall;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import java.util.HashMap;
import java.util.TimerTask;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {
Date now; // to display current time
HashMap<String, Double> outputDevices ;
// Add your task here
public void run() {
// Display current time
now = new Date(); // initialize date
System.out.println("Time is :" + now);
try {
outputDevices = ApiCall.FetchDataFromApi();
System.out.println("Final Size"+outputDevices.size()+outputDevices);
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 fact1;
fact1 = kSession.insert(outputDevices);
System.out.println(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

@ -1,3 +1,5 @@
package eu.hsrw.ias.ggd;
import HttpCall.HttpPost;
import java.util.concurrent.ExecutionException;
@ -12,9 +14,6 @@ public class SecurityToken {
HttpPost httpMethodPost = new HttpPost();
return httpMethodPost.HttpCallPost(baseURL, body);
}

View File

@ -0,0 +1,18 @@
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import eu.hsrw.ias.ggd.ScheduledTask
import javax.swing.JOptionPane;
rule "Low Battery Level"
when
$map : Map (this["battery"]<5.5)
then
System.out.println("Low Battery : "+$map.get("battery")+"! Please swap the battery soon");
JOptionPane.showMessageDialog(null,"Low Battery : "+$map.get("battery")+"! Please swap the battery soon","Low Battery Level",JOptionPane.INFORMATION_MESSAGE);
end

View File

@ -0,0 +1,21 @@
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import eu.hsrw.ias.ggd.ScheduledTask;
import javax.swing.JOptionPane;
rule "Optimal EC levels in the soil"
when
$map : Map (this["soilConductivity"]<0.57 && this["soilConductivity"]>0.11)
then
System.out.println("Optimal EC levels in the soil : "+$map.get("soilConductivity"));
JOptionPane.showMessageDialog(null,"Optimal EC levels in the soil : "+$map.get("soilConductivity"),"Soil Conductivity",JOptionPane.INFORMATION_MESSAGE);
end

View File

@ -0,0 +1,29 @@
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import eu.hsrw.ias.ggd.ScheduledTask;
import javax.swing.JOptionPane;
rule "Dry Soil Moisture"
when
$map : Map (this["soilMoisture"]<40)
then
System.out.println("It is recommended to have a Soil Moisture higher than : "+$map.get("soilMoisture"));
JOptionPane.showMessageDialog(null,"It is recommended to have a Soil Moisture higher than : "+$map.get("soilMoisture"),"Dry Soil Moisture",JOptionPane.INFORMATION_MESSAGE);
end
rule "Wet Soil Mositure"
when
$map : Map (this["soilMoisture"]>70)
then
System.out.println("Be careful the soil is extremly wet :"+$map.get("soilMoisture")+ "please dont apply water");
JOptionPane.showMessageDialog(null,"Be careful the soil is extremly wet :"+$map.get("soilMoisture")+ "please dont apply water","Wet Soil Moisture",JOptionPane.INFORMATION_MESSAGE);
end

View File

@ -1,14 +0,0 @@
import Knowledgebase.Product
rule "Offer for Diamond"
when
productObject: Product(type=="diamond")
then
productObject.setDiscount(15);
end
rule "Offer for Gold"
when
productObject: Product(type=="gold")
then
productObject.setDiscount(10);
end