Have you ever felt you do not get enough sun at work? This 21 hour hands-on tutorial will allow you to connect a light sensor via a internet-connected microcontroller to a Hana Cloud Platform account to create your very own Internet of Things solution. In HCP you will create a database to store the sensor readings and a small Fiori app that allows you to analyze your exposure to the sun in a table chart. All with a trial account and from the comfort of your browser.

The Idea is to learn about all of the different pieces: devices, firmware, authentication with tokens instead of users, hana database, odata service and ui5 controls to get an end-to-end impressions of the technologies involved. This is not a reference architecture for a big, real/life project but what you learn will be useful to understand the issues that might occur.

If you are near Walldorf stop by the d-shop and borrow one of 86 devices we have on hand for this tutorial. In other regions or situations you might simply buy an Arduino Yun or another internet-enabled microcontroller to serve as your device.

(please excuse the formatting below – SCN does not allow to upload word files)

Measure the Sun with Hana Cloud Platform – Hands On

Intention

This tutorial shows you how you can develop a simple IoT application with off the shelf hardware (e.g. borrowed from a fal lab or d-shop near you) and the HCP trial account. You will touch all of the technologies necessary and learn how to make use of them.

Prerequisites

You should have a Wifi network available to you and know the network name (aka SSID), the user and the password to login. If you don’t have such a network around you can use the hot spot of a smartphone instead.

Overview of the Steps

  1. Create an account in HCP, turn on IoT services and register your device and its sensors
  2. Create an account and code the firmware for the Electric Imp to write sensor data into HCP
  3. Build a sample Fiori app to show the sensor data from OData service as a table

Create HCP account and create your device and sensor

This account in the SAP cloud allows you to store your sensor data in the Hana database and then allows you to build additional Java or HTML5 applications on top. Furthermore can you use other services from HCP to support your application like Monitoring, Mobile or even Gamification.

If you are an SAP employee you already have a trial account and a developer user on this account on HCP. If you go to https://account.hanatrial.ondemand.com/ and press logon a certificate with your SAP user id on your SAP PC or SAP iPad will log you in automatically.

If you do not have an HCP trial account you only need an email address and at https://account.hanatrial.ondemand.com/ you can register for a trial account for developers in a few minutes. Login to your trial account to start.

Under “Services” enable the “Internet of Things Services”.

Then “Go to Service”. You will see multiple apps that let you administer your devices and sensors.

Next you need to deploy the Messaging Service app into your HCP account. To do so press “Deploy Message Management Service”. You can now close this browser tab again.

In the HCP cockpit go to “Java Applications” and open the app “iotmms”. Under Roles assign your user id (either something like D039026 or p1501272555 – check in your URL) to the role “IoT-MMS-User”. This will allow you to see the messages posted to your device later in this script.

Now we can register our device and our sensor. To do so in the HCP cockpit go again to the IoT Service under “Services”.

Go to the “Device Types” app and create a new device type called “iotimp”. This is the “model” of the device like “Chevrolet Impala” or like “iPhone 5s”.

Go back to the IoT Services cockpit, start the “Message Types” app and create a new message type called “lightreading” with one field called “light” of type “integer”. This is the kind of message the device can send to the server.

PLEASE take note of the message type id (something like “c5b17a4be2d56c9b0eca”) as you will need it later on the device to send this kind of message.

Lastly from the IoT Services cockpit use the Devices app to create your specific device in the system (e.g. your iPhone 5s with IMEI number …). Use as the name “imp” and append the number written on the electric imp to it (e.g. “imp3”). But make sure you …

… PLEASE make sure you note down the OAuth token (something like “fb1bfcf6ea2216bc39d52b6fccb38”) as this is what you later need to put on your device to authenticate it towards HCP. Otherwise anyone could send this message type on behalf of this device to HCP. This will only be shown here once and if you do not write it down you have to generate a new token (or if someone steels your device then you should also regenerate the token).

PLEASE lastly take note of the device id for your imp (something like “50e1f31c-adf0-4b88-94c0-7d1a80668664”). This is required to identify the device towards HCP.

You have now successfully readied the server part of your IoT application to receive messages from the device. You could (if you wish) send this message from any device via a POST request (e.g. from Chrome with the advanced rest client).

Program your Imp to send measurements to HCP

The electric imp hardware comes with a cloud account of its own. This account is used to maintain devices and the firmware on those devices.

Please create a new Account for yourself on the electric imp website at https://ide.electricimp.com/login and login to this account. This account will now be used on a mobile device to onboard your device in the field.

Download the native Electric Imp app on your ios or android device (you can find the apps by searching for “electric imp” in the respective app stores).

Open the app, log in and open “Configure an Imp” or “Other Network”.

Enter the name of your wifi network, user and password. If you are in SAP you can use the network SAP-Internet and leave the password field empty – the imps in use in SAP have been whitelisted.

Turn on the power to the imp (push the white sd card into its slot) – the sd card should be blinking red.

Press the “Send BlinkUp” button and hold the end of the sd card onto the screen of the smart device. There is a photo sensor in the imp which will read the wifi credentials from the blinking screen. You might want to look away as the blinking can be irritating.

Afterwards the Imp should blink green about 20 times and then stop blinking.

Go back to your browser where you are logged in. You should see the new imp with a number as its identifier under “Unassigned Devices”.

Now create a new model called “iotimp” and assign the imp you have just connected to the Internet to this model. If you select the number identifying your imp then you should see that the imp is “online” in the upper right corner.

Select the model and insert the code below into device field (right side of the screen):

hardware.pin8.configure(ANALOG_IN); // light sensor is tied to pin 8

function mainLoop() {

    local light = hardware.pin8.read(); // reading light sensor value

    agent.send(“light”, light); // send the value to the server under the label “light”

    imp.wakeup(15, mainLoop); // start this function again in 15 seconds

    };

mainLoop();

You can now push this code to the device by pressing “Build and Run”. The device is now checking for light level every 15 seconds and is sending it to the electric imp agent in the cloud. But the agent does not do anything with it yet.

To let the agent show the value please paste the following code on the left side of the screen:


device.on(“light”, function(light) { // whenever we get a “light”

  server.log(light); // we show the value in the log

});


Once you build and run this you should see the sensor values show up in the log at the bottom of the screen. Please take note of the values you get when the light sensor is not covered vs when you cover it with your finger.

To let the agent post the sensor data to HCP please paste the following code on the left side of the screen on the agent side:


device.on(“light”, function(light) { // whenever we get a “light”

    // replace the following token with your access token

    local headers = {“Authorization”:”Bearer fb1bfcf6ea2216bc39d52b6fccb38″,

“Content-Type”:”application/json;charset=utf-8″};

    // change URL to fit your trial account and device id

    local url = “https://iotmmsp1501272555trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/50e1f31c-adf0-4b88-94c0-7d1a80668664“;

    // adjust message type id to yours

    local body = “{\”mode\”:\”sync\”, \”messageType\”:\”c5b17a4be2d56c9b0eca\”, \”messages\”:[{\”light\”:” + light + “}]}”;

    local request = http.post(url, headers, body);

    local response = request.sendsync();

    foreach (index, slot in response)

        {

        server.log(index);

        server.log(slot);

        }

});


Before building and running this you need to replace the url to match your trial account url. You also need to replace the values for device (part fo the url), message type  and authorization token with your values noted earlier.

Once you build and run this your HCP database should fill with data from your sensor. To check this follow the following steps:

Login to the hana cloud platform at https://account.hanatrial.ondemand.com/.

Go to “Services” and then go to the “IoT Services” and then “Go To Service”.

Then jump into the MMS Cockpit app. From there start the “Display stored messages” app.

If you now continuously click on the table icon that has your message type id in its name (in my case T_IOT_C5B17A4BE2D56C9B0ECA) you can see that a new sensor value shows up every 15 seconds. The timestamp is generated by the server and the server is (like all IoT devices) on UTC timezone.

You now have a database filling up with sensor values. The last part shows you how to make use of this sensor data by visualizing it or building other apps on top.

Create OData feed and HTML5 app showing the data

We will do this in 2 steps. First we will create an OData service that allows to acces the data from any application. OData is a standard defined by Microsoft and SAP and multiple tools are available from Microsoft (e.g. PowerPivot) and others that can read such OData feeds.

Secondly we will build a small HTML5 app with the open source UI5 controls that you can extend as you see fit for your use case.

To do this again login to the hana cloud platform at https://account.hanatrial.ondemand.com/.

Under “HANA Instances” create a Hana Instance with name “iotinstance”. You can also use an instance that already exists in your trial account – then you need to replace all mentions of iotinstance below with the name of your instance. This instance is the new database we want to use for both storing sensor data and retrieving it.

Now go to Java Applications and stop the “iotmms” app. Delete the Data Source Binding and create a new binding to the HANA XS database instance. Start the application again. Now all sensor data is stored into this new database every 15 seconds.

Go back to the HCP cockpit and under “HANA Instances” open the “SAP HANA Web-based Development Workbench”. You should see your trial account name (e.g. d039026trial) and your hana instance “iotinstance” underneath.

From the menu open the “Catalog”. You will see multiple databases and at least one starting with “NEO_” and one starting with “DEV_”. Expand the databases starting with “NEO_” and the Tables group and find the table that corresponds to your message type ids (In my case it was T_IOT_C5B17A4BE2D56C9B0ECA). Use the right click menu on the table to “Open Content”. This will generate a query on the right side and shows the content of the table.

Please take note of the name of the database and the table for later use (something like “NEO_61PHH4VTB4EOC8CEWTKI5O4BP”.”T_IOT_C5B17A4BE2D56C9B0ECA”).

Lastly you need to provide access to your user of the content to this table from outside of this workbench. To do so replace the query with the following statement:


GRANT SELECT ON T_IOT_C5B17A4BE2D56C9B0ECA TO p1501272555;

Make sure you replace the table name and the user name with your table and user. Press the green button to run this statement. It should execute successfully.

To be able to read the data we will now create an OData service in XS.

Go back to the tab with the HANA web-based development workbench and right click your hana instance “iotinstance” and create a new package called “iotpackage”.

In this package (using right click) create a new file called “.xsapp” and leave it empty. Make sure to save it anyway. To check your result you can see the new app listed in the Hana Cloud Cockpit under HANA XS Applications (you might need to refresh the browser window).

In the HANA web-based development workbench create a new file called “.xsaccess” with the following code and save it. This defines the authentication method that will be used to govern access to the OData service:


{“exposed” : true ,”authentication” : [{“method” : “Basic”}]}

Lastly create 1 more file called “iottable.xsodata” and put the following into it:


service { “NEO_61PHH4VTB4EOC8CEWTKI5O4BP”.”T_IOT_C5B17A4BE2D56C9B0ECA” key generate local “GeneratedID”;}

Make sure to replace the name of the database and table with yours. Save it to activate it. This generates an OData service end point on the Hana Cloud Platform that can be called by anyone in the internet.

Now you can actually call the OData service in the browser to see the table by pressing the green button. It will open a URL similar to this in a new browser tab:

https://s8hanaxs.hanatrial.ondemand.com/p1501272555trial/iotinstance/iotpackage/iottable.xsodata


If you append the name of your table:


https://s8hanaxs.hanatrial.ondemand.com/p1501272555trial/iotinstance/iotpackage/iottable.xsodata/T_IOT_C5B17A4BE2D56C9B0ECA


You can see your data now in the browser. You can try this from any browser and after logging in you get access to your data from the cloud.


Create a UI5 app to show your data

Back in the HANA web-based development workbench right click your hana package called “iotpackage” and create a new file called index.html with this content:

<!DOCTYPE html>

<html>

  <head>

    <meta http-equiv=’X-UA-Compatible’ content=’IE=edge’ />

    <meta http-equiv=’Content-Type’ content=’text/html;charset=UTF-8′ />

    <title>IoT App</title>

    <!– Bootstrap SAP UI5 libraries –>

    <script id=’sap-ui-bootstrap’ type=’text/javascript’

src=’https://sapui5.hana.ondemand.com/resources/sap-ui-core.js

      data-sap-ui-theme=’sap_bluecrystal’

      data-sap-ui-libs=’sap.ui.commons, sap.viz, sap.ui.table’>

  </script>

  <script>

    var table = new sap.ui.table.DataTable({

    columns : [{

                    label : “Device”,

                    template : “G_DEVICE”,

            },

            {

                    label : “Light”,

                    template : “C_LIGHT”

            },

            {

                    label : “Created”,

                    template : “G_CREATED”,

                    sortProperty : “G_CREATED”

            }]

    });

    //Bind the table to the OData service

    var tableModel = new sap.ui.model.odata.ODataModel(“iottable.xsodata”, true);

    //Define a panel that has a title and that contains some text and the table

    var panel = new sap.ui.commons.Panel();

    table.setModel(tableModel);

table.bindRows(“/T_IOT_C5B17A4BE2D56C9B0ECA?$orderby=G_CREATED%20desc”);

    panel.addContent(table);

    //Place the panel in the body of the HTML document

    panel.placeAt(“content”);

    setInterval(function () {

      table.bindRows(“/T_IOT_C5B17A4BE2D56C9B0ECA?$orderby=G_CREATED%20desc”);;  

    }, 5000);

  </script>

  </head>

  <body class=’sapUiBody’>

    <div id=’content’></div>

  </body>

</html>


Please make sure you change the name of the table in 2 places in this file to your table name.

If you save the file and hit the green run button it should work right away and show your data in a chart and in a table updating every 5 seconds.

Reference

This end-to-end walkthrough is based on the help of a few talented people like Martin Raepple, Domnic Savio Benedict, Praharshana Perera, Rui Nogueira, Anika Schwind and Mathias Uwe Berg-Neels who I could not have completed this without. Furthermore there are a lot of tutorials covering individual steps:

http://hcp.sap.com/developers/TutorialCatalog/nat200_04_native_hana_hello_ui5_with_webide.html

https://help.hana.ondemand.com/help/frameset.htm?e4c52854bb571014aeb88753d0dad158.html

https://electricimp.com/docs/gettingstarted/blinkup/

http://hcp.sap.com/developers/TutorialCatalog/nat200_04_native_hana_hello_ui5_with_webide.html

https://help.hana.ondemand.com/help/frameset.htm?3762b229a4074fc59ac6a9ee7404f8c9.html

http://scn.sap.com/community/developer-center/cloud-platform/blog/2013/10/17/8-easy-steps-to-develop-an-xs-application-on-the-sap-hana-cloud-platform

Open Ends

It would be great to add predictive.

It would be great to record a video of doing all steps in 2 minutes.

Would be great to base a Smart Business KPI on top – we can do this once Smart Business is available in HCP. It would also be great to show integration to the predictive maintenance application.

It would be great to see what’s needed to make our odata feed fit into Open Data. But making it available publicly (anonym) is not possible on trial accounts.

Troubleshooting

If you are stuck it might be necessary to start over with a clean trial account. To do so delete the hana instance (will also delete the hana xs apps), delete all java apps. Then start over at the top of the document.

If your trial account is messed up for whatever reason one more option is to create a new trial account under e.g. your private email address. But unfortunately on an SAP device it is difficult to notlogin to the default trial associated with your sap user id. To do so you either use a non-sap machine or you disable the certificate (under browser settings > certificates and lots of clicks).

One has to first create the table, then create the xs app and the odata service for it, execute the odata top level request once and only then you can grant privileges to your user.

To report this post you need to login first.

3 Comments

You must be Logged on to comment or reply to a post.

    1. Marcus Conrad Behrens Post author

      No, the light sensor you have to solder to pin 9 yourself. The simplest is a light dependent resistor (LDR) which has between 1K and 100K resistance. You tie one end to 3.3v supply voltage, the other end to pin 9. Additionally you need to tie a 10k resistor from pin 9 to ground. This way the analog value on pin 9 represents the ratio of resistance between the ldr and the regular resistor.

      In your company or community there should be soem kind of maker space or fab lab that can help you with this very basic soldering task.

      You can also choose to use a different sensor if you want to measure something else.

      In the next version of this tutorial I would like to add the ability to analyse the data with different analytics tools from SAP and others via OData and to define rules and thresholds to be pushed back to the device.

      (0) 

Leave a Reply