Smart Car Parking -...

33
1 Smart Car Parking Accelerator DDM & LWM2M Setup

Transcript of Smart Car Parking -...

1

Smart Car Parking

Accelerator DDM & LWM2M Setup

2

3

Table of Contents

The APPIoT & LWM2M PoC .......................................................................................................... 1

1. General Information ...................................................................................................................... 4

1.1 Introduction .............................................................................................................................. 4

1.2 Hight level architect ................................................................................................................. 4

2. Setting up the Bootstrap Server with Security Settings ............................................................. 5

2.1 Bootstrap Server ...................................................................................................................... 5

2.2 Security Settings ....................................................................................................................... 7

3. Configuration for APPIoT ............................................................................................................ 8

3.1 Register a Gateway .................................................................................................................. 9

3.2 Register a device ..................................................................................................................... 11

3.3 Add Device Type to Smart Object ........................................................................................ 13

4. Eclipse Leshan .............................................................................................................................. 15

4.1 Leshan Installation and Development on Linux using Eclipse IDE .................................. 15

4.2 Leshan Installation and Development on Windows using Eclipse IDE ............................ 17

4.3 Developing LWM2M client using leshan-client-demo ........................................................ 20

4.3.1 Distance measurement project ....................................................................................... 20

4.3.2 Build and Run project .................................................................................................... 23

4.3.3 Verify the Client Connection and show data on chart ................................................ 24

5. Interfacing HY-SRF05 Ultrasonic Sensor with Raspberry Pi 3 Model B .............................. 25

6. APPIoT API used in web portal ................................................................................................. 26

6.1 Create API Key ...................................................................................................................... 26

6.2 Get the device network ID ..................................................................................................... 26

6.3 Get sensor’s ID ....................................................................................................................... 27

6.4 Get sensor’s data from APPIoT ............................................................................................ 28

7. Code ............................................................................................................................................... 29

4

M2M Device

Web Application

HTTPS

LWM2M

LWM2M

1. General Information

1.1 Introduction

A smart car parking is a system that helps drivers to find a vacant spot using the sensors in

each parking space by detecting the presence or absence of a vehicle.

1.2 Hight level architect

HY-SRF05

LWM2M Server

Raspberry Pi 3

M2M APPIoT

LWM2M Client

5

Smart Car Parking is designed with HY-SRF05 Ultrasonic sensors which measure distance.

All sensors integated to Raspberry Pi 3 Model B board. The sensor’s data will send to APPIoT via

LWM2M protocol.

Smart Car Parking system include web application. We can monitor all with chart

visualization from web.

2. Setting up the Bootstrap Server with Security Settings

This section describes the steps to setup a Bootstrap Server with Security Settings.

Note: The section is only valid if you have direct access to the bootstrap server. In most

cases the setup of the bootstrap server is done via the AppIoT/DDM-application when

registering a device.

2.1 Bootstrap Server

- Please go to the URL: http://customerxxx-demo-lwm2m-bootstrap-

server.XXX.cloudapp.azure.com:8080/

- Click on the “Add new client bootstrap configuration” button

- Provide the Client endpoint , Identity and Key

6

7

Example:

Client endpoint: tma_iot

Identity: raspberrypi3

Key (secret in hexadecimal): 37373737 (7777 ASCII)

- Click on Create button to save the setting

2.2 Security Settings

- Please go to the URL: http://customerxxx-appiot-lwm2m-

server.XXX.cloudapp.azure.com:8080/#/security

- Click on the “Add new client security configuration” button

- Provide the Client endpoint , Identity and Key

- Click on Create button to save the setting

8

3. Configuration for APPIoT

- Please go to the URL: https://customerxxx.sensbysigma.com/#/ (use Google Chrome browser)

- Click on Sign in button

- Enter username, password and click on Sign in Button (You need register a account before)

If you have successful log in, you will see APPIoT Dashboard as follows:

9

3.1 Register a Gateway

- Please click on Register Gateway button to create a new Gateway of the type LWM2M-GW

- Provide the Serial Number and Gateway Type

10

Example:

Serial Number: 12345678

Gateway type: LwM2M Gateway

- Click on Continue button

- Enter name of Gateway

Example:

Name: CarParkingGateway

- Click on Register button to save the setting

- Click on CarParkingGateway link button

11

- Setting Category: LwM2MServer, click on Edit button for the setting category

- Insert URL: coaps://customerxxx-appiot-lwm2m-server.XXX.cloudapp.azure.com:5684

Note: If the setting category is not present on the GW, click Action and add this to the GW.

- Click Save button to save the setting

3.2 Register a device

- Please click on Register Device button to create a new Device

12

- Provide the Name, Device Identifier (endpoint), Device Type, Template, Gateway,

Bootstrap Server, Identity and preSharedKey

13

Example:

Name: CarpParkingDevice

Device Identifier (endpoint): tma_iot

Device Type: select the “DevLwM2mWithPSK”

Template: Default

Bootstrap Server: select the “DEMO_BOOTSTRAP_2”

Identity: raspberrypi3 (must be same as Bootstrap Device Identity)

preSharedKey: 7777 (must be same as Bootstrap Secret Key in ASCII)

- Click on Register button to register the device

- Verify LWM2M server connection to Bootstrap by refresh URL:

http://customerxxx-demo-lwm2m-bootstrap-server.japanwest.cloudapp.azure.com:8080/

3.3 Add Device Type to Smart Object

After registering device, we need add Device Type to Smart Object. In this document, we

do an example to measure the distance with HY-SRF05 Ultrasonic sensor and Raspberry Pi 3

Model B. So we need add a device Distance to Smart Object from Device Type.

- Click on the Device Type link button

- Click on Add Smart Object Type button

14

- Select Distance(3330) and click on Add button

- Click on Save button to save the setting

The Distance device have added to Smart Objects

15

4. Eclipse Leshan

We have used the leshan client to connect the smart objects with APPIoT. Please follow the

following steps to connect the device using leshan client framework with APPIoT. The following

steps to be followed to connect the client with the APPIoT platform.

4.1 Leshan Installation and Development on Linux using Eclipse IDE

Apache Maven 3.3.9 (or higher) and JDK8 (or higher) have been installed on the Ubuntu

and their directory have been set to the PATH environment variable during the shell launch

(.bashrc) and therefore can be called from any location.

Version of Maven and Java Development Kit

- Download and install Eclipse IDE for Java EE developer from URL:

http://www.eclipse.org/downloads/ (This document use Eclipse Oxygen)

- Download the zip distribution of eclipse/leshan version 1.0 from URL:

https://github.com/eclipse/leshan

- Extract the zip file in to the Eclipse Workspace directory

- Open Eclipse and import the Leshan project to Eclipse by accessing

File > Import> Maven > Existing Maven Projects and specify the directory of the project in the

Eclipse Workspace folder

16

- Add jre8 to the Installed JREs menu in Window > Preferences > Java > Installed JREs, and set

jre8 as default execution environment

- You need to add the M2_REPO to your java classpath variables. To do that you can execute the

following command:

mvn -Declipse.workspace=<path-to-eclipse-workspace> eclipse:eclipse:configure-

workspace

- An eclipse restart is needed (if you already have it open).

- You can also do that inside eclipse: From the menu bar, select Window > Preferences. Select

the Java > Build Path > Classpath Variables page.

- Now, you need to eclipsify leshan java projects, so run: mvn eclipse:eclipse

17

- Leshan project after importing into Eclipse

4.2 Leshan Installation and Development on Windows using Eclipse IDE

You do the same things on Linux, but only different in setting up enviroment variables for

Java and Maven.

- Set up JAVA environment variables (for Windows 8 and Windows 10)

1. Make sure JDK is installed

2. Open Advanced system settings link.

3. Click Environment Variables.

18

4. In System variables, add a new JAVA_HOME variable and point it to the JDK installed

folder.

5. In System variables, find PATH, clicks edit and append this %JAVA_HOME%\bin

to the end

19

- Set up MAVEN environment variables (for Windows 8 and Windows 10)

1. Download Apache Maven from link http://maven.apache.org/download.cgi

2. Unzip it to the folder you want to install Maven (Ex: C:\Program Files\apache-maven-

3.5.0)

3. Add both M2_HOME and MAVEN_HOME variables in the Windows environment,

and point it to your Maven folder

4. Update PATH variable, append Maven bin folder %M2_HOME%\bin.

5. Done, to verify it, run mvn –version in the command prompt.

20

4.3 Developing LWM2M client using leshan-client-demo 4.3.1 Distance measurement project

- Open leshan-client-demo project: a sample of LWM2M client

- In the leshan-client-demo project, three object classes are created: MyDevice.java,

MyLocation.java and RandomTemperatureSensor.java. You can use one of these classes as a

template for your new objects.

- In the package org.eclipse.leshan.client.demo, we create new classes with name

“DistanceSensor.java” (view code in section 7) with some functions such as:

Function name Description

public DistanceSensor()

Construction function use to initialize

variables, pin modes, set schedule to read

sensor’s data and post to APPIoT

private synchronized void adjustDistance()

Read sensor’s data from HY-SRF05 Ultrasonic

sensor

private double getTwoDigitValue(float value)

Round number, takes only two decimal

public synchronized ReadResponse read(int resourceId)

Return min, max, current value of sensor’s

data; min range, max range value, sensor unit

public synchronized ExecuteResponse execute(int resourceId, String params)

Executing commands reset min max value

from user

private Integer adjustMinMaxMeasuredValue(float newDistance)

Adjust min max measured value

21

private void resetMinMaxMeasuredValues()

Reset min max measured value

- Please go to the URL: http://pi4j.com/download.html

- Add Pi4j library version 1.2 (Java I/O library for the Raspberry Pi) dependency in pom.xml

file of leshan-client-demo projects (view code in section 7)

- Please go to the URL:

http://www.openmobilealliance.org/wp/OMNA/LwM2M/LwM2MRegistry.html.

- Download 3330.xml file

- Copy 3330.xml file and past in package src/main/resources/models

- Open LeshanClientDemo.java file and initialize the DistanceSensor objects such as

22

23

4.3.2 Build and Run project

- Right click on leshan-client-demo project > Run as > Maven build

- Type clean install in the Goals text box

- After successful build, 3 .jar files are created

Caution:

On windows, you may get some errorrs when building the project. So, you open pom.xml

file in leshan folder find and disable leshan-integration-tests module, after building again.

- Copy leshan-client-demo-1.0.0-SNAPSHOT-jar-with-dependencies.jar to raspberry

- Make sure JDK have been installed on the Raspberry and their directory have been set to the

PATH environment variable during the shell launch (.bashrc)

- Run the client demo jar with the following options:

java -jar leshan-client-demo-1.0.0-SNAPSHOT-jar-with-dependencies.jar -u customerxxx-

demo-lwm2m-bootstrap-server.japanwest.cloudapp.azure.com:5684 -n tma_iot -i

raspberrypi3 -p 37373737 -b

Where:

➢ customerxxx-demo-lwm2m-bootstrap-server.japanwest.cloudapp.azure.com:5684 is

the bootstrap Server URL (DEMO_BOOTSTRAP_2) with PSK security

➢ tma_iot is the endpoint

➢ raspberrypi3 is the PSK Device Identity

24

➢ 37373737 is PSK key in Hex (7777 ASCII)

➢ -b option for bootstrapping

4.3.3 Verify the Client Connection and show data on chart

Once the configuration of LWM2M client is completed verify the connection by

monitoring the smart object resource values in APPIoT portal. Below snapshot showing the

Distance sensor value being read from the HY-SRF05 Ultrasonic sensor connect with

Raspberry Pi 3 Model client.

On Raspberry On LWM2M Server

On APPIoT On Web Application

25

5. Interfacing HY-SRF05 Ultrasonic Sensor with Raspberry Pi 3 Model B

Thera are four pins on the HY-SRF05 ultrasonic module that are connected to the Raspberry Pi

3 Model B.

Raspberry Pi 3 Model B HY-SRF05

5V (pin 4) ----------------------------------- Vcc

GND (pin 20) --------------------------------- GND

GPIO 0 (pin 11) --------------------------------- Trig

GPIO 2 (pin 13) --------------------------------- Echo

26

6. APPIoT API used in web portal

Web portal will GET sensor's data from APPIoT and display on bar charts. Get Sensor’s data

via https get with configuration as below:

6.1 Create API Key

- Please go to APPIoT: https://customerxxx.sensbysigma.com/#/

- Create API key by accessing Settings > ApiKeys

- Click on Create button

- Provice the Name

- Click on Save button to save the setting

6.2 Get the device network ID

- Click on user icon and select about

27

- In about form you will see Current Device Network ID

6.3 Get sensor’s ID

- Click on sensor value of Distance in Smart Object

- From URL in browser you can see ID of sensor value

28

6.4 Get sensor’s data from APPIoT

var baseUrl = "https://customerxxx-api.sensbysigma.com/";

var authorization = "<For Security Remove: Replace your Base64 String>";

var deviceNetwork = "d74ab707-b8fb-420e-a56a-4aca544a1912";

var sensorID = "c8f3a3d5-b26e-45b3-a220-9bd33739a587";

//Header for getting sensor's data

var requestHeader = {

url: baseUrl + ' api/v3/resources/' + sensorID,

method: 'GET',

headers: {

'Authorization': authorization,

'X-DeviceNetwork': deviceNetwork

}

};

//And we have to authorize via https header and get data to display on bar chart as below:

$http(requestHeader).success(function(data) {

if ((data != null) && (data.LatestMeasurement.v != undefined)) {

barEvent("#bar_distance", parseFloat(data.LatestMeasurement.v));

} else {

console.log("Distance value incorrect");

}

}).error(function(error) {

console.log("Error: " + error);

});

29

7. Code

- Class DistanceSensor.java

import java.math.BigDecimal;

import java.math.RoundingMode;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

import org.eclipse.leshan.client.resource.BaseInstanceEnabler;

import org.eclipse.leshan.core.response.ExecuteResponse;

import org.eclipse.leshan.core.response.ReadResponse;

import org.eclipse.leshan.util.NamedThreadFactory;

import com.pi4j.io.gpio.GpioController;

import com.pi4j.io.gpio.GpioFactory;

import com.pi4j.io.gpio.GpioPinDigitalInput;

import com.pi4j.io.gpio.GpioPinDigitalOutput;

import com.pi4j.io.gpio.PinPullResistance;

import com.pi4j.io.gpio.RaspiPin;

public class DistanceSensor extends BaseInstanceEnabler {

private static final Float UNIT_DISTANCE = 0.0f;

private static final int SENSOR_VALUE = 5700;

private static final int SENSOR_UNIT = 5701;

private static final int MIN_MEASURED_VALUE = 5601;

private static final int MAX_MEASURED_VALUE = 5602;

private static final int MIN_RANGE_VALUE = 5603;

private static final int MAX_RANGE_VALUE = 5604;

private static final int RESET_MIN_MAX_MEASURED_VALUES = 5605;

private static final String CALIBRATION = "Calibration";

private static final int CURENT_CALIBRATION = 5821;

private static final String APPLICATION = "Car Parking";

private static final int APPLICATION_TYPE = 5750;

private final ScheduledExecutorService scheduler;

private float MIN_VALUE = 2.0f;

private float MAX_VALUE = 400.0f;

private float currentDistance = 0.0f;

private float minMeasuredValue = MAX_VALUE;

private float maxMeasuredValue = MIN_VALUE;

// Connect HY-SRF05 with Raspberry Pi3 Model B

// HY-SRF05==============Raspberry Pi3 Model B

// VCC===================5V (Pin 02)

// GND===================GND (Pin 04)

// Trigger===============GPIO_00 (Pin 11)

// Echo==================GPIO_02 (Pin 13)

// GPIO Pins

private GpioPinDigitalOutput sensorTriggerPin;

private GpioPinDigitalInput sensorEchoPin;

private GpioController gpio = GpioFactory.getInstance();

public DistanceSensor() {

sensorTriggerPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00);

sensorEchoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

this.scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Distance

Sensor"));

scheduler.scheduleAtFixedRate(new Runnable() {

30

@Override

public void run() {

adjustDistance();

}

}, 10, 2, TimeUnit.SECONDS);// delay 2 seconds

}

/**

* Function adjust distance

*/

private synchronized void adjustDistance() {

try {

Thread.sleep(100);

// Make trigger pin HIGH

sensorTriggerPin.high();

// Delay for 10 microseconds

Thread.sleep((long) 0.01);

// Make trigger pin LOW

sensorTriggerPin.low();

while (sensorEchoPin.isLow()) {

// Wait until the ECHO pin gets HIGH

}

// Store the current time to calculate ECHO pin HIGH time.

long startTime = System.nanoTime();

while (sensorEchoPin.isHigh()) {

// Wait until the ECHO pin gets LOW

}

// Store the echo pin HIGH end time to calculate ECHO pin HIGH time.

long endTime = System.nanoTime();

currentDistance = (float) ((((endTime - startTime) / 1e3) / 2) / 29.1);

System.out.println("Distance: " + currentDistance);

Integer changedResource = adjustMinMaxMeasuredValue(currentDistance);

if (changedResource != null) {

fireResourcesChange(SENSOR_VALUE, changedResource);

} else {

fireResourcesChange(SENSOR_VALUE);

}

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

/**

* Function round number

* @param value

* @return

*/

private double getTwoDigitValue(float value) {

BigDecimal toBeTruncated = BigDecimal.valueOf(value);

return toBeTruncated.setScale(2, RoundingMode.HALF_UP).doubleValue();

}

31

@Override

public synchronized ReadResponse read(int resourceId) {

switch (resourceId) {

case MIN_MEASURED_VALUE:

return ReadResponse.success(resourceId, getTwoDigitValue(minMeasuredValue));

case MAX_MEASURED_VALUE:

return ReadResponse.success(resourceId, getTwoDigitValue(maxMeasuredValue));

case SENSOR_VALUE:

return ReadResponse.success(resourceId, getTwoDigitValue(currentDistance));

case SENSOR_UNIT:

return ReadResponse.success(resourceId, UNIT_DISTANCE);

case MIN_RANGE_VALUE:

return ReadResponse.success(resourceId, MIN_VALUE);

case MAX_RANGE_VALUE:

return ReadResponse.success(resourceId, MAX_VALUE);

case APPLICATION_TYPE:

return ReadResponse.success(resourceId, APPLICATION);

case CURENT_CALIBRATION:

return ReadResponse.success(resourceId, CALIBRATION);

default:

return super.read(resourceId);

}

}

@Override

public synchronized ExecuteResponse execute(int resourceId, String params) {

switch (resourceId) {

case RESET_MIN_MAX_MEASURED_VALUES:

resetMinMaxMeasuredValues();

return ExecuteResponse.success();

default:

return super.execute(resourceId, params);

}

}

/**

* Function adjust min max measured value

* @param newDistance

* @return

*/

private Integer adjustMinMaxMeasuredValue(float newDistance) {

if (newDistance > maxMeasuredValue) {

maxMeasuredValue = newDistance;

return MAX_MEASURED_VALUE;

} else if (newDistance < minMeasuredValue) {

minMeasuredValue = newDistance;

return MIN_MEASURED_VALUE;

} else {

return null;

}

}

/**

* Function reset min max measured values

*/

private void resetMinMaxMeasuredValues() {

minMeasuredValue = currentDistance;

maxMeasuredValue = currentDistance;

}

}

32

- Add Pi4j library version 1.2 dependency in pom.xml file of leshan-client-demo projects

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.eclipse.leshan</groupId>

<artifactId>leshan</artifactId>

<version>1.0.0-SNAPSHOT</version>

</parent>

<artifactId>leshan-client-demo</artifactId>

<name>leshan - client demo</name>

<description>A demonstration client built upon the Leshan client.</description>

<!-- To download SNAPSHOT builds in your Maven project, you must include the following repository

definition in your POM.XML file -->

<repositories>

<repository>

<id>oss-snapshots-repo</id>

<name>Sonatype OSS Maven Repository</name>

<url>https://oss.sonatype.org/content/groups/public</url>

<snapshots>

<enabled>true</enabled>

<updatePolicy>always</updatePolicy>

</snapshots>

</repository>

</repositories>

<dependencies>

<dependency>

<groupId>org.eclipse.leshan</groupId>

<artifactId>leshan-client-cf</artifactId>

</dependency>

<dependency>

<groupId>commons-cli</groupId>

<artifactId>commons-cli</artifactId>

</dependency>

<!-- The following dependency is all that is needed to include Pi4J (core library) in your Maven

project -->

<dependency>

<groupId>com.pi4j</groupId>

<artifactId>pi4j-core</artifactId>

<version>1.2-SNAPSHOT</version>

</dependency>

<!-- runtime dependencies -->

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-simple</artifactId>

<scope>runtime</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-assembly-plugin</artifactId>

<version>2.4</version>

<configuration>

<archive>

<manifest>

<mainClass>org.eclipse.leshan.client.demo.LeshanClientDemo</mainClass>

33

</manifest>

</archive>

<descriptorRefs>

<descriptorRef>jar-with-dependencies</descriptorRef>

</descriptorRefs>

</configuration>

<executions>

<execution>

<id>make-assembly</id> <!-- this is used for inheritance merges -->

<phase>package</phase> <!-- bind to the packaging phase -->

<goals>

<goal>single</goal>

</goals>

</execution>

</executions>

</plugin>

</plugins>

</build>

</project>