Data- and Service-Centric Orchestration of the Internet of Things - - PDF document

data and service centric orchestration of the internet of
SMART_READER_LITE
LIVE PREVIEW

Data- and Service-Centric Orchestration of the Internet of Things - - PDF document

Data- and Service-Centric Orchestration of the Internet of Things Overview Sheet Table of Contents: Tutorial: Overview Video Walkthrough Emulated IoT device Idea of the Game Goals/Steps of the Tutorial Virtual Machine overview Installed


slide-1
SLIDE 1

Data- and Service-Centric Orchestration

  • f the Internet of Things

Overview Sheet Table of Contents:

Tutorial: Overview Video Walkthrough Emulated IoT device Idea of the Game Goals/Steps of the Tutorial Virtual Machine overview Installed software Folder Structure Code Structure Starting services/agents from binaries Interacting with the VSL using the console service Tutorial TLDR Tutorial: The different steps Part 1: Overlay and Services Task 1: Start a knowledge KA and observe its initial messages Task 2: Start a second KA and and see what both agents exchange. Task 3: Start the gatewayService.jar Task 4: Use the console service to check the result Task 5: Stop everything Part 2: Building a devices digital twin as context model Task 1: Complete the context model of the board Gateway service Task 2: Complete the playercontrol context model Task 3: Play the game Task 4: Stop everything Part 3: Building the game logic and mashing up services Task 1: Complete the subscriptions and VirtualNode registrations of the Gateway Task 1.1: Complete subscriptions of the Gateway Task 1.2: Complete the virtual node registrations of the Gateway Task 2 (optional): Test if your code is working

slide-2
SLIDE 2

Task 3: Complete the orchestration logic Task 4: Test if your logic works! Task 5: Stop everything Part 4: Security Task 1: Check how secure the access to the secretKey currently is: Task 2: Update the model of the monitor service Task 3: Try accessing the secretKey node again Tutorial: Closing words VSL Java Cheatsheet Solution Part 3: BoardGateway.java GameControlServiceHandler.java

Tutorial: Overview

In this tutorial we will use the VSL to ​mash up different services in order to build a small game integrating an emulated IoT device.

Video Walkthrough

You can find a video walkthrough to follow along here: Intro: ​https://www.youtube.com/watch?v=wxcWGZDXfuw Walkthrough: ​https://www.youtube.com/watch?v=p4v8nmS0hco

Emulated IoT device

For that purpose we prepared an ​emulated IoT device offering different resources like leds and

  • buttons. The device can be controlled (send commands, request state) using CoAP. This part is

already fully implemented by us. When started, a new window is opened and the device is shown in figure 1.:

slide-3
SLIDE 3

Figure 1: The user interface of the emulated device The screen is split in two sides, one side for each player:

  • Each player has a ​button​ that can be pressed, which is mapped to a​ key on your

keyboard​. In the case of Player 1 this is “​D​” for Player 2 it is “​J​”.

  • Next to it we have a ​green led​. If the button/key the according player is pressed, the

device turns the lamp automatically on (as shown for Player 1). Otherwise the led is off (as shown for Player 2).

  • Finally towards the center each player has a ​red led​, which is required for the game. In

the image that led is currently off for both players. Finally we also have a single​ ​blue​ “​alarm​” ​led​ in the top center of the emulated device.

Idea of the Game

On its own the emulated device is rather dumb. The only thing it does is checking whether you press the D and/or J buttons and then turns on the respective players ​green LED. Not much of a fun game so far. What we actually want to have in the end is a little game that ​starts when both keys are pressed​ at the same time. 1. If this is the case, the ​blue​ alarm led should turn on to indicate the game is started. 2. Then, after a random amount of time, one players ​red LED should light up​. The according player than has to take his finger of his key as fast as possible (but not before the led lights up!).

slide-4
SLIDE 4

3. Another random delay later, the other players ​red led should light up and he has to take his finger of the key. 4. The emulated device can then be queried for the ​time it took both players to react after their​ ​red​ led ​turned on​. 5. Based on those times we can calculate the winner (who was faster?) and display it on the device using the leds.

Goals/Steps of the Tutorial

The different steps of this tutorial is as follows: 1. Get familiar with the VSL and how the game works​. Afterwards you are provided with a skeleton code of services and models for the game and have to complete it on your

  • wn.

2. Create a ​context model​ for the VSL that describes the capabilities of the smart device 3. Create a ​gateway service​ that connects the device to the VSL using the context model. 4. Create an orchestration service that implements the logic of the game. For this purpose it has to: a. Interact with the gateway service to get/set the current state of the emulated device b. Report the results​ of the game to a ​leaderboard service c. Report the (relevant) interactions​ with the VSL to a ​monitor service 5. Have a brief look at the ​access control​ features offered by the VSL. The leaderboard and monitor services are already finished and can be used as they are. The Gateway and orchestration services are provided as ​skeleton code​ with ​TODOs​ on the relevant parts.

Virtual Machine overview

Installed software

The Virtual Machine runs lubuntu as lightweight ubuntu alternative. In case you need username or password (e.g. for sudo):

  • Username: ​im
  • Password: ​im

When you start the VM, you will find all required shortcuts on the desktop:

  • Eclipse​: The IDE to work on the coding tasks
  • Firefox​: To display the leaderboard and join our irc channel for questions.
slide-5
SLIDE 5
  • Terminal​: Open a new terminal to e.g. start service jars or Knowledge Agents (The

peers that build the Vsl Overlay). You can also press ctrl+alt+t to open a new terminal

  • Teamviewer​: If you are stuck we can connect to your VM via teamviewer and try to help
  • you. If you want to do this, start teamviewer and send us your ID and password over irc

as private message (or contact us over IRC first).

  • Tutorial files​: Shortcut to the folder where all tutorial related files are stored. See next

subsection for details. The folders full path is /home/im/tutorial Feel free to install any other software you like, e.g. a text editor of your choice. You can ​change your keyboard layout​ by opening the menu (bottom left) → Preferences → LXQT settings → Keyboard and Mouse

Folder Structure

The tutorial folder contains different subfolders:

  • code​: The skeleton codes for the tutorial. See next subsection for details.
  • bin​: The bin folder contains all compiled (working) jars for the game, so that you can try

it even without/before completing the code. It also contains the console service and the knowledge agents (ka.jar) (see later section) ○ models​: The models subfolder of the bin folder contains all models relevant for the tutorial. They are simple xml files structured in different subfolders and can be edited with any editor. You will need to ​edit some models during the tutorial​.

  • web​: The website that display the leaderboard and activity of the services. (nothing to do

here for you)

  • certificates​: The certificates for all services and Knowledge agents and the scripts to

recreate them. For your convenience the skeleton code uses the correct certificates

  • automatically. (nothing to do here for you)

Code Structure

The code is already imported in eclipse. The different packages contain different services or helpers. In this template we usually separate services in two java classes per package, using the following naming scheme:

  • xxxService.java: ​This class contains the main method and is the entry point of the
  • service. It sets up all necessary things for the service in order to work. E.g. it:

○ Specifies the ​context model​ used by this service in the MANIFEST ○ Loads the specified certificate ○ Creates a ​ServiceConnector​ object (connector) used to interact with the VSL ○ Creates the corresponding ​xxxServiceHandler.java ​class ○ Registers subscriptions and virtual nodes and uses xxxServiceHandler.java methods as callback So basically the xxxService.java class is responsible for ​wiring​ the service together

slide-6
SLIDE 6
  • xxxServiceHandler.java: ​This class implements the ​logic​ for running services. It:

○ Provides handler methods for subscription notifications (if necessary) ○ Provides handler methods for virtual node callbacks (if necessary) ○ Implements e.g. continuously running operations (like our game logic) as background threads (relevant) Packages:

  • ​org.ds2os.services.im.IoTdevice

○ The emulated IoT device. You can just use the already compiled jar, but feel free to look at the source code. ○ Goal: Emulates an IoT device, exposes its resources (LEDs, state, trigger) via CoAP. ○ You don’t have to change anything in here

  • rg.ds2os.services.im.boardGateway

○ The gateway service to the emulated IoT device ○ Goal: access to the state of the (emulated) IoT device using CoAP ○ TODO​ in Part 3 of the tutorial: complete BoardGateway.java

  • rg.ds2os.services.im.gamecontrol

○ The orchestration logic service for the game. ○ Goal: Implement game logic and interact with the other services for that purpose

  • ver the VSL

○ TODO​ in Part 3 of the tutorial: complete GameControlServiceHandler.java

  • rg.ds2os.services.im.monitor

○ The monitor service that can receive performance measurements as input over the VSL and dumps the last X into an file as html table which is displayed by the browser ○ You can just use the already compiled jar, but feel free to look at the source code. ○ You don’t have to change anything in here

  • rg.ds2os.services.im.leaderboard

○ The leaderboard service of the game. ○ You can just use the already compiled jar, but feel free to look at the source code. ○ You don’t have to change anything in here

  • rg.ds2os.services.tools.vslHelper

○ Helper methods for typesearch, virtualnode parameter parsing (not needed for this tutorial) and boolean parsing (0 and 1 in this example in string representation) (VslHelper.java) ○ You don’t have to change anything in here

slide-7
SLIDE 7

Starting services/agents from binaries

The bin folder contains compiled binaries for all services needed for the tutorial:

  • <serviceIdentifier>Service.jar

It also contains the certificates for those certificates (copied from the certificates folder). In addition we have the jar for the emulated device ​iotDevice.jar​ and the knowledgeAgent ka.jar​. The Console service ​console.jar​ can be used for easy access to the data stored in the VSL, similar to accessing a file system via terminal. Before you can start any service, you have to start at least knowledge ka1​. You can start a knowledge agent by typing the following command in the bin folder: # java -jar ka.jar 1 This starts ka1. Using 2 in the end you can start ka2 and with a 3 ka3 (we only generated certificates for three agents). Note that this blocks the terminal you used and shows you the activity of that knowledge agent, which we have a brief look at in the first part of the tutorial. By default all services try to connect to ka1​, therefore at least this agent has to be running before starting services. For most of the tutorial running only this agent is sufficient but in practice the services could be distributed over arbitrary KAs connected to each other and the game would work the same, without requiring any code changes. For your convenience we included scripts that start the individual services as screen sessions in the background, not blocking your terminal. You can simply execute them in a terminal if you are in the bin folder:

  • ./startGateway.sh​: starts the boardGatewayService.jar
  • ./startControl.sh​: starts the controlService.jar
  • ./startMonitor.sh​: starts the monitorService.jar
  • ./startLeaderboard.sh​: starts the leaderboardService.jar
  • ./startIotDevice.sh​: starts the iotDevice.jar (the emulated device)
  • ./startConsole.sh​: starts the console.jar (the console service)
  • ./killScreen.sh​: kills all screen sessions and therefore all running services

In order to ​reset​ everything in case you encounter an issue: 1. Execute the killScreen.sh script 2. Stop services that might be running from eclipse 3. Stop all running KAs (press enter or ctrl-c in the terminal they are running in) 4. Start them again (ka1 first, then other services)

slide-8
SLIDE 8

Interacting with the VSL using the console service

The console service can be started by executing the ​./startConsole.sh ​script if ka1 is running. It takes an optional parameter, which is the certificate it should use. By default it uses the system.jks certificate which basically grants root access to any node, independent of access rights. For the last part you need to use a different certificate, e.g. the lead.jks certificate for the leaderboard (the ending .jksis automatically added by the script): $ ./startConsole.sh lead You should see the following: system​@​ka1​:​ /ka1​ % This means you are connected to ​ka1​ using the ​system​ certificate and your relative path (similar to current working directory) is ​ /ka1​, the root node of the data managed by ka1. Afterwards you can access the vsl via some basic commands (type ​help​ for additional info):

  • system​@​ka1​:​ /ka1​ % ls

○ print all nodes in the current directory

  • system​@​ka1​:​ /ka1​ % get /ka1/node

○ Get​ and print the value of the node with address ​/ka1/node​ (if it exists)

  • system​@​ka1​:​ /ka1​ % set /ka1/node 1

○ Set​ the value ​1​ to the node with address​ /ka1/node ​(if it exists) Usually get returns only the directly requested node. You can change that to include children up to a specified depth:

  • system​@​ka1​:​ /ka1​ % param depth 2

Afterwards get requests print also child nodes and their child nodes (depth 2). Depth -1 means all children, 0 means only the requested node. Also by default the console service displays only data. We can change that with You can change that to include children up to a specified depth:

  • system​@​ka1​:​ /ka1​ % param scope complete

Afterwards get requests also include metadata like type of the node or timestamp/version when the value was last changed.

slide-9
SLIDE 9

Tutorial TLDR

Part 1:

  • Start ka2 → observe output
  • Start ka1 → observe how the data is synced to ka2 in ka2s output
  • Start gatewayService from jar → observe how the data is synced to ka2
  • Start the console service and check the existing nodes on ka1
  • Stop everything

Part 2:

  • Complete Board/IoT device context model (see TODOs)

○ Context model for board /adaption/board ○ Context model file /adaption/playercontrol

  • Play the game:

○ Start ka ○ Start services using the start scripts (order): ■ device, gateway, monitor, leaderboard, control ○ Play the game and check the output in firefox Part 3:

  • Complete BoardGateway.java (see TODOs):

○ Add missing subscriptions and virtual node handlers.

  • Complete logic workflow in GameControlServiceHandler (see TODOs):

1. Typesearch address of device gateway, only continue if found 2. Prepare device for game (set led/alarm states) 3. Trigger first player (set trigger node) 4. Trigger other player (set trigger node) 5. Wait until both hands are off (isPressed is 0) 6. Get the times for both players 7. Set losers red led off 8. Blink winner led 9. Turn alarm off

  • Check results:

○ Start all services, same order as in Part 2 ○ Run gateway and control services from eclipse, not from the jars ○ Play the game Part 4:

  • Start ka1, monitor service and console service with leaderboard certificate

○ Try to get /ka1/mon/secretKey ○ Try to set /ka1/mon/secretKey to any value

  • Fix the access rights of the node in the model of monitor (see TODO)

○ Model: ~/tutorial/bin/models/monitor.xml

  • Repeat first step, try access

○ Make sure to restart the ka and services so that it loads the updated model.

slide-10
SLIDE 10

Tutorial: The different steps

Now let’s get to the practical part!

Part 1: Overlay and Services

In the first step we have a look at how the Overlay is built, how structural information is synchronized between different knowledge agents and how we can start services. First let us have a look at how two knowledge agents actually connect to each other and what data they exchange.

Task 1: ​Start a knowledge KA and observe its initial messages

Open a terminal and navigate to ~/tutorial/bin (cd ~/tutorial/bin). Then start ka2 by typing: $ java -jar ka.jar 2 Maximize the terminal. You should see quite some lines of output. If the startup is finished the last line should say “​All KA systems activated​”. If we have a closer look at the output we can see e.g. on which network interfaces the ka is listening for updates: … Found interface enp0s3 with address 10.0.2.15 We can also see that the KA is broadcasting periodically updates over that address: … Broadcasting on udp://10.0.2.15:36501 Finally we also see that the KA actually sent a broadcast containing its initial structure … A KOR update of length 93 is being sent. … A KOR update of length 93 is being received… ​(as it is a broadcast, the KA receives its own update)

Task 2​: Start a second KA and and see what both agents exchange.

Open a second terminal and navigate to ~/tutorial/bin (cd ~/tutorial/bin). Then start ka1 by typing: $ java -jar ka.jar 1 Keep that terminal small, we are interested in what happens on the terminal of ka2 when ka1 comes online. After a few seconds we see a the following message: … Received incoming handshakerequest from ka1

slide-11
SLIDE 11

That means that ka1 received a periodic broadcast from ka2 and wants to join its group by sending it ka2 a handshakerequest. Next they exchange a key and ka2 integrates the new ka into its ​connectedKAs​ list Finally the most important part happens, ka1 sent its structure information to ka2: … applying update for ka1, I am ka2 … added node: /ka1 … added node: /ka1/search … added node: /ka1/slmr … added node: /ka1/system … added node: /ka1/typeSearch These are the nodes registered at ka1 so far. They are mostly used for internal services and not highly relevant for you. The /ka1/search and /ka1/typeSearch nodes offer access to (type) search features of the VSL, which we need later. Next let’s start a service on ka1 and see what happens.

Task 3​: Start the gatewayService.jar

Open a third terminal and navigate to ~/tutorial/bin (cd ~/tutorial/bin). Then start the gatewayService by executing: $ ./startGateway.sh This tries to start the (precompiled) boardGatewayService.jar in the background, connecting it to ka1. On ka2 we can see that ka1 actually sent an update to ka2, informing it about the new data nodes available on ka2: … A KOR update of length 916 is being received… … applying update for ka1, I am ka2 … added node: /ka1/board … added node: /ka1/board/player1 … added node: /ka1/board/player1/red … added node: /ka1/board/player1/red/isOn … added node: /ka1/board/player1/red/isOn/desired … added node: /ka1/board/player1/trigger … ka2 hash: bddad36319c002a8, ka1 hash: 663cb0e873faeaeb … applied KOR update from ka1 You might notice that there are only nodes for player1 on the board are registered and some nodes are missing. The reason for that is that the gateway model is ​incomplete​. We fix that in Part 2 of the tutorial. This is also the reason why there is an exception shown on ka1 when

slide-12
SLIDE 12

registering the service, as the service tries to access a node that is not defined by the context model.

Task 4​: Use the console service to check the result

We can check/query the result using the console service. Start it by executing $ ./startConsole.sh If you type ls system​@​ka1​:​ /ka1​ % ls You can see that on ka1 we have a new node called board which is the id of the certificate used for the boardGatewayService. Set the depth of the request to -1 (get all children) and request all data (including metadata) system​@​ka1​:​ /ka1​ % param depth -1 system​@​ka1​:​ /ka1​ % param scope complete Then request the board node: system​@​ka1​:​ /ka1​ % get /ka1/board This returns you all nodes of the service as defined in its context model, including the types. As we can see the type of the board node is ​/adaption/board​ and the player1 node is of type /adaption/playercontrol​. Also the red led node is of type ​/actuator/led​ and has two childnodes isOn and isOn/desired. The idea here is that the isOn node returns the actual state of the led. If we want to change the state, we set the isOn/desired node to the desired state (0=off, 1=on) and the boardGatewayService tries to reflect this to the actual led. If it succeeds, querying the isOn node will return the new state. We decouple the actual state from the state we want to set. This way the isOn node always returns the actual state, independent of what we would like the state to be (e.g. it might take a bit of time to change the state).

Task 5​: Stop everything

To conclude the first part of the tutorial, we saw that the knowledge agents automatically exchange which data is available and synchronize their internal knowledge structure. Note that the actual data is NOT synced, only the available addresses and other metadata like a nodes type are synced for e.g. performant ka-local typesearch. We also saw how the (current, incomplete) model of the gateway service. Now we have to stop everything again in order to fix the incomplete context model of the gateway. Execute the script: $ ./killScreen.sh

slide-13
SLIDE 13

To stop all background services. Then press enter or ctrl+c in the two running knowledge agents. From now on, if you want to run services, it is sufficient to just run ka1, as all services are connected to this ka.

slide-14
SLIDE 14

Part 2: Building a devices digital twin as context model

Before we can actually try the game we have to complete the context model of the iot device

  • gateway. Currently it only contains the node for player1 and the model for the players is also

incomplete.

Task 1​: Complete the context model of the board Gateway service

As we saw in the console service in the last part the model for the gateway service is /adaption/board. ​That means the corresponding model is ~/tutorial/bin/models/adaption/board.xml . Open that file with an editor (e.g. from the terminal gedit board.xml) or by double clicking on it in the file explorer. Then add the missing nodes as described by the TODOs. Make sure to use the names and types of the new nodes exactly as told.

Task 2​: Complete the playercontrol context model

We also saw that the model for player1 (and now player2), which are subnodes of the board.xml model, only had a red led and a trigger node so far. Here we are missing the green led, a node for requesting the time a player needed to react and a node to get the state of the players button (pressed or not). The player models are actually just included in board.xml and are of type /adaption/playercontrol. Open the corresponding model and finish it. Again, use the given names and types. Have a look at the already given nodes as example. Save the result.

Task 3​: Play the game

Now that the models are completed, we can finally try out the game. Make sure nothing is running (stop kas, use the killScreen.sh script to kill services). Then ​start​ (in this order): 1. ka1 2. The emulated IoT device: ./startIotDevice.sh 3. The gateway Service: ./startGateway.sh 4. The monitor and leaderboard service: ./startMonitor.sh and ./startLeaderboard.sh 5. The control service: ./startControl.sh 6. Open firefox to check the output of the monitor and leaderboard services a. Use​ file:///home/im/tutorial/web/index.html​ as url, should be automatically

  • pened when starting firefox

Play a few rounds! Reminder:

slide-15
SLIDE 15

Press both keys d and j, the blue alarm led in the top indicates the game is starting. Once a red led turns on, stop pressing the according key. Once both red leds are on and bot keys are not longer pressed, the faster players red light will blink and the results are visible in firefox. Note that you can set your own player names in the vsl on the /ka1/con/players/one node using e.g. the console service (reset when you restart ka and the services)

Task 4​: Stop everything

Again, stop all services and the ka. Next we want to implement the logic on our own!

slide-16
SLIDE 16

Part 3: Building the game logic and mashing up services

Time to have a look at the code! Open eclipse.

Task 1​: Complete the subscriptions and VirtualNode registrations of the Gateway

In the previous Part we completed the context model(s) used by the gateway service. While the compiled jars contain the fully functioning code, the skeleton code of the BoardGateway.java class is missing some subscription and virtual node handlers. The basic idea behind which node should be subscribed to and which node should be registered as virtual is the following:

Task 1.1​: Complete subscriptions of the Gateway

The gateway should subscribe to its own:

  • Desired nodes of its led nodes

○ When the desired node is changed, we want to read it and try to reflect it to the emulated device. ○ We could use virtual nodes for that, but then the calling service would have to wait until the isOn value is actually updated and the virtual call returns.

  • The trigger nodes of both players

○ If a trigger node changes (independent of the value), the according trigger signal should be sent to the IoT device. We don’t actually care about the value, therefore we can just react whenever we get a notification. Most subscriptions are already implemented. Have a look at​ TODO 1​ in BoardGateway.java and implement the missing subscriptions for: ~/player2/trigger ~/alarm/isOn/desired Note that ~ refers to the root node of the own services registered address. So the address ~/player2/time is equivalent to /ka1/board/player2/time​ (if the service is registered to ka1 using the board.jks certificate keystore, which is the default).

Task 1.2​: Complete the virtual node registrations of the Gateway

The gateway should register virtual get handlers for all nodes where the request should return the live state from the emulated IoT device. On such a request, the requested state should be

slide-17
SLIDE 17

requested from the device using CoAP and the result should be returned as result of the virtual get operation. Most virtual node registrations for get operations are already implemented. Have a look at TODO 2​ in BoardGateway.java and implement the missing virtual nodes for: ~/player2/time ~/player2/isPressed ~/alarm/isOn

Task 2 (optional)​: Test if your code is working

If you want to test whether your handlers work, you can start ka1 and the console service. Then start the iot Device using the script and start the BoardGateway.java class from eclipse (right click on the class →Run as → Java Application). In the console service you can then ​set​ e.g. the​ /ka1/board/alarm/isOn/desired​ node to ​1​ and check whether the alarm lamp of the device is turned on (blue). You can then also use ​get​ on the ​/ka1/board/alarm/isOn​ node to check if the correct state is returned. When done stop the boardGatewayService again (bottom of eclipse, red square). You can keep the ka and console service running or stop them.

Task 3​: Complete the orchestration logic

Now to the major part of the game: implementing the orchestration service. In the GameControlServiceHandler.java class we have to implement the logic that continuously check whether the game should be executed and then orchestrates the different steps and reports the results. The base idea of the GameControlServiceHandler is the following: In the constructor we start a background thread that runs every 500 milliseconds after the previous run finished. The logic is implemented in that runnable and is in parts already there, in parts described by ​TODOs 1-9​:

  • TODO 1​: Only continue with the logic if we find the address of the gateway service via

typesearch

  • Given​: Start the game only when both buttons are pressed (--> get button state from the

gateway)

  • TODO 2​: Prepare the board for the game: set the state of the red leds of, turn the alarm

led on.

  • Given​: Next we pick a random delay and player to trigger first after the delay. Then we

wait for the delay to pass.

  • TODO 3​: Now trigger the first player (--> Set the trigger node of the according player)
  • Given​: Again we wait a random delay before triggering the second player
slide-18
SLIDE 18
  • TODO 4​: Trigger the other player (--> Set the trigger node of the according player)
  • TODO 5​: In the given while loop wait for both players to stop pressing buttons (--> get

the isPressed state and save them as the correct booleans)

  • TODO 6​: Retrieve the times for both players from the smart device (--> get the time

nodes of both players and parse them as long)

  • Given​: Calculate the winner
  • TODO 7​: Turn the red led of the loser off (note that both could be winners if they were

equally fast) (--> set losing players red led state to 0)

  • Given​: Use type search to find the leaderboard service, get the players names and

report both times to the leaderboard service if they are valid (<100000 milliseconds). ○ The leaderboard service adds the results to its database and displays the results in firefox

  • TODO 8​: Show the winner on the iot device. You can do whatever you want here, the

easiest example is to blink the winners led by turning it on/off a view times in a loop. Feel free to include any other leds of the smart device for a nice animation.

  • TODO 9​: Finally turn the alarm led off to indicate the next round can start (--> set alarm

led 0) Note that whenever you use connector.get(address); or connector.set(address, value); to get/set values from the VSL you can also use the method getAndReport(address); or setAndReport(address, value);. This actually uses the regular connector operations, but also reports the time/delay the command needed to execute to the monitor service, which displays the results in firefox.

Task 4​: Test if your logic works!

Now its time to test whether your solution works. Start (in this order): 1. ka1​ (if not still running) 2. The emulated ​IoT device:​ ./startIotDevice.sh 3. The ​gateway Service in Eclipse​: a. right click on the class →Run as → Java Application. 4. The ​monitor and leaderboard services​: ./startMonitor.sh and ./startLeaderboard.sh a. Alternatively start them in eclipse 5. The ​control service in Eclipse​: a. right click on the class →Run as → Java Application. 6. Open firefox to check the output of the monitor and leaderboard services a. Use file:///home/im/tutorial/web/index.html as url, should be automatically opened Now play a round and test if your logic actually works!

Task 5​: Stop everything

Again, stop all services and the ka.

slide-19
SLIDE 19

Part 4: Security

Last but not least we’ll have a brief look at the access control features of the VSL. For that purpose the monitor service actually has a node called secretKey that contains a secret message, where actually not everyone should have access.

Task 1​: Check how secure the access to the secretKey currently is:

Start (in this order): 1. ka1 2. The ​monitor service​ (either from eclipse or via script) 3. The console service, but with the certificate and access rights of the leaderboard service (which shouldn’t have the right to read the secretKey): a. $ ./startConsole.sh lead → IMPORTANT: use lead and not lead.jks, otherwise the start script doesn’t work. Now try to get the secret Key: system​@​ka1​:​ /ka1​ % get /ka1/mon/secretKey Did it work? How about changing it? system​@​ka1​:​ /ka1​ % set /ka1/mon/secretKey ThisIsMyNewSecretKey system​@​ka1​:​ /ka1​ % get /ka1/mon/secretKey Doesn’t look like it is secured properly. Stop all services and the ka.

Task 2​: Update the model of the monitor service

We can secure the access rather easily. Open the model of the monitor service (​~/tutorial/bin/models/logic/monitor.xml​). As you can see the secretKey node is just a regular node. The value is set by the monitor on

  • startup. Update the secretkey with a ​reader​ and ​writer​ tag that restricts who can access the

node: <secretKey type="/basic/text" reader=”” writer=""/> Per default everyone can read/write each node. By setting reader and writer of a node explicitly to an empty string “”, read/write (=get/set) ​access is restricted​ to the service that registered the

slide-20
SLIDE 20

model and the system root certificate (therefore we needed to use the leaderboard certificate for the console service).

Task 3​: Try accessing the secretKey node again

Repeat the steps from Task 1. Can we get/set the key now? → Make sure you restarted the ka and services after changing the model so that the updated model is loaded. You can also try to start the console service with system.jks or monitor.jks certificates. Does it work then?

Tutorial: Closing words

We hope you enjoyed this brief tutorial and got an idea of the capabilities of the VSL and how easy it is to actually interact with it. We hope to meet you again in the future.

slide-21
SLIDE 21

VSL Java Cheatsheet

Here you can find example snippets of how to write java code that Interacts with the VSL. Have a look at the Code Structure section to learn about how services are structured in a xxxService.java (implements wiring of VSL, connector, handler) and a xxxServiceHandler.java (implements logic of a service) class. The main connection to the VSL is always the ServiceConnector object that is created in the xxxService.java class and handed to the xxxServiceHandler.java class. We refer to that as connector​. Register a subscription on a node with a handler for get requests: connector.subscribe(“/ka/service/some/node/address”, new VslSubscriber() { @Override public void notificationCallback(String address) { // Do whatever you want to do on a callback, e.g. call a handler method } }); Register a virtual node with a handler for get requests: connector.registerVirtualNode("/ka/service/some/node/address", new VirtualNodeAdapter() { @Override public VslNode get(String address, VslAddressParameters params, VslIdentity identity) throws VslException { return … // Return a VSLnode you can e.g. call a handlermethod that creates the node for // you based on some remote query, e.g. to our IoT device or from a web request. } }); Create a VslNode: VslNode node = connector.getNodeFactory().createImmutableLeaf(“Some Value as String”); Set a VslNode on a specific address: connector.set(“/ka/service/some/node/address”, node); Retrieve a VslNode from a specific address: VslNode result = connector.get(“/ka/service/some/node/address”); Retrieve the String value from a VslNode: String value = node.getValue();

slide-22
SLIDE 22

Solution Part 3:

Work in progress:

BoardGateway.java

TODO 1: register subscriptions to nodes where an action should happen when the value changes connector.subscribe("~/player2/trigger", new VslSubscriber() { @Override public void notificationCallback(String address) { handler.setValue(address, IoTDevice.PATH_P2_TRIGGER); } }); connector.subscribe("~/alarm/isOn/desired", new VslSubscriber() { @Override public void notificationCallback(String address) throws VslException { handler.setValue(address, IoTDevice.PATH_ALARM); } }); TODO 2: register virtual nodes where we want to get the current state live from the IoT device connector.registerVirtualNode("~/player2/time", new VirtualNodeAdapter() { @Override public VslNode get(String address, VslAddressParameters params, VslIdentity identity) throws VslException { return handler.getValue(IoTDevice.PATH_P2_TIME); } }); connector.registerVirtualNode("~/player2/isPressed", new VirtualNodeAdapter() { @Override public VslNode get(String address, VslAddressParameters params, VslIdentity identity)

slide-23
SLIDE 23

throws VslException { return handler.getValue(IoTDevice.PATH_P2_PRESSED); } }); connector.registerVirtualNode("~/alarm/isOn", new VirtualNodeAdapter() { @Override public VslNode get(String address, VslAddressParameters params, VslIdentity identity) throws VslException { return handler.getValue(IoTDevice.PATH_ALARM); } });

GameControlServiceHandler.java

TODO 1: Use Typesearch to find the gateway service based on its type List<String> addresses = VslHelper.typeSearch("/adaption/board", connector); if (addresses.size() > 0) { boardAddress = addresses.get(0); } if (boardAddress == null) return; TODO 2: Switch the state of the leds on the board to initialize the game // Turn off the red lights in case they are on setAndReport(boardAddress + "/player1/red/isOn/desired", connector.getNodeFactory().createImmutableLeaf("0")); setAndReport(boardAddress + "/player2/red/isOn/desired", connector.getNodeFactory().createImmutableLeaf("0")); // Set the alarm to 1 to indicate the game started. setAndReport(boardAddress + "/alarm/isOn/desired", connector.getNodeFactory().createImmutableLeaf("1")); TODO 3: Trigger the first player (should take finger off)

slide-24
SLIDE 24

setAndReport(boardAddress + playerPrefixes[trigger1] + "/trigger", connector.getNodeFactory().createImmutableLeaf("1")); TODO 4: Trigger the second player (should take finger off) setAndReport(boardAddress + playerPrefixes[1 - trigger1] + "/trigger", connector.getNodeFactory().createImmutableLeaf("1")); TODO 5: Get the state of which players still press their key player1Pressed = VslHelper .parseBoolean(connector.get(boardAddress + "/player1/isPressed").getValue()); player2Pressed = VslHelper .parseBoolean(connector.get(boardAddress + "/player2/isPressed").getValue()); TODO 6: Get the time both players needed to take their finger off player1Time = Long.parseLong(getAndReport(boardAddress + "/player1/time").getValue()); player2Time = Long.parseLong(getAndReport(boardAddress + "/player2/time").getValue()); TODO 7: Set the losers red led to off if (!player1IsWinner) setAndReport(boardAddress + "/player1/red/isOn/desired", connector.getNodeFactory().createImmutableLeaf("0")); if (!player2IsWinner) setAndReport(boardAddress + "/player2/red/isOn/desired", connector.getNodeFactory().createImmutableLeaf("0")); TODO 8: Blink the winners LED int counter = 0; while (++counter < 15) { Thread.sleep(400); if (player1IsWinner) connector.set(boardAddress + "/player1/red/isOn/desired",

slide-25
SLIDE 25

connector.getNodeFactory().createImmutableLeaf(counter % 2 == 0 ? "0" : "1")); if (player2IsWinner) connector.set(boardAddress + "/player2/red/isOn/desired", connector.getNodeFactory().createImmutableLeaf(counter % 2 == 0 ? "0" : "1")); } TODO 9: Set the alarm LED off to indicate the game is reset setAndReport(boardAddress + "/alarm/isOn/desired", connector.getNodeFactory().createImmutableLeaf("0"));