8
SAP HANA CLOUD PLATFORM – IOT SERVICES Using Nodejs and Python to send data to the HCP IoT Aaron Williams, Sonali Desai / PM SAP HCP & SAP IOT Twitter: @aarondonw, @sonalid_SAP SCN: Aaron Williams Sonali Desai 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. Version : 2.0 Date : 12/8/2015 Updated by : Sonali Desai

SAP HCP IoT Nodejs and Python

Embed Size (px)

Citation preview

Page 1: 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, Sonali Desai / PM SAP HCP & SAP IOT Twitter: @aarondonw, @sonalid_SAP SCN: Aaron Williams Sonali Desai 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.

Version : 2.0 Date : 12/8/2015 Updated by : Sonali Desai

Page 2: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

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 10), authStrIoT (approx. line 19), deviceID (approx.. line 21) , and Messagetypeid ( on line 85) (Also note that you need to change the message structure according to the fields specified in your message type.)

/* * 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); });

2

Page 3: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

date = new Date(); time =date.getTime(); req.shouldKeepAlive = false; var jsonData = { "mode":"sync", "messageType":"messagetyeID", //replace messagetypeid with id from IOT cockpit "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. Note: Check your corporate proxy settings. Otherwise connect to external network outside the proxy.

3

Page 4: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

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

You can check the messages sent in corresponding table by clicking on ‘Display stored messages’ 7. Push the back arrow to get

back to the IoT Services Message Manage Service.

Then press Display Stored Messages tile

8. Select the table that contains your device and you will see the data that you sent

Note: the long table name is the true name of the table. Its format is T_IOT_[message type ID]

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

It is that easy.

4

Page 5: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

Step 2: Python

Explanation Screenshot

Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip by default, so you may have pip already. If you want to install or upgrade 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.

10. 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

11. Open your favorite text editor/IDE

12. Create a file named basicIoT_python.py

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

Change the userID (Approximately on Line 18), deviceID (Line 19) ,authorization token (Line 27) and messagetypeid (Line 45) (Also note that you need to change the message structure according to the fields specified in your message type.)

import datetime import time import urllib3 # 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

5

Page 6: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

/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 ' + '<authoriation token>' 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 body and the corresponding payload layout that you defined in the IoT Services Cockpit # replace messagetypeid with id from IOT cockpit body='{"messageType":"messagetypeid","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)

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

15. Start the python application by typing

$ phython basicIoT_python.py

6

Page 7: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

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

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

18. Click on the link in the section Application URLs and check the messages sent in corresponding table by clicking on ‘Display stored messages’

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. So now try to send other messages or hook up a device and send data from that.

7

Page 8: SAP HCP IoT Nodejs and Python

Using Nodejs and Python to send data to the HCP IoT

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.

© 2015 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.

8