Skip to Content
Technical Articles

[SAP Leonardo IoT] How to use GeoTest feature to check violation of geofences

SAP Leonardo IoT has released several functionalities regarding Geolocation service. You can create geofence location and trigger alert based on the current location of the devices or things.

 

 

Story

Let’s assume there is a rental car company in United States and they don’t allow their customers to cross the border between US and Canada so they set up GPS sensor on the car and set the rule to alert the company when any of customers have crossed the border.

 

 

Architecture

Since we are going to focus on the “Matching Geolocations within a Geoposition“, we will just trigger API endpoint of simple NodeJS server.

 

 

 

Prerequisite

In this blog post, we will not cover how to enroll devices in SAP IoT Service and how to make ‘Thing models’ on the SAP Leonardo IoT. We will assume that you already have created an IoT device with Latitude, Longitude properties as measures values and connected the device to the ‘Thing model’  successfully.

If you need information regarding how to create IoT devices and generate Things, please refer to this blog post.

SAP Leonardo IoT – How to define your Device Model and start persisting measures (How to create IoT Device)

SAP Leonardo IoT – Digital Twin ( How to create Thing model)

 

 

 

Step 1) Create Rule Context

  1. Let’s create Rule context so we can use this when we are creating a rule.

 

2. Click “New” on the top right side of the page.

 

3. Fill out basic data and select Package and Thing Type by clicking ‘add property set’

 

 

 

Step 2) Create a Rule

 

  1. Let’s create Rule so our Action engine can trigger the action based on the rule.

 

2. Create Rule -> Select Streaming Cloud

3. Enter a name of the new rule and click Definition tab

 

3. on the Definition tab, select Rule Context that you have created in the last section

4. Click Property Set name and click confirm

 

5. In the Rule Definition section, define the If condition that the rule shall test. I have set the condition to ” geoDevicePropSet.latitude > -90 ” so that this event always get triggered whenever the server receive latitude and longitude from a device.

(Hint: Entering a space in the If condition will give you a context dialog that enables you to select the right object or operator of the rule. By this way, you cannot enter an erroneous rule.)

 

6. Save and activate the rule.

 

 

 

 

Step 3) Push the Nodejs Server to the Cloud Foundry Environment.

We need a simple Nodejs server to test our actions. In this blog post, we will not cover how to push the nodejs server to the cloudFoundry environment. Here is the code of our Nodejs server.

( For only testing purpose, You can use your internal web server and expose the web server to the public internet by using ‘ngrok’ )

const express = require('express');
const fetch = require("node-fetch");
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.urlencoded( {extended : false } ));


app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))


app.post('/iotAction', (req,res) => {
    console.log("received data = ", req.body);
    res.json({
        "data": "received"
    })
});


app.get('/iotAction', (req, res) => {
    console.log("get triggered.")
    res.send("get triggered")
});

 

 

 

Step 4) Create Destination

1.We have to create a Destination to our Nodejs server to send a POST request. Open SAP Cloud Platform Cockpit and go to Connectivity > Destinations option. ( Make sure you are in the Cloud Foundry platform) and create destination by entering Name, Type, Server endpoint.

 

 

 

Step 5) Create Action to make POST request

1.On the launchpad, select the Actions tile

2. choose New to create a new action.

3. Enter Action Name and Select the Destination that you have created in the previous section. Enter value in the Email Information fields. Hint: By entering "${" + another letter(s), you will get a context menu with variables that you can use in the notification text. ( ${property_set_name.property_name } )

4. In the Trigger by field, select Event from Rule. In the Rule dropdown, select your Rule that you have created.The system populates Thing Type automatically.

 

Step 6) Invoke the Action by sending API Request.

1.By using a Postman, send measures value to SAP IoT Service.

2. If you watch your server logs, you will see the action was triggered and your server has received the values. ( For only testing purpose, You can use your internal web server and expose the web server to the public internet by using ‘ngrok’ )

 

 

 

 

Step 7) Generating OAuth token & Create a Spaces

1.A Geolocation Space represents the semantics such as geometry, related geolocations, and hierarchy of a geolocation. create space so we can use space id when we are generating the geolocation.

before we actually create a space let’s figure out how to get access token. Access token is needed for a security reason when we are handling geolocation APIs.

Install the latest version of the Postman and go to Authorization tab, select OAuth 2.0 Type and click “Get New Access Token

 

Access Token URL : https://<your tenant>.authentication.eu10.hana.ondemand.com/oauth/token

You can find your Client ID and Client Secret by following this steps.

 

 

2. Once you get the token successfully, click Use Token button in the bottom.

 

3. Let’s create a Space now.

Create POST request with this information.

( Make sure you have these specific roles-> Geolocation_Editor, Geolocation_Super_Editor )

 

https://<server address>/geolocation/v1/Spaces

header -> Content-Type : application/json

Auth: OAuth2.0

more details on Space creation

[
  {
    "Descriptions": [
      {
        "Label": "string",
        "Locale": "string"
      }
    ],
    "Geometry": {
      "Type": "string"
    },
    "ParentSpaceId": "string",
    "SpaceName": "string"
  }
]

 

We are going to make two spaces. One is United States and the other is Canada.

 

 

 

 

Step 8) Creating Geolocations

1.Let’s create Geolocations for US and Canada. Visit geojson io

In this website, you can easily create a Geojson format with a few of clicks.

 

2. I very roughly drew the polygon and retrieved the Geojson data.

 

3. Let’s Create Geolocation with the coordinates we got.

This method allows you to create a geolocation entry with details such as Name, Address, Description, Geometry, and Space. You can create single or multiple geolocations in the same call, and this method lets you create upto 20 geolocations in a single call.

Geolocation services support two Geometry Types:

  • Point

  • Polygon

Method: POST

https://<server address>/geolocation/v1/GeoLocations

header -> Content-Type : application/json

Auth: OAuth2.0

more details on Geolocation creation

Here is the sample Body that I have used for creating the Geolocation.
[
	{
	  	"Type": "Feature",
	  	"Properties": {
	  		"SpaceId": "SPACE_ID_THAT_YOU_HAVE_CREATED",
	  		"ExternalId": null,
	  		"GeoLocationName": "UnitedStates",
		    "ParentGeoLocationId": null,
			"Addresses": null,
	    	"Descriptions": [
		        {
		          "Label": "UnitedStates",
		          "Locale": "en"
		        }
		     ]
	    },
	    "Geometry": {
	      "type": "Polygon",
	      "coordinates": [
          [
            [
              -123.31054687499999,
              48.86471476180277
            ],
            [
              -124.892578125,
              39.977120098439634
            ],
            [
              -106.5234375,
              31.952162238024975
            ],
            [
              -81.38671875,
              25.799891182088334
            ],
            [
              -68.64257812499999,
              46.437856895024204
            ],
            [
              -82.79296874999999,
              40.84706035607122
            ],
            [
              -83.14453125,
              45.460130637921004
            ],
            [
              -95.09765625,
              48.69096039092549
            ],
            [
              -123.31054687499999,
              48.86471476180277
            ]
          ]
        ]
	    }
	}
]

Make sure to enter your space Id as a value of spaceId

(How to retrieve spaceId)

 

 

3. Repeat the same steps with Canada territory as well.

 

4. Once you have created both Geolocations for the US and Canada, you can see the list of your GeoLocations.

 

 

 

 

 

Step 9) GeoTest

GeoTest is used to perform geofencing tests on geo-coordinates or geolocation geometries. You can check things like the geolocations within the vicinity of a geolocation, or if any other geolocation is within the vicinity of a geolocation or geoposition, or if a geolocation is within a specified distance from a geoposition.

This means, we can check whether our device is located in US or not.

Method : GET

http://<server address>/geolocation/v1/GeoTest/Check/Within/GeoLocation

Auth: OAuth2.0

more details on GeoTest

 

You can check the presence of things within certain Geolocation by giving Latitude, Longitude, Geolocation Id, Distance as a parameter of your GET request.

 

You can test GeoTest function by giving geoLocation coordinates out side of US with the United States Geolocation ID. Then, it will tell you the presence of the thing within the US.

 

 

 

 

Step 10) Edit Nodejs server code

Okay, you may got a hunch how these whole things would be tied together. Let’s edit server side code and see the result.

 

1.Edit your Nodejs code like below.

app.post('/iotAction', (req,res) => {
    async function geoMatch(req){
        let latitude;
        let longitude;

        console.log("received data = ", req.body);
        latitude = req.body.geoDeviceLatitude;
        longitude = req.body.geoDeviceLongitude;
        

        
        let urlencoded = new URLSearchParams();
        urlencoded.append("grant_type", "client_credentials");
        urlencoded.append("response_type", "token");
        urlencoded.append("client_id", "sb-xxxxxx-e6b6-400d-8772-054b69282e76!b6001|iotae_service!b5");
        urlencoded.append("client_secret", "xxxxxxx+pk8cSxxxxxxBxjhEs=");

        let requestTokenOptions = {
        method: 'POST',
        headers: {'grant_type':'client_credentials'},
        body: urlencoded,
        redirect: 'follow'
        };

        // Requst Oauth2 Token
        let token = await fetch("https://xxxxxiotae.authentication.eu10.hana.ondemand.com/oauth/token", requestTokenOptions)
            .then(response => response.json())
            .then(json => { 
                console.log("token is ready = ", json.access_token);
                return json.access_token
            })
            .catch(error => res.status(500).json({ error: error.toString() }) );


        let requestOptions = {
            method: 'GET',
            headers: {"Authorization" : `Bearer ${token}`},
            redirect: 'follow'
        };

        let geoLocationId = 'xxxxx-05e3-47b4-81aa-0e9edcefd1e0'
        let distance = 0;

        // GeoTest GET request
        let geoMatchResult = await fetch(`https://sap-iot-noah-live-geolocation-runtime.cfapps.eu10.hana.ondemand.com/geolocation/v1/GeoTest/Check/Within/GeoPosition?Latitude=${latitude}&Longitude=${longitude}&GeoLocationId=${geoLocationId}&Distance=${distance}`, requestOptions)
            .then(response => {
                return response.json()
            })
            .then(result => {
                console.log("geoMatchResult = ", result);

                if(result.Within){
                    console.log("The customer is in the US")
                } else {
                    console.log("ALERT!!! Customer is outside of US");
                }

                return
            })
            .catch(error => console.log('error', error));
    }

    geoMatch(req);
    res.send("done")
});

 

2.Trigger the Action by sending measure values to the IoT Device.

 

3. See the result.

 

 

 

 

Conclusion

We saw how to monitor the location of the thing and creating alert based on the current location of the device by using rule, action, geoLocation, geoTest features.

Customers now can

  • Trigger Alert to the customer and their employee when the customer violate the geoFence rules.
  • Track location of their assets.
  • Charge by driving miles.

 

-All the images in the blog posts has generated by the author of this blog post-

 

Thank you.

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