Skip to Content
Technical Articles

Smart Parking – SAP Leonardo – Internet of things

Introduction

**Pre – requisite:

Understanding What is IoT ( Internet of things ) and What is SAP Cloud foundry

**

This blog is about how SAP Leonardo – Internet of things is used to resolve a real time problem – Parking system in the metro city(or smart city) .

Considering the various case Studies and POCs ( like Smart Coffee Machine( Wouter Lemaire ),Temperature sensing etc. ) I choose to pick one real problem statement which we face in our daily life

” Where is the Parking Space !! ” Many people spend alot of time in search of parking when they are in metro cities and mostly ends on either parking really far from the destination and  burning unnecessary fuels .. It is more prominent now in Business Parks where Employees are in hurry to rush to office but kill time in searching for Parking slot

 

Current Solution provider (AS – IS)

There are some Car Parking Space ,which makes this task a bit easy ( like AAA Parking in USA ) but even they do not provide real time availability of slot in the parking space and mostly mechanics requires a manual interruption , this causing loss of real time data, inaccuracy in managing the vacant space , and more over Tag in and tag out ( in time and out time ) of the vehicle is different when compares to the real time data .

In the growing world we are almost struggling to find the parking space , Weather it is a shopping mall,Hospital,Office or a College.

 

Growing in Smart city era  – how about a smart parking ?

 

SAP Leonardo – Internet of Things Solution (To – Be)

As we are growing towards Smart City (most of city already started), using the cloud solution from SAP, we will be bringing all the parking space (from mall, hospital, Co-operate offices) under one umbrella, and show the user where the parking space is available nearby.

 

So what we are going to know/understand from this blog –

  1.  Smart Parking System is an integrated system to make efficient use of parking space for vehicles using sensors to identify the empty space and notify user(s).
  2. Using SAP Cloud foundry (neo trail account) and low cost IoT sensor programmed using micro python.
  3. Agenda is to help drivers/people to make parking easy and leverage the payment methods effectively.

 

This complete setup is divided below points

  1. he edge sensors (Ultra sonic), present at the edge locations sending real time data. These units will be located at every slot in the parking lot (on floor/pillars/walls).
  2. All sensors will be connected to the programmable transmitter ESP8266.
  3. ESP8266 will send published data using MQTT protocol to the SAP IoT service.
  4. Server will authenticate the incoming message and prepare it for publishing.
  5. Authentication will be done for SAP service using OAuth Token. Token is pre-configured in the Server.
  6. The Data will be publishing to SAP Rest endpoint.
  7. Sync response will be received, and confirmation message will be processed.

Below is the step by step process how we build this solution and the how we implemented it.

  1. Smart Parking Overview
  2. How we start building – Setup requirement/Pre-requisites
  3. Parking sensors installation and data transfer via MQTT
  4. SAP Leonardo setup – Account creation, Database etc. – IoT cockpit
  5. SAP Analytics – UI5 application
  6. What we did till now and what is next?

 

  1. Smart Parking Overview:
  • Sensors are configured on the Machine/ Equipment etc.
  • These sensors are connected to Node MCU physically either by wire or soldering on the Node MCU.
  • Node MCU use MQTT service to send data to the raspberry pi
  • Raspberry pi push the data into the SAP via APIs
  • SAP –IoT integration is done with inbuilt feature of SAP Cloud- IoT Service
  • Once the data is inside the SAP, Dashboards are created

Data flow diagram of our setup

2.How we start building – Setup requirement/Pre-requisite

We use NodeMCU (ESP8266) ,a micro-controller chip , it includes on-board Wi-Fi. sensors are connected to this NodeMCU . 

Pre-requisite to use NodeMCU  – 

Why MicroPython?

Python is one of the most widely used, simple and easy-to-learn programming languages around. So, the emergence of MicroPython makes it extremely easy and simple to program digital electronics. If you’ve never programmed digital electronics before, MicroPython is a good starting point.

I’m using the esp8266-12 version board. To install micropython you will need esptool you will need to download and install python and pip, to install the esptool.

Run the below command on a terminal or cmd to install esptool

pip install esptool

Next you can visit micropython website and download the latest firmware for the esp8266, after downloading it open up a terminal in the same directory as the firmware file and then run the below command

esptool.py –port /dev/ttyUSB0 erase_flash

esptool.py –port /dev/ttyUSB0 –baud 460800 write_flash –flash_size=detect 0 esp8266-xxxxx-vxxxx.bin

You will need to change the port based on you PC.

After this you should have successfully installed micropython.

3. Parking sensors installation and data transfer via MQTT

We divide this into two parts. First is the primary sensor coding, where we define our requirement , when and what information we need and second is the MQTT sensor coding , to transfer the data into SAP

Sensor code : 
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import utime
import time
import json
import machine
import network
from umqtt.robust import MQTTClient
from hcsr04 import HCSR04

sensor1 = HCSR04(trigger_pin=5, echo_pin=4, echo_timeout_us=10000)
sensor2 = HCSR04(trigger_pin=14, echo_pin=12, echo_timeout_us=10000)

machine.Pin(13, machine.Pin.OUT).off()
machine.Pin(15, machine.Pin.OUT).off()

#################
def blinkLed(number):
led = machine.Pin(number, machine.Pin.OUT)
for i in range(3):
led.on()
time.sleep(0.5)
led.off()
time.sleep(0.5)

###############
def TaskTwo():
blinkLed(13)
changeStatus2 = False
while True:

machine.Pin(13, machine.Pin.OUT).on()
print("Slot 2 thread running")
distance2 = sensor2.distance_cm()
machine.Pin(13, machine.Pin.OUT).off()

if distance2 > 1 and distance2 < 10:
if not changeStatus2:
currentTime = time.time()
send_Two("BLOCK")
changeStatus2 = True
print('object in Slot 2 at:', distance2, 'cm')
else:
if changeStatus2:
send_Two("RELEASE")
changeStatus2 = False
yield None

utime.sleep(2)

def send_Two(t):
print('Slot 2 thread : sending message', t)
payload = {"Slot": "2", "status": t}

sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('No network conencted , connecting to network...')
sta_if.active(True)
sta_if.connect('RailWire1', '8drowssap')
while not sta_if.isconnected():
pass

c = MQTTClient('send_Two', 'iot.eclipse.org')
c.connect()
c.publish('aaaparking/Slotsensor', json.dumps(payload))
blinkLed(13)
print('Slot 2 thread : message sent')
c.disconnect()

#################
def send_One(t):
print('Slot 1 thread : sending message', t)
payload = {"Slot": "1", "status": t}

sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('No network conencted , connecting to network...')
sta_if.active(True)
sta_if.connect('RailWire1', '8drowssap')
while not sta_if.isconnected():
pass
c = MQTTClient('send_One', 'iot.eclipse.org')
c.connect()
c.publish('aaaparking/Slotsensor', json.dumps(payload))
blinkLed(15)
print('Slot 1 thread : message sent')
c.disconnect()

def TaskOne():
blinkLed(15)
changeStatus1 = False
while True:

machine.Pin(15, machine.Pin.OUT).on()
print("Slot 1 thread : running")
distance1 = sensor1.distance_cm()
machine.Pin(15, machine.Pin.OUT).off()
if distance1 > 1 and distance1 < 10:
if not changeStatus1:
currentTime = time.time()
send_One("BLOCK")
changeStatus1 = True
print('object in Slot 1 at :', distance1, 'cm')
else:
if changeStatus1:
send_One("RELEASE")
changeStatus1 = False
yield None

utime.sleep(2)

#################

TaskQueue = [TaskOne(), TaskTwo()]

while True:
for task in TaskQueue:
next(task)

2. MQTT Code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import machine
import time
import urequests
import json
import network
from umqtt.robust import MQTTClient


print("main class running")

url = "https://iotmmsp1942289005trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/2fb8bd57-78d4-4027-a204-6801009e6c9c"
headers = {'Authorization': 'Bearer ' + '711f4cdfd921cecc225f2f518ed2294',
'content-type': 'application/json;charset=utf-8'}
machine.Pin(13, machine.Pin.OUT).off()
machine.Pin(12, machine.Pin.OUT).off()

machine.Pin(5, machine.Pin.OUT).off()
machine.Pin(4, machine.Pin.OUT).off()


#################
def blinkLed(number):
led = machine.Pin(number, machine.Pin.OUT)
for i in range(3):
led.on()
time.sleep(0.5)
led.off()
time.sleep(0.5)


#################
def callback(topic, message):
print(topic, message)
d = {}

if topic == b'aaaparking/Slotsensor':
try:
d = json.loads(message)
except:
print("exception in reading json message")

if d['Slot'] and d['Slot'] == '1':
currentTime = time.time()
if d['status'] == "BLOCK":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":1, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"BLOCK", currentTime, 0, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 1 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'BLOCK_ONE')
if d['status'] == "RELEASE":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":1, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"RELEASE", 0, currentTime, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 1 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'RELEASE_ONE')
print("Slot 1 callback completed")

elif d['Slot'] and d['Slot'] == '2':
currentTime = time.time()
if d['status'] == "BLOCK":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":2, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"BLOCK", currentTime, 0, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 2 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'BLOCK_TWO')
if d['status'] == "RELEASE":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":2, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"RELEASE", 0, currentTime, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 2 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'RELEASE_TWO')
print("Slot 2 callback completed")

#################

elif topic == b'aaaparking/Slotsensor/ack':
if message == b'BLOCK_ONE':
print('MQTT thread : ack received : BLOCK_ONE ')
machine.Pin(13, machine.Pin.OUT).on() # because of RGB used, need to change

elif message == b'RELEASE_ONE':
print('MQTT thread : ack received : RELEASE_ONE ')
machine.Pin(13, machine.Pin.OUT).off()

elif message == b'BLOCK_TWO':
print('MQTT thread : ack received : BLOCK_TWO ')
machine.Pin(12, machine.Pin.OUT).on()

elif message == b'RELEASE_TWO':
print('MQTT thread : ack received : RELEASE_TWO ')
machine.Pin(12, machine.Pin.OUT).off()

#################

sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('No network conencted , connecting to network...')
sta_if.active(True)
sta_if.connect('RailWire1', '8drowssap')
while not sta_if.isconnected():
pass


print("Connecting to client...")
client = MQTTClient("receive", 'iot.eclipse.org')
client.set_callback(callback)
client.connect()
print("Client Connected")
blinkLed(5)
client.subscribe('aaaparking/Slotsensor/ack')
client.subscribe('aaaparking/Slotsensor')

while True:
machine.Pin(5, machine.Pin.OUT).on()
print("MQTT thread running")
client.check_msg()
machine.Pin(5, machine.Pin.OUT).off()
time.sleep(4)

4.SAP Leonardo setup – Account creation, Database etc. – IOT cockpit

How to create an account in SAP Cloud and activate the IoT service along with creation of database is very well explained in many blogs.

Below are few famous blogs on step by step how to create SAP account and activate service –

  1. Get started with SAP CL 
  2. Introduction to SAP CL
  3. Some more information on SAP CL
  4. Enable IoT Service and Cloud account Enable and configure  –  Follow this link you will be able to do configuration successfully.
  5. Or can see the blogs from famous Bloggers on IoT such ,Sharadha K ,Fabian Lehmann . they had explain very well on building the scenarios.

Below are the  few screenshots what we have done on configuration side –

 

Once you are done with the setup of your account , and you build your scenario requirement in your IOT cockpit we are ready to build the dashboard now .

5. SAP Analytics – UI5 application

Thanks to Mr. Ankit ( Ankit Garg ) Co Author , for building the UI interface for this scenario  .

Once data is saved in HANA Table, it is ready to be shown in a SAPUI5 Application. SAPUI5 is framework to design client-side applications.

First we will create a XSOData service on top of HANA Table. This will act as a Web Service containing Metadata information about HANA Table.

Then this service will be consumed in an SAPUI5 Application which can be rendered on Mobile/Desktop/Tablet etc. User can easily see the availability of parking slot on their mobile devices on just a tap.

The End User Interface will look something like below:

 

 

6. What we did till now and what is next ?

So, now we have seen one end to end scenario on how SAP Leonardo helps in bringing the smart city /smart parking solution, it is time to get into the payment area via creating a Payment gate, using either a tag in/ check in or

Payment mode : the complete payment method can be made via mobile ( like an android/iOS mobile app ) the normal payment method we use in Google Pay or Wallet Pay .

Parking booking/Confirmation : Based on the space available ( again the real data from the parking space) you can simply book your parking space , and drive way easy into it without any hurdle or problem as parking reservation was already made .

Secondly if any car is parked for more time, you can always set an alert or send notification to the specific person

Directions/Better UI : Using Google map/ or sap web UI interface , it is possible to see the complete parking structure and the direction from your location to parking space.User will get the real time information on the parking space.

 

 

Please feel free to drop your comments below.

Be the first to leave a comment
You must be Logged on to comment or reply to a post.