• No results found

Calvin based Internet of Things framework on Resource Constrained Devices: Analysis and implementation of an Internet of Things framework

N/A
N/A
Protected

Academic year: 2022

Share "Calvin based Internet of Things framework on Resource Constrained Devices: Analysis and implementation of an Internet of Things framework"

Copied!
68
0
0

Loading.... (view fulltext now)

Full text

(1)

IN

DEGREE PROJECT INFORMATION AND COMMUNICATION TECHNOLOGY,

SECOND CYCLE, 30 CREDITS ,

STOCKHOLM SWEDEN 2016

Calvin based Internet of Things framework on Resource

Constrained Devices

Analysis and implementation of an Internet of Things framework

LORENZO CORNEO

KTH ROYAL INSTITUTE OF TECHNOLOGY

(2)
(3)

Abstract

The Internet of Things (IoT) is a network of devices, usually sensors and actuators, that are connected together through the Internet and can be remotely accessed and commanded.

As IoT is getting very pervasive, there is the need to extend, in an efficient manner, such functionality also to Constrained Resource Devices (CRD) which rely on limited computational power. Furthermore, the diversity in the lowest level of the IoT stack, due to the several devices available on the market, is a huge problem to tackle.

We propose to solve these problems taking as a case study Calvin, an IoT actor-based hybrid framework by Er- icsson Research, and ARM mbed OS, which purpose is to fill the gap between the diversity of devices, providing a set of APIs that hides these differences.

The solution we present in this paper is µCalvin, a min- imal Calvin prototype implementation that runs on the top of mbed OS. We achieve the porting of Calvin on CRDs se- lecting a subset of its functionality which still guarantee the ability to run applications.

To conclude, we evaluate µCalvin in terms of perfor- mance, network traffic and amount of messages exchanged.

(4)

Internet of Things (IoT) är ett nätverk av enheter som vanligtvis består utav sensorer och manöverdon, som är sammankopplade genom Internet och kan fjärrstyras.

Eftersom, Internet of Things blir mycket genomträng- ande, finns det ett behov att utvidga, i en effektivt sätt, så- dan funktioner även till Constraint Resource Devices (CRD) som är beroende av begränsad beräknings kraft. Dessutom, mångfalden i den lägsta nivån av IoT stack, på grund av de flera enheter som finns på marknaden, är en enorm problem att ta itu med.

Vi föreslår att lösa dessa problem med hjälp av en fall- studie Calvin, en IoT actor-baserade hybrid framework ut- av Ericsson Research, och ARM mbed OS, vilket syftet är att fylla mellanrummet mellan mångfalden av enheter, vil- ket ger en uppsättning API: er som döljer dessa skillnader.

Den lösning som vi presenterar i denna uppsats är µCalvin, en minimal Calvin prototyp genomförande som körs på toppen av mbed OS. Vi uppnår porteringen av Calvin på CRDs, genom att välja en delmängd av dess funktionalitet som fortfarande garantera möjligheten att köra applikatio- ner.

För att sammanfatta, utvärderar vi µCalvin i form av prestanda, nätverkstrafiken och mängden av meddelanden som utbyts.

(5)

Contents

1 Introduction 3

1.1 Background . . . . 3

1.2 Problem . . . . 4

1.3 Purpose . . . . 4

1.4 Goals . . . . 4

1.5 Ethics and sustainability . . . . 5

1.6 Methods . . . . 5

1.7 Delimitations . . . . 6

1.8 Outline . . . . 6

2 Calvin and mbed OS 7

2.1 Related work . . . . 7

2.1.1 Global Sensor Network (GSN) . . . . 7

2.1.2 Node-RED . . . . 7

2.1.3 FreeRTOS . . . . 8

2.1.4 Other relevant work . . . . 8

2.2 Calvin background . . . . 8

2.3 Calvin . . . . 9

2.3.1 Runtime . . . . 11

2.3.2 Actors . . . . 11

2.3.3 Application . . . . 11

2.4 CalvinScript . . . . 11

2.4.1 Components . . . . 12

2.5 Actors in Python . . . . 12

2.6 An echo example . . . . 13

2.7 mbed OS . . . . 15

3

µCalvin

19

3.1 Requirements analysis . . . . 20

3.1.1 Joining the network . . . . 20

3.1.2 Actor migration . . . . 22

3.1.3 Opening a tunnel and port connection . . . . 24

3.1.4 Tokens exchange . . . . 25

(6)

3.2.2 Interaction . . . . 27

3.2.3 Behavior . . . . 27

3.3 Problem analysis . . . . 30

3.3.1 Structure . . . . 30

3.3.2 Interaction . . . . 32

3.3.3 Behavior . . . . 35

3.4 Implementation and testing . . . . 35

3.5 Conclusion . . . . 37

4 Evaluation 41

4.1 Round Trip Time . . . . 41

4.2 Gap . . . . 47

4.3 Amount of messages and network traffic . . . . 50

4.4 Discussion . . . . 52

5 Conclusion 55

6 Future work 57

Bibliography 59

(7)

Acknowledgement

First of all, I am very grateful to my parents, Laura and Tiziano, that always supported me throughout this journey. Also, I want to thank the rest of the family and friends in Cesena for encouraging me all the times.

This report is the result of a master thesis developed at Ericsson Research, department of Device Technologies. I want to thank my supervisor Lars Andersson that, with his help and dedication, made this thesis possible.

Furthermore, I want to thank Professor Mihhail Matskin for all the opportuni- ties, trust and suggestions he gave me throughout my master studies.

Last but not least, I am very grateful to my classmates and friends Antonis, Nik and Vasilis, for all the good time we spent together, within and without the university. Finally, a special thanks to Maurizio, Marco and Katarina for being my second family here in Stockholm.

Stockholm, 17 June 2016

Lorenzo Corneo

(8)
(9)

Chapter 1

Introduction

The Internet of Things (IoT) is already a huge reality in the everyday life, nonethe- less, an even huge growth of it is expected. According to the Ericsson Mobility Report, the predicted number of “things” connected to the Internet by 2021 would be around 28 billions[1]. For this reason, we need to be prepared to provide the de- velopers with suitable tools, and users with appropriate infrastructures for enjoying the services.

The revolution has already started, and both companies and research institutes are studying architectures, frameworks and new languages for an easier and faster development process. In the next sections, we are going to expose the general background of the area, the problem, goals, ethics, sustainability and limitation of this thesis.

1.1 Background

At the time of writing, application development for the Internet of Things (IoT) is usually complex as developers must confront with heterogeneous vendor specific solutions, communication protocols, platforms and standards. In fact, developing applications for specific devices might already be challenging, because of the afore- mentioned problems, but, porting these to different platforms is totally both not sustainable and scalable. To conclude, a scenario where developers must deploy their applications on several and heterogeneous devices is not uncommon.

On the hardware side, boards like Arduino[2] made everything easier, giving the opportunity to everyone to develop prototypes at a very low cost. The community of the so called “makers” is huge and the information can be easily retrieved everywhere on the web. The hardware side revolution is not only Arduino. In fact, a very interesting and promising project is ARM mbed[3], which embraces both hardware and software with the mission to provide an operative system, mbedOS, to a wide range of IoT devices in order to make it easier writing applications requiring high connectivity.

The case study of this master thesis is Calvin[4], an hybrid framework born to

(10)

merge the principles of the Actor model[5] and the Flow Based Programming[6], currently under research and development at Ericsson Research. As ARM mbed offers a valid and concrete solution to the fragmentation of the devices at the lower layer of IoT, it is the ideal candidate embrace the Calvin framework and together smooth the difficulties of application programming.

1.2 Problem

When writing an application for Internet of Things, usually, a developer splits the implementation in two parts: the one running on Constrained Resource Devices (CRD) and the one running on more powerful devices (i.e. computers, Raspberry Pi). The main problem is that this method does not help in keeping the development process smooth and transparent.

Nowadays, many distributed frameworks are built on top of so called runtimes (RT), that represent the basement of the framework, and they allow developers to write a single application and deploy it wherever a RT exists without changing a single line of code. CRDs suffer some limitations (i.e. energy consumption, limited computational power) but running an IoT framework on the top of them would give many benefits to the developers. The research question for this master thesis is:

How can we run Internet of Things frameworks on top of Constrained Resource Devices and what are the limitations?

1.3 Purpose

The purpose of this master thesis is to provide a solution for running an IoT frame- work on those devices with limited resources, like for example, microcontrollers.

More specifically, we will provide a solution for running the Calvin framework on boards mounting ARM Cortex-MX MCU.

Furthermore, we will provide valid experiments to test and evaluate the solution, which will be a prototype implementation.

1.4 Goals

Goals of this master project are to provide the followings:

• A practical solution to run an IoT framework on CRDs

• A minimal Calvin runtime (prototype implementation) for mbed OS, called µCalvin

• An evaluation of µCalvin, reporting experiments and results

• Extend the physical domain of Calvin to provide additional tools to the com-

munity of IoT developers

(11)

1.5. ETHICS AND SUSTAINABILITY

1.5 Ethics and sustainability

From an ethical point of view, µCalvin, is morally necessary for several reasons.

Firstly, it supports the expansion of Calvin which proposes a solution to the frag- mentation of IoT applications development. Every extension of Calvin would help developers make the IoT era happens quicker. This cannot occur if the community of developers will not port Calvin on Constrained Resource Devices.

Secondly, µCalvin together with mbed OS will decrease the time necessary to develop IoT applications. In fact, this will assure to write the application code once, and deploy it many times without the need of any modifications.

The saving of time may allow companies to better allocate human resources that would be free to work on other projects. From this, an increase of companies’ wealth is expected. As a result, companies may hire more employees and redistribute the amount of work per employee to improve the quality of work.

From the sustainability point of view, µCalvin is not optimized for energy con- sumption as it does not provide any kind of energy management, such as sleep mode or energy saving mode. Nonetheless, energy optimization will be included in future work sections in the conclusions of this thesis. The sustainable aspect of our prototype implementation is that, in the nearest future, it will allow to balance the energy consumption in distributed software systems sharing the work load with CRDs in a more efficient way.

1.6 Methods

The thesis is a Quantitative Research as it supports experiments and testing, mea- suring variables and falsify or validate hypothesis or thesis. In our specific case, the quantitative research will measure the functionality of the minimal IoT framework that will be object of the study.

As a research method, the experimental is the one that is more suitable for in- vestigating variables and performance of a computer system like ours. This method is characterized by the manipulation of one or more variable keeping the others constant and investigates how the changes affect the whole system.

Quantitative methods are usually coupled with a deductive approach that con- sists in testing theories with the support of data, usually large data sets. We will also use an experimental strategy that makes use of statistics in order to prove or reject the initial assumptions. The data sets to be analyzed are gathered using experiments so that we can study the evolution of the variables.

The research will be valid, reliable and the reader will be able to replicate the

results as every procedure will be detailed and explained in the text[7].

(12)

1.7 Delimitations

Our case study, Calvin, is a complex framework built of many parts and layers. For the thesis purpose, we will concentrate only on the minimal subset of functionality useful to provide the use of Calvin on ARM microcontrollers, which correspond to a minimal runtime (RT).

An important part of the framework, and fundamental to build Calvin applica- tions, is the actor layer[5], of which we will provide a very small and hard-coded implementation. Even though we will provide some actors, we will do that just to be able to perform experiments, but we will not study it in detail.

Another aspect that we will not take into consideration is the energy consump- tion. During the experimentation part, we will try to push as much as possible our micro controllers in order to evaluate the performance. This scenario, though, is not sustainable if, for example, the micro controller is powered up with some batteries because they will be drained in a short period of time.

1.8 Outline

In chapter 2 we will introduce both Calvin and ARM mbedOS so that the reader

can assimilate the base knowledge required to understand this thesis work. Then,

chapter 3, shows the development process of µCalvin according to the classic soft-

ware engineering development method. Furthermore, chapter 4 provides a set of

experiments with which we evaluate its performance on micro controllers and some

analysis. Additionally, future works will be pointed out. Finally, the conclusion will

discuss the achievements of this thesis work.

(13)

Chapter 2

Calvin and mbed OS

This chapter provides the reader the background knowledge which is fundamental for the understanding of the topic that will be object of the study later on. Firstly, we present the most relevant related work. Then, the programming paradigms that inspired Calvin, will be briefly introduced, namely Actor model[5] and Flow Based Programming (FBP)[6] as well as the main competitor of it. Finally, we will present ARM mbed OS which is the software platform we will use to host this thesis project:

µCalvin.

2.1 Related work

In this section, we are going to list the most relevant work that have been done in the area of our topic.

2.1.1 Global Sensor Network (GSN)

Global Sensor Network[8] is one of the most adopted middleware that tackles down the problem of the heterogeneity of the sensors. In fact, through the use of its Virtual Sensor s, which are defined through XML files, it is possible to handle easily the diversity of the sensors. For example, in these XML files it is possible to specify the type of the data returned, tuning parameters, how to connect to them and how to retrieve values.

2.1.2 Node-RED

Node-RED[9] is a visual tool, developed in Javascript, for writing Internet of Things

applications following the Flow Based Programming[6] paradigm. In fact, within a

web browser it is possible to design flows dragging nodes from a palette and con-

necting them together. Node-RED is a light-weight runtime built on the top of

Node.js[10] and it is an ideal candidate to run on the top of Constrained Resource

Devices, whenever they could support Javascript. Also, Node-RED, can take ad-

vantage of the hundreds of thousands modules available on Node.js repositories.

(14)

Furthermore, it is possible to define custom functions and nodes for extending the functionality of the designed system.

2.1.3 FreeRTOS

Free-RTOS [11] has been developed for a period of twelve years, in collaboration with the world’s leading chip companies, and it is the de-facto standard solution for applications development for microcontrollers. Also, it supports Internet of Things applications development with the freeRTOS+Nabto library which is a small piece of C code that enables CRDs to be accessed and controlled remotely through the network.

2.1.4 Other relevant work

It is worth mentioning also middlewares and architectures that have been proposed, especially in academia. Among these, we want to briefly explain the architecture studied by Boman et al. in [12]. In its paper, Boman et al., makes use of the Cloud to allow 3rd party applications to be able, always, to retrieve data, also when the sensor networks, or other parts of the system, are temporary unavailable. This work is relevant because it facilitates the integration of IoT applications and make them more accessible.

Several programming paradigms may be used for IoT applications development like, for example, the agent oriented paradigm. In fact, Fortino et al. propose an IoT middleware based on agents and the cloud for building “decentralized, dynamic, cooperating and open systems”[13].

There are many relevant work that have been produced recently, but for brevity reasons we can not describe them all. Nevertheless, we provide references so that the interested reader may be able to explore them. Nitti et al. talks about the Social Internet of Things (SIoT)[14], that proposes to address how devices make connections between each other in order to get appropriate and relevant data. Also, new IoT challenges are listed and discussed in [15] by Fersi and it can be used as a reference for future works on IoT frameworks.

2.2 Calvin background

The concept of actor in Calvin is very important as it is the computational unit which performs actions in the application. The Actor Model is a mathematical theory in which the actors are the universal primitives of digital computation[5].

Actors communicates via message passing and this implies that actors have a address and that are uniquely identifiable through a unique identifier. When a actor receives a message, it can concurrently:

• send messages to another actor, via its address

• create a new actor, with a new address

(15)

2.3. CALVIN

• determine how to handle the next message to be received

The communication between actors, because of the message passing, is asynchronous[5].

Important frameworks and languages which implements the actor model are Erlang[16], Akka[17], Orleans[18] and many others.

Another important background aspect of Calvin is the Flow Based Programming[6].

The most important concepts are processes, ports, connections and Information Packets (IPs). The core idea is that processes are made up of input ports and output ports, and they perform some computation. After, the results are shipped through output ports under the form of IPs. Ports are bound together with unidi- rectional connections and processes can be used more than once and combined with other in order to extend functionality. For example, processes can perform basic operations like Sum, Multiplication, Counter and then can be used together to cre- ate more complex processes like Power (x

y

), Summation(

P

) and so on. Well known examples of FPB are NoFlo[19] and Node-RED[9] by IBM, which is designed appo- sitely for IoT application development. Both these frameworks are implemented in JavaScript and can be deployed wherever the language is supported.

The last, but not least, concept is the Mobile Agent (MA)[20]. As it can already have been noticed, Calvin is not an Agent system based framework, nonetheless it aims to exploit the seven fundamental benefits reported by Lange and Oshima in [21]:

• reduce network load

• encapsulate protocols

• are naturally heterogeneous

• overcome network latency

• execute asynchronously and autonomously

• adapt dynamically

• are robust and fault tolerant

Mobility is one of the most interesting aspect of this master thesis as the most of the work was done with the purpose of distribute actors from one device to another.

Calvin, that will be introduced in the next section, combines these programming paradigms and, in particular, replaces actors with the processes of FBP and gives them mobility through their migration functionality.

2.3 Calvin

Calvin is an open source project by Ericsson Research hosted on GitHub[22] can be

installed on many device, also on the ones showing limited computational power, as

long as they can run Python. The most important architectural components are:

(16)

1. Platform: Hardware + Operating system

2. Runtime: this layer is divided in two sub-layers: platform dependent and plat- form independent. On the platform dependent part, it uses services exposed by the OS and, on the platform independent one, it exposes the interface for the actors.

3. Actors: the workers of the application. They define in-ports and out-ports as well as a set of prioritized actions to perform that are fire when certain conditions happen.

4. Application: defines the actors of the system and how their ports are con- nected together.

Fig. 2.1 shows the transparency of the application layer. In other words, the application is defined on a specific node and it gathers data from the actors, even if they have migrated to others runtimes.

Actors can migrate wherever there is a Calvin runtime up and running. Addi- tionally the runtime supports multi-tenancy, that is, a single runtime might host many actors coming from different applications, all on the same instance, sharing the same resources.

Figure 2.1: Architecture of Calvin. The runtime is divided in two parts: platform

dependent and platform independent.

(17)

2.4. CALVINSCRIPT

2.3.1 Runtime

The runtime is the most important part of Calvin because it lays at the basement of the architecture’s stack. As previously said, it is divided in two parts: platform dependent and platform independent.

The platform dependent part, exploiting the services exposed by the OS, is responsible for the communication between the other runtimes and through a plug- in mechanism it supports any kind of transport layer such as WiFi, BlueTooth, I2C.

The platform independent part exposes the interface toward the actor layer, providing them APIs (i.e. actors creation, migration, etc...) and multi-tenancy that allows them to share the same runtime (and resources).

2.3.2 Actors

An actor consists of in-ports, out-ports and actions. For in-port is intended an input port, while for out-port an output port. Those ports consume and produce tokens that are sent to other actors.

The actions are prioritized and they are executed only when a certain precon- dition is true. For instance, the Python implementation defines the @condition decorator so that it is possible to specify which in-ports should receive a token in order to fire the action. Additionally, it might be specified also the out-port for sending a response as a output. Finally, it is possible to insert a @guard decorator that adds constraints for the execution of the action.

2.3.3 Application

The application can be implemented either in Python or in Calvinscript. For the former case, an utility module is defined to expose the APIs interface through which it is possible to create actors, specify connections between actors’ ports, migrate them, etc.

CalvinScript is the ad hoc language created for Calvin which has a very clear, clean, elegant and powerful syntax. The next section dives more in depth into that.

2.4 CalvinScript

A CalvinScript application is basically composed of two parts:

1. Actors declaration

2. Connections between actors’ ports

An actor can be declared with the following syntax:

<actor_name> : <namespace>.<actortype>(<arguments>)

(18)

A concrete example:

temp1 : weather.Sensor(name="temperature_1") snk : io.StandardOut()

The second part shows the connections between the unidirectional ports of the agents in the system. The syntax is the following:

<actor_name>.<out-port_name> > <actor_name>.<in-port_name>

An example:

temp1.value > snk.token

indicating that the actor temp1 connects its value port to the token port of actor snk.

2.4.1 Components

From its design purposes, Calvin, has been made to develop applications as to build things with LEGO bricks. Then, Calvin supports components definition that allow the developer to build complex objects reusing existing ones. Basically, a component is a program that defines in-ports and out-ports that can be used and connected to other components / actors.

The syntax for a component declaration is the following:

component <component_name>(<arguments>)

<in-port_list> -> <out-ports_list> {

<program>

}

2.5 Actors in Python

Actors are the computational units of Calvin as they perform actions that will affect the system. Actors can be defined in Python and in the source code below, there is a simple and incomplete implementation of it:

1 from calvin . actor . actor

2 import Actor , ActionResult , manage , condition

3

4 class ActorName ( Actor ):

5 """

6 Actor description .

7 Inputs :

8 in−port : in−port description

(19)

2.6. AN ECHO EXAMPLE

9 in−port : in−port description

10 Outputs :

11 out−port : out−port description

12 out−port : out−port description

13 """

14

15 def init (self, arguments ...) :

16 # #########

17

18 @condition ([in

ports_list ], [out

ports_list ])

19 @guard (....)

20 def action1 (self, arguments ...) :

21 # Performs action

22 return ActionResult (...)

23

24 action_priority ( action1 , actionN , ....)

Every Calvin actor must inherit from the base class calvin.actor.actor.Actor.

In the code below, it can be seen that in-ports and out-ports are declared in the class description with the following syntax:

Inputs :

<in-port_name> : description Outputs :

<out-port_name> : description

The port names defined in the actor are the same used in the CalvinScript (or Python application).

The action_priority method defines the execution priority of the actions.

That is, if two conditions are true at the same time, the first action to be fired is the one with the highest priority. This is a limitation for applications that require a data stream as one action will fire always while the other never.

2.6 An echo example

In the previous sections we listed the most important aspects of Calvin, and even though there would be much more to say about it, we are now able to understand and enjoy a very simple example: an echo application between two runtimes. In this very particular example, we will use also a custom actor, created by us, that measure the Round Trip Time

1

(RTT) between the two runtimes. We opted for this choice because we can use it for data gathering later on in the text.

1Round Trip Time: the time used for a message of negligible dimension to go from the source to the target and back again.

(20)

Just to make things more interesting (and distributed, of course!), we assume that we use two runtimes on different hardware: a Linux machine and a Raspberry Pi 2 Model B.

Fig. 2.2 shows the architecture of the application, and in particular the dis- tribution of the actors over the runtimes and the connections between the ports.

To notice that the arrows indicate the direction as long as the connections are unidirectional in Calvin.

Figure 2.2: Architecture of the echo example distributed between a Linux machine and a Raspberry Pi 2 Model B.

The Linux machine hosted three actors:

• std.CountTimer: provided by the std package of Calvin, sends on its out-port an integer increased every time of 1.

• io.StandardOut: provided by the io package of Calvin, prints to the standard output what it gets as input in its in-port token.

• mcalvin.Latency: this is a user defined actor that we implemented for this very example. Each time it receives something (token) on the in-port signal, it sends a message through the out-port request containing the current times- tamp. On its in-port diff, it receives a timestamp and then it calculates the difference between that and the current timestamp. The result is shipped to the StandardOut in-port token through the out-port output.

The Raspberry Pi 2 hosts the mcalvin.Echo actor which its function is to receive

the input on its in-port request and forwards it directly to its out-port response.

(21)

2.7. MBED OS

The source code below is the CalvinScript implementation of the example showed in Fig. 2.2:

/* Actors declaration */

count = std.CountTimer() sink = io.StandardOut() lat = mcalvin.Latency() echo = mcalvin.Echo() /* Ports connection */

count.integer > lat.signal lat. output > sink.token lat.request > echo.request echo.response > lat.diff

the code is really easy and clean as it only declares the actors and it defines the connection between their ports, making use of the > sign that act like an arrow that gives the direction of the connection.

2.7 mbed OS

mbed OS is an operative system created by ARM which run on the top of ARM mbed-enabled boards. It allows developers to write their code in C++ and it is possible to access a whole set of APIs providing common functionality to the application layer. mbed OS is specifically designed for CRDs so that can run in background, providing the most efficient service for the limited hardware it runs on top of. The main characteristics of this operative system we find:

• Modularity: it provides, through the very same code, common functionality to all the compatible boards. Additionally, it is possible to extends specific functionality with user defined modules that create hardware specific inter- faces.

• Single threaded and event-driven: it provides tools for having an impor- tant coding experience also on small devices.

• The Hardware Abstract Layer (HAL) is the same for all the boards, mean- ing that all the devices are provided with the same set of APIs. Behind the scenes, mbed OS automatically matches the software interface with the spe- cific hardware it is running on. This is one of the strongest point of this projects: the developers write one application and it is possible to deploy it on all the devices which are supported by mbed OS.

• Efficiency in managing the power consumption and the scheduling of tasks,

especially for low power devices.

(22)

• Security, it is possible to use TLS protocol

• It is possible to choose between many types of network interfaces, like Wi-Fi, BlueTooth Low Energy (BLE), Ethernet, 6LoWPAN.

• It supports device management protocols like LWM2M and CoAP, so that the device can be updated with bulk operations.

mbed OS is just a component of the development kit, which exposes a set of APIs common to all the boards mbed-enabled, but ARM supply also a build system called yotta[23] that allows the deployment of the same source code on different devices.

The philosophy is that the developer writes once and deploys many times. In fact, yotta combines the application source code with the mbed OS code and with any reusable libraries that the developer decides to use within its project. With yotta it is possible to builds two types of things: reusable libraries and executable modules.

Figure 2.3: A Freescale FRDM-K64F: an mbed OS enabled board mounting a MK64FN1M0VLL12 MCU (120 MHz, 1 MB flash memory, 256 KB RAM), an RGB LED and an FXOS8700CQ accelerometer and magnetometer

We will now show an example of how to build an executable modules that will be able to run on an mbed-enabled device, for instance, the Freescale FRDM-K64F[24], shown in Fig. 2.3.

1 $ yotta init

2 $ yotta search

3 $ yotta target < name_of_target >

4 $ yotta target

5 $ yotta install mbed

drivers

6 $ yotta build

(23)

2.7. MBED OS

Line 1, creates all the necessary files and folders that are required for a minimal application:

• module.json: this is the file that contains all the dependencies, to reusable libraries, that the application will use. For example, the most used dependency would be the mbed-drivers that enables the application using the mbed OS APIs.

• source folder which contains all the source code for our executable module.

Everything inside this folder will be included in the compilation process.

• test folder, used for running tests on the files included in the source folder.

Line 2 helps the user finding the supported mbed-enabled boards. For example, it

is possible to insert, after the word “search”, a string and the program will return

a list of target matching that string. Afterwards, a target can be added using the

command at line 3. With line 4, it is possible to check which targets has been added

to the project, and which targets can be targeted for deploying the application. Line

5, shows how it is possible to add a reusable module to the application (it is possible

to use yotta search also for modules). Finally, line 6 show how to build the binary

application that will run on the mbed-enabled board.

(24)
(25)

Chapter 3

µCalvin

The full stack of Calvin implements several features and can run wherever the Python language is supported. On the other hand, Constrained Resource Devices (CRD) may not have the opportunity to run the Python interpreter, due to the lack of resources and operative system. For this reason, we put effort in creating µCalvin: a version of Calvin that is written in C/C++ and implements a minimal subset of the full runtime. Consequently, the memory allocated on the CRDs, in order to run Calvin, would be as small as possible. Also, from a system perspec- tive, running µCalvin on many devices and running the full runtime only on one supported hardware, may result more efficient.

In this chapter, we present µCalvin: is a minimal Calvin runtime for mbedOS.

Figure 3.1: µCalvin architecture. µCalvin runs on the top of the HW and is bound

to a full Calvin runtime and act as a slave, meaning that it only waits for incoming

connections. This fact is highlighted by the hard connection. From the picture, it

is also clear the distributed nature of a Calvin application, which is defined as a

unique piece of software, and then its actors are shipped on different platforms.

(26)

Word Definition

System It is the piece of SW the client interacts with. It starts at the APIs level, includes the Calvin full stack runtime, and it terminates with the Constrained Resource Devices.

Constrained Resource Device (CRD)

The word identifies a small device with limited computational power such, for example, a Raspberry Pi, an Arduino, an mbed-compliant board (i.e. ST NUCLEO, ARM Cortex-MX micro controller), etc...

Runtime (RT) It is the basement of the Calvin framework and provides fundamental features without which the system can not exist and run.

Actor It is the fundamental computational entity in Calvin. It is made up of ports, which can be both input or output, and performs a set of action.

Token Tokens are the object exchanged among the actors and those are sent from / to ports.

Port Ports are entry / exit points of an actor and they are used to exchange tokens. Those are commonly called in-ports and out-ports, respectively for inputs and outputs.

Tunnel It is the communication link where the tokens are exchanged between actors.

Table 3.1: The glossary of the system map each term to a definition so that the reader knows the exact meaning of the words.

3.1 Requirements analysis

The goal of this section is to identify a minimal set of functionality in order to build a runtime that can run on mbed devices. For this reason, all the functionality to be included will be listed and analyzed in depth, to make it easier to replicate them on the CRD. As mbedOS has to be programmed in C++, this imposes to us a constraint so that µCalvin is to be implemented in such language.

Fig 3.2 shows the use case diagram for µCalvin. All we want for this project, is to be able to use Calvin also on embedded devices and this implies that we should be able to send and receive tokens from other actors. To do so, it is important that we provide functionality such as actor migration, restore previous port connections and create a communication tunnel, that may be also encrypted for security reasons.

An important element of this analysis is the glossary, which is responsible to provide a mapping between a word and the corresponding meaning. In fact, the glossary is particularly useful because it eliminates ambiguities and misunderstand- ings when a particular word is mentioned in the text. The glossary is presented in Table 3.1.

3.1.1 Joining the network

The first step through the implementation of a minimal runtime passes through the

ability to join an existing Calvin network. Calvin is built on the top of a Distributed

(27)

3.1. REQUIREMENTS ANALYSIS

Hash Table

1

(DHT), for instance Kademlia[27], so we want our small devices to be placed somewhere in the domain space. If we were to do so, for example, with two runtime, we would use the control API of one runtime to send an invitation for joining the network to the other runtime. The Calvin Control API are at HTTP level so that everything is invoked through POST and GET methods. To invite a runtime to join another one, we could use the following commands:

$ csruntime --host localhost --controlport 5001 --port 5000

$ csruntime --host localhost --controlport 5003 --port 5002

$ cscontrol http://locahost:5001 nodes add calvinip://localhost:5002 The first two commands launch the two runtimes respectively on port 5000 and 5002, while the last one tells the first runtime to send a join request to the second one. As a confirmation of the join operation we will get something similar to the following message:

Listing 3.1: Output of JOIN REQUEST operation

1 {u ’ calvinip :// localhost :5002 ’: [u ’84 efb694−3569−4863−97d5−4 e749e6b1bd7 ’, 200]}

From the moment we get the above message, the two runtimes are linked together in a network. What we have at the moment is not enough to implement anything, we need to understand what had happened behind the scenes. There are two options to do so, look at the Calvin’s source code or eavesdrop the network traffic with a network analyzer (i.e. Wireshark[28]). The latter option is the one utilized.

First of all, 5001 (from now on, the runtime is identified by its port or control port) accesses its Control APIs sending to itself a POST /peer_setup containing the following data:

{"peers": ["calvinip://localhost:5002"]}

After this, 5001 knows about the peer to contact to build the connection. The next operation in the sequence, is 5001 to contact 5002, sending a JOIN_REQUEST message via TCP:

{"cmd": "JOIN_REQUEST", "serializers": ["json"], "id": uuid1,

"sid": uuid2}

with uuid1 and uuid2 Universal Unique IDentifier (UUID) generated by the Python interpreter. 5002 can now send the JOIN_REPLY message back to 5001:

{"cmd": "JOIN_REPLY", "serializer": "json", "id": uuid3, "sid": uuid2}

Note that the "sid" field is the same in both the messages. The final message is sent by 5001, and it is a confirmation: HTTP/1.0 200 OK containing the acknowledgment string we got in listing 3.1.

1See also other DHT like Chord[25] and Pastry[26]

(28)

3.1.2 Actor migration

Another key aspect we want to have in µCalvin, is the possibility to host an actor which is migrated from a another runtime. Without this function it would be definitely impossible to use Calvin on CRDs. The actor layer is out of the scope of this project and it will not be implemented. Nevertheless, in order to provide some migration functionality, the actor layer is hard-coded into µCalvin. In other words, µCalvin will host some simple actor that performs some basic operations (i.e. a counter, a printer, etc...) and it will not be possible to migrate custom actors

2

.

Before being able to migrate one actor, we must deploy an application which has at least two actors. For our particular case, we chose to take into consideration test/scripts/test1.calvin which consist in one std.Counter (one out-port) and a io.StandardOut (one in-port) actor. The counter sends tokens (numbers) to the sink which prints everything on standard output. It is possible to deploy a calvinscript through the Control APIs using the command:

$ cscontrol http://<runtime_address>:<controlport>

deploy tests/scripts/test1.calvin

If everything is ok, the reply of the runtime is similar to:

{u’application_id’: u’0a4c8b57-2de2-42c6-988d-bfc0ad80a809’, u’actor_map’:{

u’test1:src’: u’caf1479c-1c2b-4f13-8f0e-416630d41760’, u’test1:snk’: u’90433fb4-9d06-4009-8c62-8e8dbc94dfc5’}}

Now, we got from the runtime the application and the actors id and it is now possible to migrate one actor making use of this information.

Also this time, we use the Control APIs and we migrate the actor with the following command:

$ cscontrol http://<first runtime address>:<controlport>

actor migrate <actor id> <other runtime id>

This command starts a POST call:

POST /actor/9dd5a119-5a75-420a-838c-bc53be1b54f7/migrate with the following JSON data as parameter:

{"peer_node_id":uuid2}

Underneath, at transport level, 5001 sends to 5002 this JSON data:

2This is a limitation of Calvin. In fact, it does not allow to receive an actor if it is not implemented also on the other runtime. Currently, this problem is under investigation.

(29)

3.1. REQUIREMENTS ANALYSIS

{"to_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34",

"from_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb", "state":

{"prev_connections": {"actor_name": "test1:snk", "inports":

{"f10ba8af-973b-491a-a675-c0d15db230b0":

["ae46079a-51ba-46c5-af26-78e6e3d417fb",

"5115ae41-3d01-4121-863a-b2d1743dbc1e"]},

"actor_id": "9dd5a119-5a75-420a-838c-bc53be1b54f7", "outports":

{}}, "actor_type": "io.StandardOut", "actor_state":

{"store_tokens": 1, "name": "test1:snk", "inports": {"token":

{"name": "token", "fifo": {"write_pos": 170, "readers":

["f10ba8af-973b-491a-a675-c0d15db230b0"], "fifo":

[{"data": 0, "type": "Token"}, {"data": 0, "type": "Token"}, {"data": 0, "type": "Token"}, {"data": 0, "type": "Token"}, {"data": 0, "type": "Token"}], "N": 5, "tentative_read_pos":

{"f10ba8af-973b-491a-a675-c0d15db230b0": 170}, "read_pos":

{"f10ba8af-973b-491a-a675-c0d15db230b0": 170}}, "id":

"f10ba8af-973b-491a-a675-c0d15db230b0"}}, "quiet": 1,

"_deployment_requirements": [], "tokens": [1, 2, 3,...,170],

"_managed":

["tokens", "store_tokens", "quiet", "name", "id",

"_deployment_requirements"], "outports": {},

"id": "9dd5a119-5a75-420a-838c-bc53be1b54f7"}},

"cmd": "ACTOR_NEW", "msg_uuid":

"2b73997c-5e1b-4d39-a21b-9683a20bcdce"}

In this JSON string there are a lot of information we will be very interested in later on in this chapter, in particular:

• name: the name of the actor assigned in the calvinscript

• inports: all the in-ports of the actor

– id: UUID of the port

– name: the name of the port

– fifo: the FIFO queue of the actor which contains the token already

received.

• outports: all the out-ports of the actor

– id: UUID of the port

– name: the name of the port

– fifo: the FIFO queue of the actor which contains the token already sent.

• id: the unique identifier of the actor

(30)

• actor_type: the type of the actor.

Inside actor_state there are also the arguments that may have been passed to the actor during its creation (i.e. quiet, store_tokens. etc...). When the message reaches 5002, the actor is created and its state restored.

3.1.3 Opening a tunnel and port connection

In Calvin, information between actors is propagated through the ports making use of TOKENs, but how and where they are shipped throughout the network? Inter- actors communication must happen within a communication link called TUNNEL.

After the creation of the new actor, 5002, asks 5001 to open a new tunnel using the following message:

{"from_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34", "cmd":

"TUNNEL_NEW", "tunnel_id": "810d7467-16c0-471b-ad99-5dfdda80ef86",

"to_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb", "policy":

{}, "type": "token", "msg_uuid":

"48869e0c-91f4-401a-b795-c5242e5c4c90"}

Here, the important information are the cmd: NEW_TUNNEL command and the tunnel_id, which is used to refer to that particular tunnel.

Successively, 5001 sends back to 5002 a REPLY message that serves as a confir- mation for the creation of the new tunnel.

{"to_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34",

"from_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb", "cmd":

"REPLY", "value": {"status": 200, "success_list":

[200, 201, 202, 203, 204, 205, 206], "data": {"tunnel_id":

"810d7467-16c0-471b-ad99-5dfdda80ef86"}}, "msg_uuid":

"48869e0c-91f4-401a-b795-c5242e5c4c90"}

The tunnel id is in value.data.tunnel_id and has the very same value of the tunnel just opened. In value.status there is 200, meaning that everything was fine, and a list of all the correct statuses (values from 200 to 206). If the runtime gets a message with a status different from those ones, it means that an error occurred.

At this stage, 5002 has an instance of the new actor which is completely discon- nected from the system. For this reason, the runtime sends to 5001 a PORT_CONNECT message specifying the ports to connect together.

{"from_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34",

"peer_port_name": null, "peer_actor_id": null, "cmd":

"PORT_CONNECT", "peer_port_id":

"5115ae41-3d01-4121-863a-b2d1743dbc1e", "tunnel_id":

"810d7467-16c0-471b-ad99-5dfdda80ef86", "to_rt_uuid":

(31)

3.1. REQUIREMENTS ANALYSIS

"ae46079a-51ba-46c5-af26-78e6e3d417fb", "msg_uuid":

"ea1ec208-cd31-4a69-b069-caac919bc45a", "port_id":

"f10ba8af-973b-491a-a675-c0d15db230b0", "peer_port_dir": null}

In a nutshell, 5002 is asking to 5001 to connect the port specified in field peer_port_id), of the sink actor, to the port specified in field port_id, of the peer’s actor port (the counter actor on 5001) via the tunnel that was opened previously.

Runtime 5001 sends and acknowledgment back to 5002:

{"to_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34",

"from_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb", "cmd":

"REPLY", "value": {"status": 200, "success_list":

[200, 201, 202, 203, 204, 205, 206], "data": {"port_id":

"5115ae41-3d01-4121-863a-b2d1743dbc1e"}}, "msg_uuid":

"ea1ec208-cd31-4a69-b069-caac919bc45a"}

Usually, cmd fields that contains the word REPLY, like in this case, represent confir- mation of something. Within the data field, there is the connected port and inside the value field, there is status: 200 meaning that everything is fine for runtime 5002. Now, also 5002 wants to tell 5001 that everything is fine. Another REPLY is sent and the ports are correctly connected:

{"to_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb",

"from_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34", "cmd":

"REPLY", "value": {"status": 200, "success_list":

[200, 201, 202, 203, 204, 205, 206], "data": null}, "msg_uuid":

"2b73997c-5e1b-4d39-a21b-9683a20bcdce"}

3.1.4 Tokens exchange

In the previous subsections we set up all it was needed to be able to enable actors to talk to each other. What is missing now is the exchange of information between them. In Calvin, tokens are exchanged and they transit through a tunnel. The example we are taking into consideration now, wants a counter sending tokens (containing integers) to a sink that will print them out.

Here an example of this token:

{"to_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34",

"from_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb", "cmd":

"TUNNEL_DATA", "value": {"sequencenbr": 170, "token": {"data":

171, "type": "Token"}, "cmd": "TOKEN", "port_id":

"5115ae41-3d01-4121-863a-b2d1743dbc1e", "peer_port_id":

"f10ba8af-973b-491a-a675-c0d15db230b0"}, "tunnel_id":

"810d7467-16c0-471b-ad99-5dfdda80ef86"}

(32)

To notice that the token is sent through the tunnel previously created. The most interesting field inside the message is value, which contains the actual token. The tokens are sent with command TUNNEL_DATA, the token is inside the field value identified by command TOKEN. It is not incorrect to say that the TUNNEL_DATA encapsulates TOKEN. Also, source port and destination port are present.

{"to_rt_uuid": "ae46079a-51ba-46c5-af26-78e6e3d417fb",

"from_rt_uuid": "ddfd5db3-665b-4bab-bd88-ea1303201b34", "cmd":

"TUNNEL_DATA", "value": {"sequencenbr": 170, "peer_port_id":

"f10ba8af-973b-491a-a675-c0d15db230b0", "cmd": "TOKEN_REPLY",

"port_id": "5115ae41-3d01-4121-863a-b2d1743dbc1e", "value":

"ACK"}, "tunnel_id": "810d7467-16c0-471b-ad99-5dfdda80ef86"}

In this section, we analyzed the traffic through the network when an application is deployed and an actor migrated to another runtime. Now, we know what we have to build in order to set Calvin up on a CRD. In the next sections, we are going to make use of the software engineering approach in order to develop a software system that will provide the requirement we want to satisfy with µCalvin. We will produce several UML 2.0[29] diagrams that will describe the system from the perspectives of structure, interaction and behavior.

3.2 Domain Model

In this section we are going to model all the entities we want to have in our minimal runtime. Usually, the domain model should be completely independent from the used technologies.

In the following subsections, we are going to look at the problem from three different perspectives, namely structure, interaction and behavior.

3.2.1 Structure

This section exposes the structure of the domain, as it comes from the requirement analysis, without any influences by the technologies we are going to use later on for the implementation. The output of this analysis is the class diagram showed in figure 3.3.

Our domain is composed by five entities. microCalvin is the main entity which has the only purpose to run the system, so that Calvin can be used also on CRDs.

This component is related to Tunnel which has the responsibility to provide a

communication link between the full Calvin stack and µCalvin. The tunnel can

provide also encryption, but this is out of the scope of the project as security is not

taken into account. microCalvin also encapsulate Actor entities that can perform

actions to affect the system. These actions, usually, consume and / or produce

Tokens, which is another important entity of the domain. Tokens are sent through

Ports defined by the Actor. These Port are of two kinds: in-ports and out-port,

(33)

3.2. DOMAIN MODEL

respectively for input and output. They have an unique identification number, they are connected to another port and they have a FIFO queue where to store Tokens.

3.2.2 Interaction

Sequence diagrams are used to understand the interactions that occur among the objects of the system. Fig. 3.4 shows these interactions when the user calls the action method. First of all, the method is executed and a action is performed (action may include also a reading from the FIFO queue of any of the in-ports).

After this, usually, a Token is created so that the Actor pushes it into the FIFO queue of its relative Port. Finally, at the end of the action, the token is sent to the actor connected to that port through the tunnel (by the microCalvin entity).

Now that we have analyzed how an actor performs its action, we look at Fig. 3.5 which shows, from the domain point of view, how the main loop of microCalvin works. The run method runs forever and the first operation is to get all the actors contained into the microCalvin object. Then, one at a time, it invokes the action method on each actor and the tokens produced are flushed from the FIFO queues through the tunnel. Not shown in the sequence diagram, the waiting time for µCalvin for receiving a JOIN_REQUEST from another runtime and the operation to build up a connection with the migration of an actor. This is going to be described in detail in the next section because it has to solve some problem that are not part of the domain.

3.2.3 Behavior

The activity diagrams are very important for understanding which task is executed and in which order. From time to time the developer may lose the difference between activity and sequence diagram: the former describe what is performed while the latter focuses mainly on the interaction between the objects of the system.

Very important for the domain is to understand what has to be done by the whole

system, Fig. 3.6 tells us this. During the initial phase, the system is just waiting

for a connection request, this is an indicator that µCalvin is a passive component

which does not take any initiative for connection. The only component responsible

for connection is a full Calvin runtime. The next operation to be executed is to

set up a connection with the runtime and then hosting an actor which migrates

on µCalvin and restores the previous connections of its ports. Then, there is a

sequence of operations executed in a loop until the user manually terminates the

system (i.e. unplugging the power cable or pressing the reset button on the micro

controller board). These operations are respectively the firing of the action, which

consist in reading from a FIFO queue of a port, and / or producing an output token

to be placed in another port’s FIFO queue.

(34)

System boundary

User

Use Calvin on CRD

Migrate actors Connect ports

Create a tunnel Send and receive tokens

«include»

«include»

«include»

«include»

Figure 3.2: Use case diagram for µCalvin.

Actor +getID() +getInPorts() +getOutPorts() +action()

Port +getID() +getPeerID() +getFIFO() Token

+getValue() Tunnel

+getID()

microCalvin +run()

1..*

Figure 3.3: Class diagram for the domain model.

ActorAction interaction

a: Actor p: Port

t: Token user: Client

1 : action

2 :

«create»

3 : pushToken

4 : pushToFifo

Figure 3.4: Sequence diagram of the execution of the action that produces a token.

(35)

3.2. DOMAIN MODEL

microCalvinRun interaction

c: Client

mc:

microCalvin

t: Tunnel

while true seq

until actor is not null seq

1 : run

2 : getActors

3 : action

4 : sendToken

Figure 3.5: Sequence diagram for run method of µCalvin.

Wait for JOIN REQUEST

Setup connection and receive ACTOR

Fire actors action Send tokens

[terminate]

Figure 3.6: Activity diagram for the system of µCalvin.

(36)

3.3 Problem analysis

In this phase of the software development process we are going to define the logic architecture of the system, so that we are already looking to a solution for our problem.

We already know from section 3.1, that we are going to use mbedOS platforms and C++ so the following sections are technology dependent and the changes made after section 3.2 are made because of this.

Like in section 3.2, we analyze the problem from the same perspective points:

structure, interaction and behavior.

3.3.1 Structure

As often in Object Oriented Programming projects, a layered architecture is used.

The first layer is for network communication, the second layer includes the applica- tion logic and the third one, the application APIs.

Fig. 3.7 shows the class diagram for the domain model. NetworkLayer is an in- terface that exposes two very simple operations: read and write which respectively read and write from / to the network. read returns a string while write sends one.

In addition, this interface has some worthy to mention methods which calculates the length of a received message (or a message to be sent), unwraps correctly the buffer and get the content of the message.

NetworkLayer itself is not enough as it is only an interface, and we actually need a concrete class that reads and sends data through a network interface. To this purpose, we have EthernetLayer which implements NetworkLayer on a Ethernet interface. It is possible to implement whatever network interface is desired (i.e.

BlueToothLayer, nRFLayer, etc...).

Actors are the fundamental computational unit of Calvin, an Actor entity can not be missing. Actor is an abstract class which requires to its specification classes to implement the virtual method action which performs its task. The actor layer is out of the scope of this project, nonetheless, we implemented a few ones for demonstration purposes (i.e. ActorStandardOut, ActorCounter, etc...). The ac- tor, except for the action performed, is a collection of inports (inputs) and outports (outputs). More in detail, a Port is an entity which has a Unique Universal IDenti- fier (UUID), it is connected to another port (with another UUID) and has a FIFO queue where its inputs or outputs are placed so that the actor can process them in its action.

In order to order keep track of the actors currently in the runtime, we defined an entity called ActorManager which acts as an actors container. It provides access to all the actors and has functionality to create and remove them.

The core of the whole system is the MessageHandler entity. This component

is responsible for the management of all the incoming messages and provides the

correct reply. All the outgoing messages are put into an outbox which is modeled as

a FIFO (First-In First-Out) queue. Additionally, when an actor is migrated from

(37)

3.3. PROBLEM ANALYSIS

microCalvin -in b o x: queue -outb o x: queue +run() Net w orkLa y er +send(c har*) +receiv e(): char* EthernetLa y er Blueto othLa y er A ctor +action() +getInP orts(): queue<P ort> +getOutP orts(): queue<P ort> +getID(): char*

P ort +getID(): char* +getP eerID(): char* +getFifo(): queue A ctorManager A ctorStdOut A ctorCoun ter

MessageHandler +handleMessage(c har*) +sendT ok en() Figure 3.7: Domain mo del structure, class diagram for µ Calvin.

(38)

the full runtime, it creates the new actor using the functionality exposed by the ActorManager.

Finally, the microCalvin entity is the third layer and is the entry point to the application which can be invoked through the run method. It encapsulates two FIFO queues, one for the incoming messages and one for the outgoing ones, in transit through the minimal runtime. Then, it instantiates the ActorManager which is ready to accept migrating agents from others runtimes. Finally, also a NetworkLayer interface is included in order to interact with the network.

3.3.2 Interaction

In this section we will look at the components that build the system from the point of view of the interaction.

We start with the µCalvin loop represented in Fig. 3.8. Firstly, the queue of the incoming messages is processed, meaning that every message is popped out and handled by the MessageHandler (invoking handleMessage). Then, the same thing is executed for the outgoing messages queue, with the difference that now the messages are not handled, but sent by the NetworkLayer and then popped out from the queue. At this stage, the message queues are empty and they are ready to be filled again. In fact, the ActorManager will provide the list of all the actors present in the runtime, and their action method will be fired. This process might produce some output which is kept inside the FIFO queue of the issuing port of the actor.

Now, all the ports of all the actors are iterated and every FIFO queue is processed, meaning that the tokens will be moved from there, and pushed to the queue of the outgoing messages ready to be sent in the next iteration of the main loop.

The next component to be analyzed is the NetworkLayer, in particular its meth- ods read and send. read (Fig. 3.9) reads a stream of bytes, gets the content of the message invoking the private method getPacketContent and returns a char*. On the other side, in Fig. 3.10, send takes as input a char*, which is the content to be sent, it calculates its dimension and then it appends the content of the message and sends everything throughout the stream connection. Every programming lan- guage, when using the network, sends messages with a certain conventions and the dimension of the received message is essential for the decoding (in our particular scenario, Python needs 4 bytes to specify the length of the message content).

Finally, MessageHandler is the most interesting and complex class as it al-

lows the fulfillment of the requirements listed in section 3.1. Its core method,

showed in Fig. 3.11, is named handleMessage because it manages all the sup-

ported operations required by the full runtime. First of all, it parses the json

message and then it processes the message according to its cmd field. When this

field is equal to JOIN_REQUEST, the method handleJoin is called and, sequentially,

also handleNewTunnel, which is responsible for the creation of a communication

tunnel between the two runtimes. After this step, the two runtimes are part of

the same network and they have already set up the communication link for send-

ing and receiving tokens (which is identified by a UUID). When cmd is equal to

(39)

3.3. PROBLEM ANALYSIS

microCalvinloopinteraction rt: microCalvinam: ActorManagerinboxoutbox frt:User

nl: NetworkLayermh: MessageHandler actorisnullloop

1:run 2:getMessages 3:messages 4:handleMessages 5:getMessages 6:messages7:send 8:getActors 9:actors 10:action 11:sendTokens

Figure 3.8: Domain mo del in teraction, sequence diagram for µ Calvin’s main lo op.

(40)

NetworkLayerRead interaction

rt:

microCalvin

nl:

NetworkLayer

1 : readInbox 2 : read

3 : read

4 : getPacketContent

5 : fillInBox

Figure 3.9: Sequence diagram for read operation of NetworkLayer.

NetworkLayerSend interaction

rt:

microCalvin

nl:

NetworkLayer

1 : send

2 : sendLength

3 : sendMessage

Figure 3.10: Sequence diagram for send operation of NetworkLayer.

References

Related documents

Unfortunately, existing cloudlet solutions are stateless, therefore all the data would still have to be send to the cloud after processing, which can saturate the network with

Threat #5: This attack was also successful; a nefarious user could easily overwhelm the network the plug is connected to with the intention to drown out the

Recently, there are emerging studies on hardware assisted security on IoT related devices such as: building a unified identity verification framework based on PUFs [36], FPGA

In the paper titled “A Secure and Scalable Data Com- munication Scheme in Smart Grids,” the authors present communication architecture for smart grids and propose a scheme to

Among others, the IoT will allow for first movers to differentiate themselves from a commoditized market and improve on customer relationships (Canaan et al., 2016; Reifel

Alla tio artiklar i denna litteraturstudie utvärderade digitala interventioner för personer med demens eller personer som har risk att få demenssjukdom. Sju artiklar visade

As it arises from the sections above, the Data Protection Regulation attempts to create a stronger framework for the protection of individual’s privacy by (i)

Inteno has overviewed one of these software frameworks, called AllJoyn, they believe that it would simplify the discovery, com- munication, and management of connected