A Simple Door Monitoring System with HANA XS and Raspberry Pi

Standard
Intro

I have built a simple door sensor with SAP HANA and Raspberry Pi to monitor the door-opening events. The wireless door sensor is a magnetic gap sensor that will send the RF 433 Mhz signal to the receiver when someone open the door. The Raspberry Pi with the receiver within the range listens for the incoming signal from the sensor. Once the signal is detected, the Raspberry Pi will send the ODATA http post request  to the HANA server. You can monitor the events status from the web app (backend).

If you never heard of Raspberry Pi, you may refer to its website at http://www.raspberrypi.org/ . Building the receiver will not be covered in this blog. Please refer to this blog to build it: Adding 433 to your Raspberry Pi | Ninja Blocks

rpi.jpg

Slide1.JPG

HTTP POST Command: Curl

On the Raspberry Pi, there is a command line tool in Linux to post the http request: curl with the JSON data: body.json.

if (mySwitch.getReceivedValue() == 13981149 ) {

system(“curl -H ‘Content-Type: application/json’ –data @/home/pi/433Utils/RPi_utils/body.json http://hana2.vm.cld.sr:8000/rpi/sensor/service/RPISensor.xsodata/RpiSensor

}

The body.json contains the current timestamp, date and STATUS = Open. The timestamp and date will be auto-populated by the insert procedure on the HANA XS side.

{“STIMESTAMP”:”\/Date(0000000000000)\/”,”SDATE”:”\/Date(0000000000000)\/”,”STATUS”:”Open”}

To run the receiver, just type sudo ./RFSniffer on the Raspberry Pi command prompt. This command listens to the incoming signal from the sensor and sends the http post ODATA request to HANA XS. On the HANA XS side, the insert procedure will update the HANA table.

sensor.jpg

Project Structure: Key Components

The structure and explanation is pretty much the same as in my earlier blog here: http://scn.sap.com/community/developer-center/hana/blog/2014/07/07/real-time-gps-tracker-using-sap-hana-xs-sapui5-cordova-geolocation-plugin-and-odata

aa.jpg

Let’s focus here on the key components:

  • The RpiSensor table to store the status of the door events:b.jpg
  • The  XSODATA:
    xsodata.jpg
  • The InsertRowRPISensor procedure:
    c.jpg
  • And also the web app backend SAPUI5 to view the information:
    d.jpg

A complete source code can be found on GitHub: ferrygun/HANADoorSensor · GitHub

Summary

You could make an internet of things by combining the power of SAP HANA and the micro-computer/controller like the Raspberry Pi/Arduino with other sensors (e.g,. GPS, temperature/humidity, contact sensors, etc) and create a dashboard to present the status of the sensors.

Thanks for reading my blog. I hope you enjoy it.

Advertisements

Real Time GPS Tracker using SAP HANA XS, SAPUI5, Cordova Geolocation Plugin and OData

Standard

Hello to all,

 

I would like to share how to build a simple Android app GPS tracker powered by SAP HANA using XS, SAPUI5 with Cordova Geolocation Plugin and ODATA. The idea is to send the latitude and longitude position from the Android phone to the SAP HANA. The backend web application will show  the current location in Google Map.

 

The app screenshots  will look like this:

 

  • Android Client
    10.jpg

 

  • Backend Web App
    5.jpg

 

Required Components

  • Android phone with GPS and 3G/4G enabled. I am using Samsung Galaxy S4 for the demo.
  • SAP HANA access. I am using the 30-days HANA version. Refer to http://scn.sap.com/docs/DOC-28191
  • SAPUI5 with Cordova Geolocation plugin.

 

6.jpg

 

The Android Client

 

This client will send the current position via OData service to the SAP HANA.

 

  • Create SAPUI5 index.html.
    In the onSuccess function, we’ll get the latitude & longitude position and pass these values to the oEntry array and create the OData request (Post method).

    1. function onSuccess(position) {
    2. var element = document.getElementById(‘geolocation’);
    3. element.innerHTML = ‘Latitude: ‘ + position.coords.latitude + ‘<br />’ +
    4. ‘Longitude: ‘ + position.coords.longitude + ‘<br />’ +
    5. ‘<hr />’ + element.innerHTML;
    6. jQuery.sap.require(“sap.ui.model.odata.datajs”);
    7. var sUrl = “hana2.vm.cld.sr:8000/tracker/info/service/GPSTracker.xsodata”;
    8. var oModel = new sap.ui.model.odata.ODataModel(sUrl, true“userid”“password”);
    9. var oEntry = {};
    10. oEntry.STIMESTAMP = ‘/Date(0000000000000)/’;
    11. oEntry.SDATE      = ‘/Date(0000000000000)/’;
    12. oEntry.LAT =  position.coords.latitude.toString();
    13. oEntry.LONG = position.coords.longitude.toString();
    14. // oData Create
    15. oModel.create(‘/GPSTracker’, oEntry, null,
    16. function() { success = true;},
    17. function() {  failure = true;}   );
    18. if (failure == true) {
    19. alert(“Create failed”);
    20. }
    21. else {
    22. alert(“Data Saved!”);
    23. }
    24. }

    2.jpg

  • Create the Cordova Geolocation plugin
    Create a cordova project in C:\programs:

    – mkdir c:\programs

    – cd c:\programs

    – cordova create c:\programs\Geolocation com.enterprisemobility.Geolocation Geolocation

    – cd geolocation

    – cordova platform add android

    – cordova plugin add org.apache.cordova.geolocation

    Copy the index.html from the SAPUI5 project that we have created in previous step to c:\programs\geolocation\www and build the project:

    cordova build

    If the build is success, you will get the debug apk in the C:\programs\Geolocation\platforms\android\ant-build. Install this apk on your device.
    4.jpg

The HANA XS

The key components in the HANA XS:

  • The HANA table GPSTRACKER for storing the latitude and longitude position.

    table.schemaName = “GPSTRACKER”;

    table.tableType = COLUMNSTORE;

    table.description = “GPSTRACKER”;

    table.loggingType = NOLOGGING;

    table.columns = [

    {name = “STIMESTAMP”; sqlType = TIMESTAMP;  nullable = true;},

    {name = “SDATE”; sqlType = DATE; nullable = true;},

    {name = “LAT”; sqlType = NVARCHAR; length = 50; nullable = true;},

    {name = “LONG”; sqlType = NVARCHAR; length = 50; nullable = true;}

    ];

    table.primaryKey.pkcolumns = [“STIMESTAMP”];

  • An OData service GPSTracker.xsodata with custom insert procedure.

    service namespace “tracker.info.service” {

    “GPSTRACKER”.”tracker.info.init::GPSTracker” as “GPSTracker”

    create using “tracker.info.service::InsertRowGPSTracker”;

    }

  • An Insert procedure InsertRowGPSTracker.procedure for inserting the latitude and longitude position to GPSTRACKER table.

    insert into “GPSTRACKER”.”tracker.info.init::GPSTracker”

    values (current_timestamp, current_date,  lv_LAT,lv_LONG);

The Back-end Web App with Google Map

The back-end web app displays the timestamp, latitude & longitude coordinate in the table. User can select the item to display the exact location in the Google map. The “Refresh Data” button will update the information in the table with the new location received from the client.

 

In the GPS.view.js, we call the OData GPSTracker.xsodata/GPSTracker and bind it.

 

  1. oController.oModel = new sap.ui.model.odata.ODataModel(“hana2.vm.cld.sr:8000/tracker/info/service/GPSTracker.xsodata”,true“userid”“password”);
  2. vCol = “STIMESTAMP”;
  3. oControl = new sap.ui.commons.TextField({editable:false}).bindProperty(“value”,vCol);
  4. oTable.addColumn(new sap.ui.table.Column({label:new sap.ui.commons.Label({text: “Timestamp” }),
  5. template: oControl,
  6. sortProperty: vCol,
  7. filterProperty: vCol
  8. }));
  9. vCol = “LAT”;
  10. oControl = new sap.ui.commons.TextField({editable:false}).bindProperty(“value”,vCol);
  11. oTable.addColumn(new sap.ui.table.Column({label:new sap.ui.commons.Label({text: “Latitude” }),
  12. template: oControl,
  13. sortProperty: vCol,
  14. filterProperty: vCol
  15. }));
  16. vCol = “LONG”;
  17. oControl = new sap.ui.commons.TextField({editable:false}).bindProperty(“value”,vCol);
  18. oTable.addColumn(new sap.ui.table.Column({label:new sap.ui.commons.Label({text: “Longitude” }),
  19. template: oControl,
  20. sortProperty: vCol,
  21. filterProperty: vCol
  22. }));
  23. oTable.sort(oTable.getColumns()[0]);
  24. // Google Map
  25. oTable.attachRowSelectionChange(function(oEvent) {
  26. var currentRowContext = oEvent.getParameter(“rowContext”);
  27. var lat = oController.oModel.getProperty(“LAT”, currentRowContext);
  28. var lang = oController.oModel.getProperty(“LONG”, currentRowContext);
  29. oController.actSearch(lat, lang);
  30. });
  31. oTable.setModel(oController.oModel);
  32. oTable.bindRows(“/GPSTracker”);
  33. oPanel.addContent(oTable);

 

The oTable.attachRowSelectionChange function calls the Google Map actSearch function with parameter lat and lang.

 

  1. actSearch: function (lat, lang) {
  2. this.geocoder = new google.maps.Geocoder();
  3. var latlng = new google.maps.LatLng(lat, lang);
  4. var mapOptions = {
  5. center: latlng,
  6. zoom: 16,
  7. mapTypeId: google.maps.MapTypeId.ROADMAP
  8. };
  9. this.map = new google.maps.Map($(‘#map_canvas’).get(0), mapOptions);
  10. var marker = new google.maps.Marker({
  11. position: latlng,
  12. map: this.map,
  13. title: ‘You are here’
  14. });
  15. }

 

Source Code

You can find the complete source code in the GitHub: ferrygun/SAPHanaGPSTracker · GitHub

The final structure as per below screenshots:

 

8.jpg9.jpg

 

 

Run the App

 

After you have installed the apk in your device, enable the GPS and tap the app to run it

11.jpg
Upon receiving the GPS signal, the app will display the longitude and latitude position and send this information to HANA server. You can stop it by clicking the Clear Watch button
12.jpg

 

To run the backend web app,  open the link http://hana2.vm.cld.sr:8000/tracker/info/index.html in Chrome browser. Replace “hana2.vm.cld.sr” with your HANA server’s address. You will get the current position from the client.

7.jpg

 

 

Thank you for reading my blog and I hope you also enjoy developing the SAP HANA XS application.

Please feel free to drop me any feedback/comment.

P.S: this blog was inspired by http://scn.sap.com/community/developer-center/hana/blog/2013/11/17/latest-share-price-google-finance-odata-crud

Build SAPUI5 Cordova Barcode Scanner with OData Service

Standard

I would like to share how easily to integrate the Cordova barcode-scanner plugin with the SAPUI5 app and connect to the OData back-end service to retrieve the material number and description.

 

We will deploy the SAPUI5 app on the Android and use it to scan the barcode label. Once the barcode label is recognized, we pass it to the OData request to get the description of the material number.

 

The app screenshots will look like as below:

1403304389495.jpg1403304401680.jpg1403304411030.jpg

 

Required Components

 

OData Service

I am using the customized OData service ZGW_MATERIAL_SRV that is calling the BAPI_MATERIAL_GET_DETAIL with material number as an input. You may refer to other blog how to setup the OData service.

3.jpg

 

Execute http://sapgatewayserver.com/sap/opu/odata/sap/ZGW_MATERIAL_SRV/Materials(‘<material_number>) in the Chrome browser to get the input.

The sapgatewayserver.com is your SAP Netweaver Gateway server and the material number, for my case is 0009620-081.

 

The OData output format will look like as per below screenshot:

1.jpg

Barcode Scanner Function

The doScan method performs the barcode scanning. It is calling the cordova plugin barcodeScanner to get the barcode number in result.text. Then pass this parameter to the OData query string to perform the OData query. The response  (i.e., response.data.Material & response.data.MatlDesc) will be captured and printed in the scanresult page.

 

  1. doScan: function() {
  2.   cordova.plugins.barcodeScanner.scan(
  3.   function (result) {
  4.   jQuery.sap.require(“sap.ui.model.odata.datajs”);
  5.   var sUrl = http://sapgatewayserver.com/sap/opu/odata/sap/ZGW_MATERIAL_SRV&#8221;;
  6.   var oModel = new sap.ui.model.odata.ODataModel(sUrl, true“username”“password”);
  7.   oModel.read(
  8.   “/Materials(‘” + result.text + “‘)”,
  9.   null,
  10.   null,
  11.   true,
  12.   function(oData, response) {
  13.   console.log(response.data.Material);
  14.   var oMatID = []; var oMatDescr=[];
  15.   oMatID.push(response.data.Material);
  16.   oMatDescr.push(response.data.MatlDesc);
  17.   var data = [];
  18.   for(var i = 0; i < oMatID.length; i++) {
  19.   data.push({“MatID”: oMatID[i], “MatDescr”: oMatDescr[i]});
  20.   }
  21.   var oModel1 = new sap.ui.model.json.JSONModel({ “zgwmat”: data });
  22.   sap.ui.getCore().setModel(oModel1, “zgwmatmodel”);
  23.   var bus = sap.ui.getCore().getEventBus();
  24.   bus.publish(“nav”“to”, {
  25.   id : “scanresult”,
  26.   });
  27.   },
  28.   function (err) {
  29.               alert(“Error in Get — Request “ + err.response.body);
  30.                   console.log(err.response.body);
  31.              }
  32.   );
  33.        },
  34.      function (error) {
  35.         alert(“Scanning failed: “ + error);
  36.     }
  37.   );
  38.   },

The complete source code is available in the Github: https://github.com/ferrygun/SAPUI5CordovaBarcodeScanner

Create Cordova Project

 

Make a folder programs in your C:\ drive and create the cordova project by executing the following command:

 

  • cordova create C:\programs\barcodeScanner com.enterprisemobility.barcodeScanner barcodeScanner
  • cd barcodeScanner
  • cordova platform add android

 

Then copy all your files (except META-INF and WEB-INF) in Eclipse barcode-scanner WebContent folder to C:\programs\barcodeScanner\www

6.jpg

The final structure in C:\programs\barcodeScanner\www will be like this:

7.jpg

Build the Cordova Project

 

Execute the following command to build the cordova project under C:\programs\barcodeScanner

  • cordova build

 

If it’s successful, you will get the debug APK file (barcodeScanner-debug.apk) in C:\programs\barcodeScanner\platforms\android\ant-build.

 

Copy this APK to your Android device to test the app.

 

Generate Barcode
Please visit the http://www.barcode-generator.org/ to generate the online barcode to test the app.
Select a barcode: Code 128, enter the barcode number 0009620-081 and click on Create Barcode.

5.jpg

 

You will get the following barcode image. Print it, we will use it to scan the barcode label using our app.

2.jpg

Demo Video

 

 

I hope you enjoy and successful implementing the barcode plugin with your SAPUI5 app. Please feel free to drop any comment/feedback.

 

Thanks for reading my blog.

Auto Device Registration in SAP Mobile Platform with Sencha Touch

Standard

Hi to all,

What I would like to share in this blog is how we are going to create an app using Sencha Touch 2 that is able to perform device registration automatically in the SAP Mobile Platform.

What You Need

These are the components that you need in order to execute the app:

Setting Up Application ID in SAP Mobile Platform

  • After you have registered an account in https://account.hanatrial.ondemand.com/, please log-on and it will bring you to the SAP HANA Cloud Platform Cockpit
    1.jpg
  • Go to  Account Information > Services > SAP Mobile Platform
  • You will see the main Home page. Please go to Applications page and click New
  • Under New Application, fill in the following information. For the application ID com.FD.Demo, please take a note carefully of this name convention. We will use this naming convention in our Sencha code.
ID com.FD.Demo
Name com.FD.Demo
Vendor FD
Description FD Demo

4.jpg

  • Under Back End, fill in the following information:
EndPoint http://sapes1.sapdevcenter.com:8080/sap/opu/odata/iwbep/gwdemo/
Connect to Internet
Rewrite URL Checked
Allow anonymous connection Checked
Username Username (for example: P1940517116)
Password password

5.jpg

You can use any OData services available from SAP OData backend service that you have registered. I am using the CountryCollection to get the country description: http://sapes1.sapdevcenter.com:8080/sap/opu/odata/iwbep/gwdemo/CountryCollection

  • Continue with Authentication. Go to this tab, select New for the Security Profile and fill in the below information then click Save.
Security Profile Name com_FD_demo
Authentication Type Basic Authentication
Authentication URL http://sapes1.sapdevcenter.com:8080/sap/opu/odata/iwbep/gwdemo/
Connect to Internet

6.jpg

Test the SAP Mobile Platform Connection

To test the setting that we have done it in the above steps, please go to the Application page, select the application ID that we have created, com.FD.Demo and click Ping. If successful, you will see the green checked icon status for both Backend and Security profiles.

7.jpg

Setting up Sencha Touch

Don’t worry about writing the codes, you can download the source code from the Github site: https://github.com/ferrygun/SenchaSMP3.0.
You can create a new app in Sencha working folder by typing:

sencha -sdk “<path_to_ SDK touch-2.3.1>” generate app -name <Name_of_App> -path “<path_to_App>”

For example, if you want to create the Sencha app named with FD4 and SDK folder is in C:\touch-2.3.1 and your Sencha working folder is in C:\SenchaTouch\FD4, then you can type the following command in the command-prompt:

sencha -sdk “C:\touch-2.3.1” generate app -name FD4 -path “C:\SenchaTouch\FD4”

In this app, a user will enter the country code to get the description of the country code. The country code entered by the user will be passed to OData service:

http://sapes1.sapdevcenter.com:8080/sap/opu/odata/iwbep/gwdemo/CountryCollection(‘<country_code>’)

If the country code exist, it will print the country code description in another page.

10.jpg11.jpg

In order to access the data from SMP, firstly we need to register the device in the SMP. Below simple workflow describes the logic to connect to the application ID. This process will be executed every time the app is loaded. Please put this under controller init function: /app/controller/note.js > init.function().

9.jpg

  • First step is to check if it can connect to application ID. It performs a simple Ajax GET request to https://smp-p1940517092trial.hanatrial.ondemand.com/com.FD.Demo/

    1. Ext.Ajax.request({
    2. url: ‘<apache_web_server>/sapgw/com.FD.demo’
    3. headers: {
    4. “Content-Type” : “application/atom+xml; charset=UTF-8”,
    5. “Authorization” : ‘Basic UDE5NDA1MTcxMTY6UGFwYW1hbWExOA==’
    6. },
    7. method: ‘GET’,
    8. withCredentials: true,
    9. useDefaultXhrHeader: false,
    10. disableCaching: false

The Authorization value above is the result of the base64.encode of your username and password in the SAP OData backend service. The above code is calling the application ID com.FD.Demo that we have defined in the SMP and perform the GET request.

Content-Type application/atom+xml; charset=UTF-8
Authorization Basic UDE5NDA1MTcxMTY6UGFwYW1hbWExOA==
XML Body <?xml version=”1.0″ encoding=”utf-8″?>
<entry xmlns=”http://www.w3.org/2005/Atom” xmlns:m=”http://schemas.microsoft.com/ado/2007/08/dataservices/metadata” xmlns:d=”http://schemas.microsoft.com/ado/2007/08/dataservices“>
<content type=”application/xml”>
<m:properties>
<d:DeviceType>devtype</d:DeviceType>
</m:properties>
</content>
</entry>where devtype is one of these combinations depending on the OS’ client:
iPad, iPhone, iPod, iOS, Android, Blackberry, Windows, Unknown
    1. if(response.statusText == ‘Not Found’ || response.statusText == ‘Forbidden’ ) {
    2. if(Ext.os.is.iPad) {
    3. devtype = ‘iPad’
    4. else if(Ext.os.is.iPhone) {
    5. devtype = ‘iPhone’
    6. else if(Ext.os.is.iPod) {
    7. devtype = ‘iPod’
    8. else if(Ext.os.is.iOS) {
    9. devtype = ‘iOS’
    10. else if(Ext.os.is.MacOS) {
    11. devtype = ‘iOS’
    12. else if(Ext.os.is.Android) {
    13. devtype = ‘Android’
    14. else if(Ext.os.is.BlackBerry) {
    15. devtype = ‘BlackBerry’
    16. else if(Ext.os.is.Windows) {
    17. devtype = ‘Windows’
    18. else if(Ext.os.is.Other) {
    19. devtype = ‘Unknown’
    20. }
    21. var regXML = ‘<?xml version=”1.0″ encoding=”utf-8″?>’ +
    22. ‘<entry xmlns=”://www.w3.org/2005/Atom” xmlns:m=”://schemas.microsoft.com/ado/2007/08/dataservices/metadata” xmlns:d=”://schemas.microsoft.com/ado/2007/08/dataservices”>’ +
    23. ‘<content type=”application/xml”>’ +
    24. ‘<m:properties>’ +
    25. ‘<d:DeviceType>’ + devtype + ‘</d:DeviceType>’ +
    26. ‘</m:properties>’ +
    27. ‘</content>’ +
    28. ‘</entry>’
    29. Ext.Ajax.request({
    30. url: ‘//<apache_web_server>/sapgw/odata/applications/latest/com.FD.Demo/Connections’,
    31. headers: {
    32. “Content-Type” : “application/atom+xml; charset=UTF-8”,
    33. “Authorization” : ‘Basic UDE5NDA1MTcxMTY6UGFwYW1hbWExOA==’
    34. },
    35. method: ‘POST’,
    36. withCredentials: true,
    37. useDefaultXhrHeader: false,
    38. xmlData: regXML,
    39. disableCaching: false
  • If the registration process is successful, you will see the application connection ID with the status registered under Application Connection tab. You can see the device type is Windows because I am running the app in my Windows OS. If you are running the app from your iPhone, you will see the device type is iPhone. Please try it.
    12.jpg
  • During registration process, user will not be able to interact with the app. Once it is completed, user can continue.

Hopefully the above blog will benefit you to gain insight and experience in using the SAP Mobile Platform. Off course you also can put the log-on page before the app checks the connection ID to enforce the security.

Thanks for reading my blog and feel free to drop me any comments.