http = urllib3.PoolManager()
headers = urllib3.util.make_headers(user_agent=None)
headers['Authorization'] = 'Bearer ' + config.oauth_credentials_for_device
headers['Content-Type'] = 'application/json;charset=utf-8'
url='https://iotmms' + config.hcp_account_id + config.hcp_landscape_host + '/com.sap.iotservices.mms/v1/api/http/data/'+ str(config.device_id)
urllib3.disable_warnings()
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
print (temperature, humidity)
time = datetime.datetime.now().time()
date = datetime.datetime.now().date()
body= '{"mode":"async", "messageType":"' + str(config.message_type_id_TH) + '", "messages":[{"Date":'+ ' "' + str(date) + '"'+ ',"Time":'+ ' "' + str(time) + '"'+ ',"Temperature":'+ ' "' + str(temperature) + '"'+ ',"Humidity":'+ ' "' + str(humidity) + '" }]}'
r = http.urlopen('POST', url, body=body, headers=headers)
print(body)
print(r.data)
private Double getTempfromDevice(String deviceid) {
InitialContext ctx = null;
DataSource ds = null;
Connection con = null;
Double result = null;
try {
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/default");
con = ds.getConnection();
PreparedStatement query = con.prepareStatement(
"SELECT TOP 1 \"C_TEMPERATURE\" FROM \"SYSTEM\".\"T_TH_IOTMESSAGES\" WHERE \"G_DEVICE\" = '"+deviceid+"' ORDER BY \"G_CREATED\" desc");
ResultSet rs = query.executeQuery();
while (rs.next()) {
result = rs.getDouble(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public Boolean checkTemp(Double temp) throws ClientProtocolException, IOException {
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
HttpPost httpPost = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
httpClient = getHTTPClient();
String rulesRuntimeUrl = "https://bpmrulesruntimebpm-s000xxxxxtrial.hanatrial.ondemand.com/";
String xsrfTokenUrl = rulesRuntimeUrl + "rules-service/v1/rules/xsrf-token";
String invokeUrl = rulesRuntimeUrl
+ "rules-service/v1/rules/invoke?rule_service_name=TemperatureHumidityCheck::TExceededService";
httpPost = new HttpPost(invokeUrl);
httpPost.addHeader("Content-type", "application/json");
String xsrfToken = getXSRFToken(xsrfTokenUrl, httpClient, httpContext);
if (xsrfToken != null) {
httpPost.addHeader("X-CSRF-Token", xsrfToken);
}
// replace value of authorizationHeader with base64 encoded value of
// “<user-name>:<password>”
String authorizationHeader = "<base64 encoded value of <user-name>:<password>>";
httpPost.addHeader("Authorization", "Basic " + authorizationHeader);
// construct input data to the rules service
String fact = "{ \"__type__\":\"measures\",\"temperature\":" + temp + ",\"humidity\":" + 50 + "}";
StringEntity stringEntity = new StringEntity(fact);
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost, httpContext);
// process your response here
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
InputStream inputStream = response.getEntity().getContent();
byte[] data = new byte[1024];
int length = 0;
while ((length = inputStream.read(data)) > 0) {
bytes.write(data, 0, length);
}
String respBody = new String(bytes.toByteArray(), "UTF-8");
// The respBody is a JSON and parse is to get discount
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonObject = objectMapper.readValue(respBody, JsonNode.class);
return jsonObject.get("exceeded").asBoolean();
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
/**
* Gets the xsrf token for business rules/workflow
*
* @param requestURL
* @param client
* @param httpContext
* @return
* @throws ClientProtocolException
* @throws IOException
*/
private String getXSRFToken(String requestURL, CloseableHttpClient client, HttpContext httpContext)
throws ClientProtocolException, IOException {
HttpGet httpGet = null;
CloseableHttpResponse response = null;
String xsrfToken = null;
String authorizationHeader = null;
try {
httpGet = new HttpGet(requestURL);
// replace value of authorizationHeader with base64 encoded value of
// “<user-name>:<password>”
authorizationHeader = "<base64 encoded value of <user-name>:<password>>";
httpGet.addHeader("Authorization", "Basic " + authorizationHeader);
httpGet.addHeader("X-CSRF-Token", "Fetch");
response = client.execute(httpGet, httpContext);
// Fetch the token from response and return
Header xsrfTokenheader = response.getFirstHeader("X-CSRF-Token");
if (xsrfTokenheader != null) {
xsrfToken = xsrfTokenheader.getValue();
}
} finally {
if (httpGet != null) {
httpGet.releaseConnection();
}
if (response != null) {
response.close();
}
}
return xsrfToken;
}
/**
* Checks whether the temp alert message needs to be triggered by reading
* the business rules
*
* @param temp
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String triggerTempAlertProcess(String devicename, Double temp) throws ClientProtocolException, IOException {
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
HttpPost httpPost = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
httpClient = getHTTPClient();
String rulesRuntimeUrl = "https://bpmworkflowruntimewfs-s000xxxxtrial.hanatrial.ondemand.com/";
String xsrfTokenUrl = rulesRuntimeUrl + "workflow-service/rest/v1/xsrf-token";
String invokeUrl = rulesRuntimeUrl + "workflow-service/rest/v1/workflow-instances";
httpPost = new HttpPost(invokeUrl);
httpPost.addHeader("Content-type", "application/json");
String xsrfToken = getXSRFToken(xsrfTokenUrl, httpClient, httpContext);
if (xsrfToken != null) {
httpPost.addHeader("X-CSRF-Token", xsrfToken);
}
// replace value of authorizationHeader with base64 encoded value of
// “<user-name>:<password>”
String authorizationHeader = "<base64 encoded value of <user-name>:<password>>";
httpPost.addHeader("Authorization", "Basic " + authorizationHeader);
// construct input data to the workflow service to create instance
String fact = "{ \"definitionId\":\"temperaturealert\",\"context\":{ \"devicename\":\"" + devicename
+ "\",\"text\":\"Temperature has risen above the set limit. Please check the device\"}}";
StringEntity stringEntity = new StringEntity(fact);
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost, httpContext);
// process your response here
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
InputStream inputStream = response.getEntity().getContent();
byte[] data = new byte[1024];
int length = 0;
while ((length = inputStream.read(data)) > 0) {
bytes.write(data, 0, length);
}
String respBody = new String(bytes.toByteArray(), "UTF-8");
// The respBody is a JSON and parse is to get discount
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonObject = objectMapper.readValue(respBody, JsonNode.class);
return jsonObject.get("id").asText();
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
/**
* Reads device name for the device id using Remote Device management API
*
* @param deviceid
* @return
*/
private String getDevicename(String deviceid) throws ClientProtocolException, IOException {
String devicename = null;
HttpGet httpGet = null;
String authorizationHeader = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
try {
httpClient = getHTTPClient();
String RDMSUrl = "https://iotrdmsiotservices-s00xxxxxxtrial.hanatrial.ondemand.com/com.sap.iotservices.dms/v2/api";
String invokeUrl = RDMSUrl + "/devices/" + deviceID;
httpGet = new HttpGet(invokeUrl);
// replace value of authorizationHeader with base64 encoded value of
// “<user-name>:<password>”
authorizationHeader = "<base64 encoded value of <user-name>:<password>>"; httpGet.addHeader("Authorization", "Basic " + authorizationHeader);
httpGet.addHeader("X-CSRF-Token", "Fetch");
response = httpClient.execute(httpGet, httpContext);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
InputStream inputStream = response.getEntity().getContent();
byte[] data = new byte[1024];
int length = 0;
while ((length = inputStream.read(data)) > 0) {
bytes.write(data, 0, length);
}
String respBody = new String(bytes.toByteArray(), "UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonObject = objectMapper.readValue(respBody, JsonNode.class);
return jsonObject.get("name").asText();
} finally {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
Double temp = getTempfromDevice(deviceID);
if (checkTemp(temp)) {
// 1. Get device name from where the alert has come
String devicename = getDevicename(deviceID);
// 2.trigger alert process
String instanceID = triggerTempAlertProcess(devicename, temp);
response.getWriter().println("Temperature alert process triggered with instance " + instanceID);
} else {
response.getWriter().println("Temperature under control " + getTempfromDevice(deviceID));
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
11 | |
10 | |
7 | |
6 | |
4 | |
4 | |
3 | |
3 | |
3 | |
3 |