SAP HCP IoT Nodejs and Python

9
SAP HANA CLOUD PLATFORM – IOT SERVICES Using Nodejs and Python to send data to the HCP IoT Aaron Williams / PM SAP HCP & SAP IOT Twitter: @aarondonw, SCN: Aaron Williams Description This show you how you can post data to your HCP IoT Services account, using NodeJs and Python. For this example, you will not need an IoT device. This is part of a series, to see the other items follow this link to SCN. System prerequisites Have an SAP HCP Trial Account Target group Application developers People interested in the SAP HANA Cloud Platform- IoT Services Target group requirements Basic programming language, ideally in Java, JavaScript/NodeJS, and/or Python.

Transcript of SAP HCP IoT Nodejs and Python

SAP HANA CLOUD PLATFORM – IOT SERVICES Using Nodejs and Python to send data to the HCP IoT

Aaron Williams / PM SAP HCP & SAP IOT Twitter: @aarondonw, SCN: Aaron Williams Description This show you how you can post data to your HCP IoT Services account, using NodeJs and Python. For this example, you will not need an IoT device. This is part of a series, to see the other items follow this link to SCN. System prerequisites • Have an SAP HCP Trial Account

Target group • Application developers • People interested in the SAP HANA Cloud

Platform- IoT Services

Target group requirements • Basic programming language, ideally in Java,

JavaScript/NodeJS, and/or Python.

Using Nodejs and Python to send data to the HCP IoT

2

Step 1: Set up- Getting Node.js

Explanation Screenshot

USE Google Chrome or Firefox browser

The first thing that you will need is node.js. So head over to https://nodejs.org and click the install button.

1. Open your favorite text editor/IDE (textpad, sublime, etc). Notepad will work for this too.

2. Create a file named basicIoT.js, and save it. You will need to navigate to this, so put in a place where you can easily get to it.

3. Copy and paste the code on the right to the file and save it. There are a lot of comments in the code. You will need to go in and customize it for your account. Namely, you need to change the hostIoT (approx.. line 12), authStrIoT (approx. line 21), and deviceID (approx.. line 23).

/* * By Aaron Williams - Product Manager SAP HCP/IoT * @aarondonw * The goal of this is to simply push data into the HCP * using the SAP IoT Services */ //Host for your IoT server var hostIoT = 'iotmms<user>trial.hanatrial.ondemand.com'; //port var portIoT = 443; //path to post data var pathIoT = '/com.sap.iotservices.mms/v1/api/http/data/'; //this is the authorization token, format is Bearer <auth token> //the auth token is taken from device ID on the IoT Services Cockpit // this is a string so it surrounded by single quotes (') var authStrIoT = 'Bearer <authoriation token>'; //the device ID that you are sending the data from var deviceId = '<device ID'; // message type id for the device var stationId = 1; var date = new Date(); var time = date.getTime (); //just some data to send var temp =9; var humid=0; var brightness=0; /** main function * All this does is take some data and push it into the HCP DB **/ setInterval(function () { temp ++; humid ++; brightness++; updateIoT(temp,humid,brightness) }, 5000); ///this does the work function updateIoT(temp, humid,brightness) { var http = require('https'); var options = { host: hostIoT, port: portIoT, path: pathIoT + deviceId, agent: false, headers: { 'Authorization': authStrIoT, 'Content-Type': 'application/json;charset=utf-8' }, method: 'POST', }; options.agent = new http.Agent(options); callback = function(response) { var body = ''; response.on('data', function (data) { body += data; }); response.on('end', function () { //console.log("END:", response.statusCode, JSON.parse(body).msg); }); response.on('error', function(e) { console.error(e); }); } var req = http.request(options, callback); req.on('error', function(e) { console.error(e); });

Using Nodejs and Python to send data to the HCP IoT

3

date = new Date(); time =date.getTime(); req.shouldKeepAlive = false; var jsonData = { "mode":"sync", "messageType":"1", "messages": [{ "Humidity": humid, "Temperature": temp, "Brightness": brightness, "timestamp": time }] } var strData = JSON.stringify(jsonData); console.log("POST jsonData:" + strData); console.log(""); req.write(strData); req.end(); }

4. Go to your cockpit and click on the JAVA Applications, and click on your Java application, make sure that it is running.

5. Start the nodejs application by typing

node basicIoT.js

You will now see data pumping to your HCP instance, every five seconds

If you get a compile error, make sure that there wasn’t a copy/paste error. Some times, copying can cause issues. If you get other errors, make sure that your JAVA Application is up and running.

6. Go back to the HCP Cockpit and click on the link to your Application URLs

You should see your graph with the new data coming in.

Using Nodejs and Python to send data to the HCP IoT

4

7. To stop the node server, press control-c

It is that easy.

Using Nodejs and Python to send data to the HCP IoT

5

Step 2: Python

Explanation Screenshot

To install a lot of things in the python world you will, you will want pip. Go here and follow the instructions to get pip. https://pip.pypa.io/en/latest/installing.html The link will also help you out to determine which version of pip you have.

1. You will need to install a package called urlib3. Go here for instructions: https://urllib3.readthedocs.org/en/latest/

Under the “Getting Started” section it will tell you to type in: pip install urllib3

2. Open your favorite text editor/IDE

3. Create a file named basicIoT_python.py

4. Copy and paste the code on the right to the file and save it.

import urllib3 import datetime import time # disable InsecureRequestWarning if your are working without certificate verification # see https://urllib3.readthedocs.org/en/latest/security.html # be sure to use a recent enough urllib3 version if this fails try: urllib3.disable_warnings() except: print('urllib3.disable_warnings() failed - get a recent enough urllib3 version to avoid potential InsecureRequestWarning warnings! Can and will continue though.') # use with or without proxy http = urllib3.PoolManager() # http = urllib3.proxy_from_url('http://proxy_host:proxy_port') # interaction for a specific Device instance - replace 1 with your specific Device ID #url = 'https://iotmms_on_your_trial_system.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/1' url = 'https://iotmms<userID>trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/' deviceID = '<device_ID>' url = url +deviceID headers = urllib3.util.make_headers() # use with authentication # please insert correct OAuth token headers['Authorization'] = 'Bearer ' + 'edc1eea6f8d820b4c555509b199cfe8' headers['Content-Type'] = 'application/json;charset=utf-8' #I just started with random numbers, you can choose what ever you like temperature =29 humidity =5 brightness=15 #just put in 3 rows into the DB for x in range(0, 3): current_time = int (time.time() *100) timestamp =str (current_time) brightness= brightness+1 humidity=humidity+1 temperature=temperature+1 stringBrightness = str (brightness) stringHumidity = str(humidity) stringTemperature = str(temperature) print (str (current_time)) # send message of Message Type 1 and the corresponding payload layout that you defined in the IoT Services Cockpit body='{"messageType":"1","mode":"sync","messages":[{"timestamp":' body=body+timestamp body = body +',"Humidity":'+stringHumidity body = body +',"Brightness":'+stringBrightness body = body +',"Temperature":'+stringTemperature+'}]}' print ("") print (body) r = http.urlopen('POST', url, body=body, headers=headers) print ("") print(r.status) print(r.data)

Using Nodejs and Python to send data to the HCP IoT

6

5. Open a terminal and navigate to the folder with your code. -Terminal for a Mac and Command prompt for Windows (cmd)

6. Start the python application by typing

$ phython basicIoT_python.py

7. You will now see data pumping to your HCP instance, every five seconds

8. Go to your cockpit and click on the JAVA Applications, and click on your Java application, make sure that it is running.

9. Click on the link in the section Application URLs

Step 3: Other Languages/next steps

Explanation Screenshot

As you can see, the language that you use to send the data doesn’t matter. As long as you can send a post you can send data to the IoT Services.

Using Nodejs and Python to send data to the HCP IoT

7

So now try to send other messages or hook up a device and send data from that.

Using Nodejs and Python to send data to the HCP IoT

8

Using Nodejs and Python to send data to the HCP IoT

9

Citations/ Acknowledgements This is was based upon a post by Michael Ameling and the IoT Services Starter Kit. I also got a lot of help from Philip Mugglestone of the Hana Academy team.

© 2014 SAP SE or an SAP affiliate company. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company. SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Please see http://www.sap.com/corporate-en/legal/copyright/index.epx#trademark for additional trademark information and notices.