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()
GPIO.output(lightPin,False)
GPIO.output(buzzPin,GPIO.LOW)
try:
while True:
if GPIO.input(buttonPin) == False:
#Get thickness from user. This value will come from sensor in live scenario
thickness = input("Enter thickness:")
time = datetime.datetime.now().time()
date = datetime.datetime.now().date()
body= '{"mode":"async", "messageType":"' + str(config.message_type_id_THICK) + '", "messages":[{"Date":'+ ' "' + str(date) + '"'+ ',"Time":'+ ' "' + str(time) + '"'+ ',"Thickness":'+ ''+str(thickness)+' }]}'
r = http.urlopen('POST', url, body=body, headers=headers)
#wait for 5 seconds before polling the data from MMS.
sleep(5)
message = http.urlopen('GET', url, headers=headers)
#if the message is not empty - [], then light up the LED and switch the buzzer on
if len(message.data) > 2:
GPIO.output(buzzPin,GPIO.HIGH)
GPIO.output(lightPin,True)
except KeyboardInterrupt:
GPIO.output(lightPin,False)
GPIO.cleanup()
/**
* read data from device
*
* @return
*/
private String getThicknessfromDevice(String deviceid) {
InitialContext ctx = null;
DataSource ds = null;
Connection con = null;
String 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_THICKNESS\" FROM \"SYSTEM\".\"T_THICK_IOTMESSAGES\" WHERE \"G_DEVICE\" = '"+deviceid+"' ORDER BY \"G_CREATED\" desc");
ResultSet rs = query.executeQuery();
while (rs.next()) {
result = rs.getString(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* Check thickness against rules
* @param materialtype
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String checkThickness(String thickness)
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-s000xxxxtrial.hanatrial.ondemand.com/";
String xsrfTokenUrl = rulesRuntimeUrl + "rules-service/v1/rules/xsrf-token";
String invokeUrl = rulesRuntimeUrl
+ "rules-service/v1/rules/invoke?rule_service_name=Thickness::ThicknessRulesService";
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__\":\"Input\",\"Thickness\":\"" + thickness + "\"}";
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
//return respBody;
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonObject = objectMapper.readValue(respBody, JsonNode.class);
String action = jsonObject.get("Action").asText();
if (action.equalsIgnoreCase("Stop")) {
//Push raise alarm message to the device
return pushMessageToDevice(thickness);
}else{
return "No action required";
}
} 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;
}
/**
*
* @param thickness
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String pushMessageToDevice(String thickness) 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 iotUrl = "https://iotmmss000xxxxtrial.hanatrial.ondemand.com/com.sap.iotservices.mms/";
String pushUrl = iotUrl
+ "v1/api/http/push/"+deviceID;
httpPost = new HttpPost(pushUrl);
httpPost.addHeader("Content-type", "application/json");
// 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 = "{ \"method\": \"http\",\"Sender\": \"IoTApplication\",\"messageType\": \""+messageID+"\",\"messages\":[{\"Date\":"+"12122018"+",\"Time\":\""+111111+"\",\"Thickness\":"+thickness+" }]}";
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
return respBody;
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
response.getWriter().print(checkThickness(getThicknessfromDevice(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 |
---|---|
5 | |
4 | |
4 | |
4 | |
4 | |
3 | |
3 | |
3 | |
3 | |
2 |