Evaluation of IoTivity: A Middleware Architecture for the Internet of Things

KAJSA ELFSTRÖM

KTH ROYAL INSTITUTE OF TECHNOLOGY INFORMATION AND COMMUNICATION TECHNOLOGY

This master thesis project was carried out in collaboration with

Tritech Technology AB Industrial supervisor: Mats Malmberg

Evaluation of IoTivity: A Middleware Architecture for the Internet of Things Utvärdering av IoTivity: En Mellanvaruarkitektur för Sakernas Internet

KAJSA ELFSTRÖM Examiner: Mark T. Smith KTH Supervisor: Kalle Ngo KTH School of Information and Communication Technology

Abstract

Today the Internet of Things (IoT) lacks universal standards for communication and interaction between devices. There is a wide collection of diverse software architectures for IoT applications on the market, where smart devices from different manufacturers are often unable to interact with each other. A standards organization within IoT gaining recognition is the Open Connec- tivity Foundation (OCF), an industry group delivering an IoT software framework specification and a product certification program. Open Connectivity Foundation (OCF) is funding an open source reference implementation of the specification called IoTivity, which runs as middleware intended to be portable to all operating systems and connectivity platforms. The goal of the OCF is to enable interoperability be- tween IoT devices regardless of manufacturer, , chipset or physical transport. Through a literature review, the key functional and non-functional requirements for IoT middleware architectures were found. Functionality requirements identi- fied were data management, resource management, resource discovery, and context- awareness. The quality attributes were found to be interoperability, adaptability, scalability, security, and real-time behavior. In this thesis project, IoTivity was evaluated with respect to these requirements with the scenario-based Method for Evaluating Middleware Architectures (MEMS). As a part of MEMS, a case study of implementing a building management system (BMS) with IoTivity was conducted. Results showed that, within the framework of the case study, IoTivity complied with three out of four functional requirements, and three out of five quality require- ments identified for IoT middleware architectures. One of the quality requirements, security, was not evaluated in this study. Keywords: Internet of Things, IoTivity, Middleware, Open Connectivity Foun- dation, Standard. Referat

Idag finns det redan många olika mjukvaruarkitekturer för sakernas internet, på engelska Internet of Things (IoT), ute på marknaden. Ett problem är att det ännu inte finns några brett accepterade standarder för hur dessa saker ska interagera. Det kan ofta innebära att uppkopplade enheter från olika tillverkare inte fungerar ihop. Det finns ett flertal organisationer som försöker etablera standarder för saker- nas internet, på alla olika nivåer i kommunikationskedjan. En av de organisationer som nämns allt oftare är Open Connectivity Foundation (OCF). Det är en grupp av ledande företag som har specificerat ett mjukvaruramverk för IoT och ett tillhörande program för produktcertifiering. De sponsrar även en referensimplementation av detta ramverk med öppen källkod som kallas IoTivity. Denna referensimplementa- tion körs som en mellanvara och är tänkt att vara portabel till flera olika mjuk- och hårdvaruplattformar. OCFs långsiktiga mål är att möjliggöra kommunikation mel- lan uppkopplade enheter oberoende av deras tillverkare, operativsystem, chip-set och kommunikationsteknik. Genom en studie av tidigare forskning kunde de mest väsentliga funktionella och kvalitativa kraven på IoT-mellanvara sammanställas. Bland de funktionella kraven fanns datahantering, resurshantering, kontextmedvetenhet och mekanismer för att upptäcka enheter i nätverket. De kvalitativa kraven inkluderade interoperabilitet, anpassningsbarhet, skalbarhet, säkerhet och realtidsbeteende. Examensarbetet har utvärderat IoTivity med avseende på ovan nämnda krav genom en scenariobaserad evalueringsmetod kallad Method for Evaluating Middle- ware Architectures (MEMS). Som en del av MEMS genomfördes en fallstudie där en systemprototyp för fastighetsautomation implementerades med IoTivity. Resultat från genomförda experiment visade att, inom ramarna för fallstudien, kunde IoTivity uppfylla tre av de fyra funktionella kraven och tre av de fem kval- itativa kraven. Ett av de kvalitativa kraven, säkerhet, utvärderades inte i det här projektet. Nyckelord: Sakernas Internet, IoTivity, Mellanvara, Open Connectivity Founda- tion, Standard. Acknowledgements

I would like to express my thanks to my examiner Mark Smith, and supervisors Kalle Ngo and Mats Malmberg, for your helpful feedback and inspiration. To all colleagues at Tritech, thank you for welcoming me with open arms and making the time of this thesis project fun and memorable. I also wish to extend my thanks to my family for their support and encourage- ment during these past years of studying at KTH.

Kajsa Elfström, Stockholm, April 2017

Contents

List of Figures i

List of Tables iv

Acronyms vii

1 Introduction 1 1.1 Background ...... 1 1.1.1 Middleware for the Internet of Things ...... 2 1.1.2 Design Patterns for the Internet of Things ...... 2 1.2 Problem ...... 3 1.3Purpose...... 4 1.4 Goals ...... 4 1.5 Benefits, Ethics and Sustainability ...... 4 1.6Method...... 5 1.7 Delimitations ...... 5 1.8 Outline ...... 6

2 Theoretical Background 7 2.1 Common Concepts of the Internet of Things ...... 7 2.1.1 Communication Models ...... 8 2.1.2 Internet of Things Stack ...... 9 2.2 Middleware for the Internet of Things ...... 10 2.2.1 Motivation of a Middleware Solution ...... 10 2.2.2 Functional Requirements ...... 11 2.2.3 Non-Functional Requirements ...... 13 2.3 Open Connectivity Foundation and IoTivity ...... 15 2.3.1 The Open Connectivity Foundation Framework ...... 16 2.3.2 IoTivity ...... 16 2.3.3 Architecture Overview ...... 16 2.3.4 Core Framework ...... 17 2.3.5 Architectural Design Patterns ...... 21 2.4 Summary of Related Work ...... 27 Contents

3 Methodology 29 3.1 Method for Evaluating Middleware Architectures ...... 29 3.1.1 Description and Motivation ...... 29 3.1.2 Motivating a Case Study in MEMS ...... 29 3.1.3 Steps of MEMS ...... 30 3.2 Equipment for System Prototype ...... 32

4 Case Study 33 4.1 Case Scenario ...... 33 4.1.1 Fictional Project ...... 33 4.1.2 Building Management System ...... 34 4.1.3 Automatic Monitoring and Control Applications ...... 36 4.2 Prototype ...... 37 4.2.1 Building Lighting System Device ...... 38 4.2.2 Emergency Evacuation System Device ...... 38 4.2.3 Entrance Security System Device ...... 39 4.2.4 HVAC System Device ...... 39

5 Evaluation Plan 41 5.1 Key scenarios ...... 41 5.2 Testbed Components ...... 50 5.3 Procedures for Interoperability Experiments ...... 52 5.4 Procedures for Adaptability Experiments ...... 53 5.5 Procedures for Scalability Experiments ...... 53

6 Results 57 6.1 Results of Experiments Testing Interoperability ...... 57 6.2 Results of Experiments Testing Adaptability ...... 57 6.3 Results of Experiments Testing Scalability ...... 59

7 Discussion 65 7.1 Discussion ...... 65 7.1.1 Key Findings from Experiment Results ...... 65 7.1.2 Validity of Experiments ...... 69 7.1.3 Influence of Design Patterns ...... 71 7.1.4 Further Reflections on Quality Requirements ...... 73 7.2 Conclusions ...... 74 7.3 Recommendations for Future Work ...... 75

Bibliography 75

A Resource Type Definitions of Building Management System I A.1 Property Definitions for Single Resource Types ...... I A.1.1 Air Quality Sensor ...... I A.1.2 Alarm ...... II A.1.3 Door ...... II A.1.4 Door Lock ...... II Contents

A.1.5 Elevator Control ...... II A.1.6 Light Source ...... III A.1.7 Location ...... III A.1.8 Mode ...... III A.1.9 Motion Detector ...... III A.1.10 Operational State ...... IV A.1.11 Smoke Detector ...... IV A.1.12 Surveillance Camera ...... IV A.1.13 Temperature ...... IV A.1.14 Thermostat ...... V A.1.15 Time Interval ...... V A.1.16 Ventilation ...... V A.2 Required Resource Links of Collection Resource Types ...... VI A.3 Resource Type and Interface Definitions ...... VII

B Modification of Server Application Source Code in Key Scenarios 8to10 IX

i Contents

ii List of Figures

2.1 An overview of communication models for the Internet of Things (adapted from figures of [1])...... 8 2.2 An example of an Internet of Things stack...... 10 2.3 The functional blocks of the OCF framework architecture (adapted from Figure 2 of [2])...... 17 2.4 The concepts of entity, resource, URI, property, and representation in the OCF resource model...... 18 2.5 An example illustrating the concepts of collection and link in the OCF resource model...... 19 2.6 The five steps of the observe mechanism in the OCF framework (adapted from Figure 32 of [2])...... 24 2.7 Communication for resource directory discovery and for resource di- rectory supported discovery queries (adapted from Figure 30 of [2]). . 26

4.1 Overview of building for which building management system proto- type was implemented...... 34 4.2 Overview of communication in building management system...... 36 4.3 An overview of the network setup for the building management system prototype...... 37

5.1 A utility tree for organizing quality attributes, sub-concerns, and key scenarios for the evaluation...... 43

6.1 A line chart showing resource request delay times in scenarios 12.1, 12.2, and 17. A marker represents the average value of the sample subset with larger, unexpected values. Error bars show standard deviation from the mean...... 60 6.2 A line chart showing resource request delay times in scenario 12.3. A marker represents the average value of the sample subset with larger, unexpected values. Error bars show standard deviation from the mean. 61 6.3 A line chart showing how the round-trip delay time per request changes with the number of requested resources in key scenarios 12.1 and 12.2. Error bars show standard deviation from the mean...... 62

iii List of Figures

6.4 A line chart showing how the one-way delay time per request changes with the number of requested resources in key scenarios 12.3 and 13. Error bars show standard deviation from the mean...... 62 6.5 A line chart showing how the round-trip delay time per resource changes with the number of requested resources in key scenario 17, comparing results for low and high quality of service (QoS). Error bars show standard deviation from the mean...... 63

iv List of Tables

2.1 An example of properties of a light resource represented with the OCF resource model (adapted from Table 30 in [2])...... 20 2.2 A table presenting some of the standard resource interfaces defined in the OCF framework (adapted from Table 8 in [2])...... 20

3.1 Device platforms used in test environment for building management system prototype...... 32

4.1 Resources and applications in building management system prototype. 35

5.1 Key Scenario 1 ...... 44 5.2 Key Scenario 2 ...... 44 5.3 Key Scenario 3 ...... 44 5.4 Key Scenario 4 ...... 45 5.5 Key Scenario 5 ...... 45 5.6 Key Scenario 6 ...... 46 5.7 Key Scenario 7 ...... 46 5.8 Key Scenario 8 ...... 46 5.9 Key Scenario 9 ...... 47 5.10 Key Scenario 10 ...... 47 5.11 Key Scenario 11 ...... 47 5.12 Key Scenario 12 ...... 48 5.13 Key Scenario 13 ...... 48 5.14 Key Scenario 14 ...... 48 5.15 Key Scenario 15 ...... 49 5.16 Key Scenario 16 ...... 49 5.17 Key Scenario 17 ...... 49 5.18 Metrics and scales for key scenarios...... 50 5.19 Testbed components used in the experiments...... 51

6.1 Experiment results of interoperability metric: Percentage of requests correctly processed...... 57 6.2 Experiment results of adaptability metric: Number of logical lines of code (LLOC) added/changed in source files...... 58

v List of Tables

6.3 Experiment results of adaptability metric: Number of source code software modules that required changes...... 58 6.4 Experiment results of scalability metric: RTD per request decreas- es/increases as the number of requested resources increases...... 59 6.5 Experiment results of scalability metric: OWD per request decreas- es/increases as the number of requested resources increases...... 59 6.6 Experiment results of scalability metric: Number of requested re- sources before exceeding 10 sec RTD or OWD...... 59

A.1 Common properties of all resources...... I A.2 Air quality sensor resource properties...... I A.3 Alarm resource properties ...... II A.4 Door resource properties ...... II A.5 Door lock resource properties ...... II A.6 Elevator control resource properties ...... II A.7 Light source resource properties ...... III A.8 Location resource properties ...... III A.9 Mode resource properties ...... III A.10 Smoke detector resource properties ...... III A.11 Operational state resource properties ...... IV A.12 Motion detector resource properties ...... IV A.13 Surveillance camera resource properties...... IV A.14 Temperature resource properties...... IV A.15 Thermostat resource properties ...... V A.16 Time interval resource properties ...... V A.17 Ventilation resource properties ...... V A.18 Collection resource type definitions...... VI A.19 Resource Type and Interface Definitions...... VII

vi Acronyms

6LoWPAN IPv6 over Low power Wireless Personal Area Networks

ALG Gateway

API Application Programming Interface

BMS building management system

CoAP Constrained Application Protocol

CRUDN Create, Retrieve, Update, Delete, and Notify

HATEOAS Hypermedia as the Engine of Application State

HTTP Hypertext Transfer Protocol

IEEE Institute of Electrical and Electronics Engineers

IETF Internet Engineering Task Force

IoT Internet of Things

IP Internet Protocol

ITU International Telecommunication Union

JSON JavaScript Object Notation

LLOC logical lines of code

M2M Machine-to-Machine

MEMS Method for Evaluating Middleware Architectures

vii Acronyms

MQTT Message Queuing Telemetry Transport

MQTT-SN MQTT for Sensor Networks

OASIS Advancing Open Standards for the Information Society

OCF Open Connectivity Foundation

OIC Open Interconnect Consortium

OS operating system

OWD one-way delay time

QoS quality of service

RAML RESTful API Modelling Language

REST Representational State Transfer

ROA Resource-Oriented Architecture

RTD round-trip delay time

UDP User Datagram Protocol

URI Uniform Resource Identifier

URL Uniform Resource Locator

XML Extensible Markup Language

YAML YAML Ain’t Markup Language

viii Introduction

This chapter presents the background and context of the problem area addressed in the thesis. The specific problem, the problem solving approach and delimitations are described, along with the purpose and goals of the project and the written thesis. A brief discussion of benefits, ethics, and sustainability is given. The chapter ends with an outline of the structure and content of the thesis.

1.1 Background

The Internet of Things (IoT) is expected to deliver a whole new range of services to all parts of our society, and improve the way we work and live. Among the application scenarios for Internet of Things (IoT), we find smart cities, smart cars, home and building automation, smart health care, environmental monitoring, and smart farming. The challenges within IoT are often related to interoperability, device resource constraints, and security. The highly distributed, ubiquitous and heterogeneous environment of IoT requires a complex and scalable software architecture. Many devices have limited energy, memory, and processing capacities, and commonly face requirements of simplicity and low development and manufacturing costs. Security and privacy are essential for the IoT since a vulnerable network potentially enables unauthorized access to monitoring and control of all sorts of devices in cars, medical equipment, and locking systems. The interoperability issues come with heteroge- neous devices and networks, and the diversity of application domains encompassed by IoT. According to [3], the best approach to face the above challenges is to use a software platform defined as middleware. Middleware for IoT is an active research area, many have been designed and implemented, and there are various industrial groups suggesting standard specifications for this type of IoT software platform. However, as noted by [4, 5], there is no middleware available today that can support all the services generally requested in IoT applications.

1 Chapter 1. Introduction

1.1.1 Middleware for the Internet of Things Every IoT system has an underlying software architecture consisting of a set of integrated elements, delivering the functionality and quality the system requires. Middleware refers to a category of software infrastructure technologies that simplify the construction of distributed software architectures. As defined by [6], middleware is an abstraction layer, hiding the details of the underlying software and hardware. It connects the application layer with underlying layers such as operating system (OS) and device drivers. The desirable requirements of a middleware architecture, listed by [6], help to explain its purpose. The middleware should preferably

• be adaptable, flexible and scalable to support variations in application-level requirements and variations in resource availability of devices

• provide applications with secure access to resources on remote devices

• be portable to different hardware and software platforms

• support various application programming languages

• provide standardized and easy-to-use communication interfaces abstracted to such a level that applications can seamlessly communicate with remote devices

There can be various levels of middleware in a software architecture. However, as clarified by [6], middleware resides in the layer which is not an OS or device drivers, nor an application. Within the context of IoT, the first essential role of middleware is to provide abstraction from the physical things, that is, objects of the physical world, to the applications. The second is to provide interoperability across heterogeneous devices and diverse application domains. Other main features proposed in [3] are context awareness, handling of large data volumes, privacy and security, and device discovery and management. Several systematic reviews of existing middleware approaches for the IoT have been undertaken, such as [3], [4], and [5, Chapter 4]. An overview of commercial IoT frameworks is presented by [7].

1.1.2 Design Patterns for the Internet of Things The IoT concept presents a wide range of design problems at many levels of the system architecture. The application domains, use cases and resource constraints are many and varied. In order to avoid reinventing the wheel, and in order to deliver a high-quality architecture, software developers use design patterns. Within software engineering, a design pattern is a reusable solution to a reoc- curring design problem within a particular context. It describes a best-practice, or a known and proven approach, to solve a common problem when designing soft- ware. Each pattern applicable to a given problem has advantages and disadvantages depending on contextual factors.

2 Chapter 1. Introduction

Design patterns can be seen as building blocks of a software architecture. A set of coherent design patterns can form a reference architecture from which a system’s behavior can be modeled and understood. There are various design patterns relevant for IoT middleware such as informa- tion models, interaction models, and infrastructure models. Using a middleware, providing an abstract representation of physical things and enabling applications to interact with them, is a sort of high-level design pattern in itself. Information models can describe how to structure data, for instance in an XML document, or define models for resource access control. Design patterns for interac- tion can describe how different system components communicate with each other. An example is the publish-subscribe communication pattern, and the use of a mes- sage broker to connect the publishers and subscribers. Design patterns that can use well known standards and practices for communi- cation are advantageous since they promote interoperability.

1.2 Problem

Today the IoT lacks universal standards for communication and interaction between devices. This has resulted in a wide collection of diverse software architectures for IoT applications on the market, where smart devices from different manufacturers are often unable to interact with each other. The difficulty of interaction is increased by device heterogeneity in terms of hardware platform and underlying software, communication protocol and technology, and data models. The resource constraints imposed upon devices in many IoT application scenarios require resource efficient solutions, limiting the choice of standards and protocols to use. Various standards organizations try to overcome these problems and promote technological advance by suggesting common standards for IoT software architec- tures. One of the organizations contributing in the IoT standardization effort is the Open Connectivity Foundation (OCF), an industry group delivering an IoT software framework specification and a product certification program. The organization is including in its membership well-known companies such as , Cisco, General Electric, Samsung, Microsoft, Qualcomm, and IBM. Open Connectivity Foundation (OCF) further sponsors an open source reference implementation of the architecture specification called IoTivity, which runs as middleware intended to be portable to all operating systems and connectivity platforms. Initially OCF has focused on smart homes and offices, but targets various application domains in the future. The goal of the OCF is to enable devices to communicate regardless of manufacturer, operating system, chipset or physical transport [8].

In relation to the above problem area, the research question was:

• In a building management system context, how well does IoTivity meet the key functional and quality requirements identified for IoT middleware?

3 Chapter 1. Introduction

1.3 Purpose

The purpose of this project was to evaluate IoTivity, an open-source reference im- plementation of the IoT architecture specification from OCF. The evaluation was performed with regard to the quality and functionality generally required from IoT middleware and applications. The purpose of this thesis was to describe the gen- eral requirements of IoT middleware, discuss the selection of design patterns for the middleware architecture presented in the OCF framework, and present a case study of using the IoTivity middleware in a building management application scenario.

1.4 Goals

This thesis project had the following goals:

• Identify and describe the key functional and quality requirements of IoT mid- dleware through a literature study

• Identify and describe the key design patterns forming the IoTivity middleware architecture described in the OCF framework specification

• Prototype a building management system (BMS) using IoTivity, and evaluate the functionality with regard to the identified quality attributes by performing experiments on the system prototype

• Analyze how the key design patterns of IoTivity affected the behaviour of the system in the experiments

1.5 Benefits, Ethics and Sustainability

This project could contribute in the effort to find common communication and interoperability solutions for the IoT. With common standards the infrastructure technology for the IoT can mature and become more reliable. Interoperability and possibility to integrate smart devices from different manufacturers will protect users from being dependent upon a single vendor. The reference implementation of the OCF framework is open source, meaning the source code is made available to anyone wishing to study it, change it and distribute it. It is developed in a collaborative manner, bringing in ideas and per- spectives from developers from various companies, industry sectors, and interest groups. Sharing knowledge and solutions as in the open-source development model can advance technology and provide innovation opportunities. There are various ethical issues arising with the IoT, especially regarding privacy and integrity. The IoT applications collect and make use of large amounts of data about the surrounding world, including people. The predicted social benefits of IoT applications such as smart cities, offices and health care include improved efficiency, health, and safety. At the same time, the extensive data collection implies a risk of potential breaches of privacy.

4 Chapter 1. Introduction

1.6 Method

General software architecture evaluation methods commonly focus on understanding the connection between the architecture design and the selected quality attributes. The evaluator wants to ensure that the architecture meets the key quality goals while supporting the key functional requirements. As described by [9], there are particular concerns that come into the picture when evaluating middleware architecture. Middleware is usually designed to support a wide range of applications, as in the case with IoTivity. Since it is meant to be reusable over several vertical domains, it is said to be horizontal in nature. The key quality attributes, however, can have different scope and importance when related to a particular vertical domain or application context. In this project, the scenario-based Method for Evaluating Middleware Architec- tures (MEMS) [9, 10] was applied in order to evaluate IoTivity. As a part of this method, a case study of implementing a building management system (BMS) pro- totype was conducted. The idea of MEMS is to express the quality attributes in the form of scenarios, since the attributes themselves are too vague to analyze. A scenario describes an action or a chain of actions happening in a system when a cer- tain architecture is used. The scenario should be quality-sensitive since it is meant to show how the architecture responds with respect to the given quality attributes in a particular context.

The steps of MEMS include

• determining key quality attributes • identifying key architectural design patterns • generating key scenarios • defining quality metrics and scales • prototyping • designing and running experiments measuring the quality of the architecture

The project used an inductive research approach, and the middleware was eval- uated exclusively with quantitative metrics. Today there is no broad consensus on what design patterns to use for IoT middleware targeting various vertical domains. Evaluating one middleware architecture in one vertical domain, in this case BMSs, was a step to find the most suitable design patterns for this type of middleware.

1.7 Delimitations

The complexity of the IoTivity middleware made it impracticable to evaluate the quality of the complete architecture, considering the time limitation of this project. Therefore, this project evaluated a few of the components considered important for IoT middleware. One important component of the architecture not investigated in this project is security. Provision of secure communication and authorized remote

5 Chapter 1. Introduction access of resources is of key importance when evaluating the utility of a middleware solution. In the quality evaluation of the IoTivity middleware only quantitative metrics were applied, since qualitative metrics would have required developers or other stake- holders to subjectively assess the quality, which was outside the scope of this explo- ration. Using both quantitative and qualitative metrics could have provided a more complete picture.

1.8 Outline

The overall structure of the study takes the form of seven chapters. Chapter Two begins by laying out the theoretical framework of the research, and looks at com- mon concepts of IoT, the requirements of IoT middleware, the core architecture and identified design patterns in the OCF framework specification. The third chapter is concerned with the methodology used for this study. MEMS and the case study are motivated, and the steps of MEMS are explained. The thesis goes on describing the case study in depth in chapter four, and the plan for the evaluation in chapter five, including a description of the test environment and the experiment procedures. Chapter six presents the experiment results with text, tables, and graphs, without any interpretation. The seventh and last chapter presents the findings and con- clusions of the research, discusses the results analysis, and provide suggestions for future work.

6 Theoretical Background

This chapter presents the theoretical background of this thesis project. The initial section describes the common concepts of and models for the Internet of Things (IoT), generating the functional requirements and quality considerations for an IoT software architecture. Then follows a section motivating a middleware solution, and describing the identified key requirements of such an approach. The third section describes the OCF framework, their reference implementation IoTivity, its core functional blocks, and key design patterns. The chapter concludes with a summary of previous work and how it relates to this project.

2.1 Common Concepts of the Internet of Things

Although the term Internet of Things (IoT) is widely used, and various definitions of the term have been proposed, there is still no common agreement of what the term actually encompasses. One of the more comprehensive and general definitions of Internet of Things (IoT), as well as other terms commonly used within IoT, are suggested by the International Telecommunication Union (ITU) [11].

Internet of Things: A global infrastructure for the information society, enabling advanced services by interconnecting (physical and virtual) things based on existing and evolving interoperable information and communication technologies.

Thing: With regard to the Internet of things, this is an object of the physical world (physical things) or the information world (virtual things), which is capable of being identified and integrated into communication networks.

Device: With regard to the Internet of things, this is a piece of equipment with the mandatory capabilities of communication and the optional capabilities of sensing, actuation, data capture, data storage and data processing.

The following subsections describe some of the common concepts and views of IoT, such as communication models, protocols and networking technologies commonly used.

7 Chapter 2. Theoretical Background

2.1.1 Communication Models In an overview of IoT presented by [1], four different device communication models are described. These are the device-to-device, device-to-cloud, device-to-gateway, and back-end data-sharing models, shown in Figure 2.1. The communication and networking protocols in the figure are only examples of what can be used. The device-to-device model includes two or more devices exchanging messages directly, which is a common communication model in home automation applications. This requires the devices to have the same communication protocol and data model. In the device-to-cloud model, the devices connect directly to an Internet cloud service. The cloud connection enables a user to access the device remotely via a Web interface or smartphone. The devices usually exploit traditional communication mechanisms such as Ethernet or WiFi to establish the connection to the IP network. Many vendors use proprietary data protocols for communication device-to-device and device-to-cloud, which forces users to buy devices exclusively from the same product family, commonly referred to as vendor lock-in.

Figure 2.1: An overview of communication models for the Internet of Things (adapted from figures of [1]).

The device-to-gateway model displays how an IoT device connects to a cloud service via an Application Layer Gateway (ALG). The ALG, acting as an interme- diary, can provide services like security and data protocol translation, and is often used to address interoperability issues between devices with otherwise incompatible communication technologies. In a smart home scenario, the gateway is commonly a smartphone or a smart hub. The back-end data-sharing model is an extension of the device-to-cloud model, with the aim to avoid data silos when IoT devices upload data only to a single server.

8 Chapter 2. Theoretical Background

The idea is to enable the server to share the data with other back-end systems, so that data streams from several IoT devices can be aggregated and analyzed. This model targets interoperability between back-end systems, but is difficult to realize without common standard communication and data protocols between the vendors. In summary, these models are strongly influenced by the vendors’ choice of using open standard or proprietary protocols. The device-to-gateway model’s primary use is to enable interoperability, while the back-end data-sharing model requires it [1].

2.1.2 Internet of Things Stack There are many standards and protocols that are relevant for and typically used within IoT. Figure 2.2 shows some of the protocols commonly used to enable con- nectivity and communication between IoT devices. There is no common standard IoT stack model, so the stack layer names on the left side in Figure 2.2 are only there for guidance. Starting from below in Figure 2.2, IEEE 802.15.4 [12] is a standard for low-rate wireless networks, from the Institute of Electrical and Electronics Engineers (IEEE). It defines physical layer and media access control sublayer specifications and aims to provide low power, low cost, low complexity, and low data rate connectivity for non-expensive devices. The standard has multiple physical layer specifications in order for support of various frequency bands. Several protocol specifications like 6LoWPAN, Zigbee [13], Z-Wave [14], and Thread [15] are based on IEEE standard 802.15.4. 6LoWPAN is the name of an Internet Engineering Task Force (IETF) working group and the acronym stands for IPv6 over Low power Wireless Personal Area Networks. This working group is defining an adaption layer and specifications for transmitting IPv6 over IEEE 802.15.4 networks [16]. IPv6 is version six of the Internet Protocol (IP), meant to be the successor of IPv4 [17]. The main difference is the expanded addressing capability, increasing the IP address from 32 bits to 128 bits, which is necessary since the Internet is running out of unique IPv4 addresses [1]. Other improvements are header simplification, support for extensions and options, and traffic flow labeling capacity [17]. A challenge is that IPv6 is not compatible with IPv4, and much of the available software for IoT devices today only supports IPv4 [1]. Message Queuing Telemetry Transport (MQTT) is a light-weight publish-subscribe messaging protocol, suitable for IoT connectivity due to its design principles of min- imizing network bandwidth and device resource requirements. Since 2014, MQTT is an Advancing Open Standards for the Information Society (OASIS) standard [18]. There is also an extension, called MQTT for Sensor Networks (MQTT-SN). It is very close to MQTT, but is further optimized for a wireless communication environment with high link failure rate and low bandwidth, and for low-cost, battery-operated devices with restricted storage and processing capabilities [19]. Constrained Application Protocol (CoAP) is another protocol designed for con- strained networks and devices, and suitable for IoT communication. It provides a request-response model based on Representational State Transfer (REST), similar to and easily interfaced with the well-known Hypertext Transfer Protocol (HTTP),

9 Chapter 2. Theoretical Background and is thereby easily integrated with the web [20]. MQTT runs over TCP, MQTT-SN runs over UDP, and CoAP runs over both TCP and UDP. All three of them are promising protocols to use with IoT. In the application layer in Figure 2.2, binary, JSON, and CBOR are listed. These are examples of data formats from the IPSO Smart Objects design pattern. This pattern provides a consistent data model in order to achieve interoperability between smart devices. Only the protocols from Figure 2.2 with the most significance for IoT have been explained in this text.

Figure 2.2: An example of an Internet of Things stack.

2.2 Middleware for the Internet of Things

This section summarizes and describes the requirements for IoT middleware found in previous research. It does not distinguish requirements specific for building manage- ment applications, but instead describes general requirements for IoT middleware solutions targeting various vertical domains and application scenarios, since that is the overall concern of this thesis project.

2.2.1 Motivation of a Middleware Solution A middleware solution can ease the application development process by providing an abstraction and adaption layer, hiding the details of diversity of the underlying hardware and software platforms. The middleware can provide Application Pro- gramming Interfaces (APIs) for physical layer communication, offer common ser-

10 Chapter 2. Theoretical Background vices to applications, and integrate heterogeneous computing and communication devices [3]. In the light of the characteristics of IoT infrastructures and applications pre- sented in Section 2.1, a middleware platform is a useful approach to cope with the complexity, heterogeneity, connectivity, and scalability challenges encountered in IoT [3, 4].

2.2.2 Functional Requirements The functional requirements are those describing what the middleware should do and what features it should provide. Bandyopadhyay et al. [3] have identified six functional blocks required in IoT middleware, being data management, context awareness, resource discovery, re- source management, security and privacy, and interoperation. In this thesis, security and interoperability are considered as non-functional requirements and are described in Section 2.2.3. The functional blocks are described in the following subsections.

Data Management Data management services usually required by applications are data acquisition, processing, storage and transfer. The processing can include data filtering, com- pression, and aggregation [4]. The data occurring in IoT networks can be sensed data or any information rel- evant for applications such as positional, environmental, identification, or history data. It can also be metadata describing the device context or the network infras- tructure [3]. According to [5], all network devices, be it processing, sensor or actuator nodes, should operate and be configured in the same way. Using the same data management middleware component in all nodes, enabling each node to collect, store, process and send data, will promote interoperability between heterogeneous platforms and provide a homogeneous operation layer for data management. Regarding constrained devices, there are strategies for easing the burden of data management. If the node has limited storage and processing capabilities, the node can send its data to an assisting node, responsible for processing data and answering queries. If the node has limited power supply, it is often better to perform data processing and aggregation before transfer, since sending large amounts of raw data over a wireless medium, possibly to many receivers, requires more energy than the processing.

Resource Discovery Resource discovery is about enabling applications to discover what resources or services are available for use in the network. IoT resources include the resources found in devices, such as their power and memory, their connected sensors and actuators, available communication modules, and services they provide [4].

11 Chapter 2. Theoretical Background

According to [4], important requirements for the resource discovery mechanism are to be automated and scalable. The article states that, due to the dynamic character of the IoT infrastructure, one must assume that the availability of resources in the network is continuously changing. In a centralized system, a dedicated server could be responsible for finding devices present in a network, retrieve their metadata and notify applications about available resources or services. In a decentralized approach, each new device should be able to connect to the network, make its presence known and announce the resources or services it offers [4]. The device metadata can include device name, vendor or manufacturer details, and description of underlying software and hardware platform. Then there is the semantic device description, which can describe the available resources or services, device capabilities, security properties or device malfunction. For other devices to understand what to do with this information, the semantic device description must comply with a common semantic model, which should be optimized for resource consumption [3].

Resource Management A middleware should deliver services for resource consumption and configuration. Resource management is about managing resource information and providing proper resource access interfaces. Resources should be described, accessed, and configured in a homogeneous manner, even if the devices are heterogeneous [5]. This requires a semantic device description, which abstracts from the specific hardware and software platform of a device, and instead presents its type, properties and features. A device ontology of some sort is commonly used for this purpose [3]. Resource configuration capabilities can include powering up or down a device, managing subscriptions for publish-subscribe messaging, starting or stopping peri- odic activities, managing alarms and events, setting actuation values, monitoring parameters, or any other application-specific setting [5]. Resource management can also be about monitoring resource usage, fair resource allocation and provisioning, and resolving resource conflicts. This is especially im- portant when resources are constrained and impact the quality of service (QoS) of a system [4]. Moreover, resource management can include device status inquiry and device malfunction discovery.

Context Awareness Xin Li et al. [21] explain the concepts and key features of context awareness, and present a survey of existing context aware middleware technologies. The article claims that if a device is to be smart, it has to be aware. The idea of context awareness is that devices autonomously should be able to adapt their behaviour to the changing environment, and thereby reduce the need of human intervention. According to [4], context awareness plays an essential role in achieving the vision of IoT, since Machine-to-Machine (M2M) or device-to-device communication is one of the pillars of IoT.

12 Chapter 2. Theoretical Background

There are ongoing discussions on what context actually means, and several def- initions have been reviewed by [21]. The general definition finally selected by [21] was "...context is any piece of information that can represent the changes of the circumstance (either static or dynamic)". Examples of context parameters are loca- tion, identity, and state of things or people. It can be the time of the day, season, temperature, or any information used to characterize the situation of things or de- vices. Furthermore, the most general and accurate definition of the term context aware- ness designated by [21], is "a system is context-aware if it uses context to provide relevant information and/or services to the user, where relevancy depends on the user’s task", which was originally presented by [22]. As described by [21], the IoT has brought about many devices able to collect context information by means of sensors. The challenge now is to find efficient solutions to increase the usability of the context data. Adding context awareness ability to the middleware architecture, enabling context detection and management, decreases the complexity of context aware application development. Context acquisition, modeling, reasoning, distribution, and visualization are the events of a context lifecycle, according to [21]. Thus, these are the required compo- nents of a context-aware middleware, in one form or another.

2.2.3 Non-Functional Requirements The non-functional requirements are those describing how the middleware should perform a certain function and what quality attributes it has. Interoperability, security and privacy, scalability and adaptability are listed as key requirements of IoT middleware in [3, 4, 5]. The importance of timeliness and bounded response times in applications with real-time requirements is noticed by [4, 5]. Additional requirements mentioned in [4] are reliability, ease-of-deployment and popularity. These requirements are described in the following subsections.

Interoperability Interoperability is about allowing devices to share information despite heterogeneity. To achieve this, heterogeneous device components must be abstracted and managed in the same way. The middleware should provide all devices with common models for configuration and data processing, as well as standard interfaces for data and resource access [5]. The middleware should run over heterogeneous devices without requiring any additional effort or custom programming from the application devel- oper [4]. Devices should also be able to interact across heterogeneous networks, potentially using different communication technologies or protocols. Interoperability can be further divided into network, syntax, and semantics [3]. Network interoperability defines the protocols used for exchanging information across the network and covers the basic connectivity issues, though does not consider the content of the information. The syntactic interoperability considers the encoding format and structure of the data shared between devices. Examples of open standard data interchange formats are JavaScript Object Notation (JSON), Extensible Markup Language (XML), and

13 Chapter 2. Theoretical Background

YAML Ain’t Markup Language (YAML). Appropriate syntax and data representa- tion are prerequisites to semantic interoperability. Semantic interoperability requires a semantic model describing how to interpret the information shared between devices, or in other words, how to understand the meaning of the content. The semantic information model is often domain-specific.

Security and Privacy Security and privacy are critical aspects of IoT, and have to be considered at all system levels and in all middleware components. The key elements to consider are confidentiality, authenticity, and non-repudiation [3]. According to [3], security can be dealt with in two ways. One way is to implement high-level peer-to-peer communication, where peers communicate in a secure and abstract way at higher layers. The other approach is to implement secure topology management, handling authentication of new peers, network access permissions, and protection of routing information exchanged in the network. Context-aware middleware and applications, introduced in Section 2.2.2, might deal with personal information, such as the health status of a person or location of an object, information which must not be disposed to unauthorized persons or devices. Therefore every component of the middleware using personal information must consider privacy [4].

Real-Time or Timeliness The real-time or timeliness requirement concerns the ability of the middleware to support applications with real-time constraints. IoT involves many real-time appli- cations within domains such as health care, transportation, and factories [4]. Middleware should provide real-time services to overlying applications, ensuring bounded response times when necessary. In real-time applications, a late delivery of information might make an operation useless or even endanger the system or its users [4]. A real-time operation is correct only if it is performed logically correct and finished within a certain time frame. Timeliness is generally important since much of the information exchanged in a network is only valid and useful for a limited amount of time.

Scalability The scalability requirement of IoT middleware has two key aspects. The first is the question of resource constrained devices which lack the capability to host a complex middleware architecture supporting every potentially relevant feature for an IoT application. Consequently, the middleware must be modular, so that constrained devices can implement only the most basic functionality required to fulfill its pur- pose. Some devices with very limited resources might even need assistant devices doing the heavy lifting of data storage, processing, aggregation and transfer. The second is the aspect of extremely large networks of devices, and extremely large volumes of data collected and exchanged by these devices. The middleware

14 Chapter 2. Theoretical Background needs a scalable design in order to accommodate the growth of networks and ap- plications [4]. According to [3], managing these voluminous data requires improved methods for finding, fetching, and transferring data, adding new challenges of data querying, indexing, and modeling IPv6, explained in Section 2.1.2, is part of the answer for a scalable IoT infras- tructure, providing a scalable solution for addressability of devices.

Adaptability Since the middleware is intended to be reusable for a wide range of application and use scenarios, it must be adaptable to the numerous changes of environment, cir- cumstances and application-level demands occurring within IoT. As noted by [3], the objective of all middleware is to offer an adaption layer in a plug and play mode. Applications might have diverse demands of what set of operations should be avail- able, what things and concepts should be possible to virtualize, minimum lifetimes, or maximum response times. In order to enable adaption of the middleware even after deployment, it should provide system and resource configuration interfaces, to eliminate the need to reprogram the device [5]. For context-aware applications, the middleware should enable dynamic adaption to changing contexts [4].

More Non-Functional Requirements Other significant non-functional requirements, although only mentioned by [4] and therefore not considered among the most important in this thesis, are reliability, ease-of-deployment, and popularity [4]. Reliability concerns the middleware’s fault-tolerance, which is the ability of the middleware system to remain operational during the time period of a mission, even if faults occur in one or several components. The system-level reliability applies to all middleware components, since no chain is stronger than its weakest link. Ease-of-deployment, meaning easy installation and setup of a device, is desirable since the person deploying it should not be required to have expert knowledge. Popularity refers to the likelihood of continued support, maintenance, and ex- tension of a particular middleware technology, which increases with the number of users, developers, and researchers that adopt it. This is a main concern for embed- ded hardware in general. Often manufactures promise a certain product lifetime with support, hardware availability, and tool chains.

2.3 Open Connectivity Foundation and IoTivity

This section presents the Open Connectivity Foundation (OCF) framework with an overview of the architecture, descriptions of the core functional blocks, and de- scriptions of the identified key architectural design patterns. All information and examples about the OCF framework in this section are extracted from the Open In- terconnect Consortium (OIC) specification version 1.1 [2]. OCF mentions on their web site that this document is still a draft specification and not the final, adopted version.

15 Chapter 2. Theoretical Background

2.3.1 The Open Connectivity Foundation Framework Open Connectivity Foundation (OCF) is an industry group and standards organi- zation with the objective of developing standards and certification for IoT devices. It is one of many competing standards organizations within the IoT domain. The vision of OCF is that the billions of devices predicted to be connected to the IoT within the next few years should be able to communicate with one another regardless of their manufacturer, vertical market sector, operating system or physical transport technology [8]. The standard specification presented by the OCF is called the OIC specifica- tion, and covers the core architecture, security, resource type models, and so far one vertical market profile which is smart home. The OIC specification has adopted a Resource-Oriented Architecture (ROA), implying that things, information, and concepts are represented as resources. The resource model is meant to be domain- agnostic, and then vertical profiles are provided on top of the core framework, spec- ifying domain-specific semantics. The vertical market profile contains a resource specification, which is a list of reusable resources in, for instance, smart home de- vices. A future goal of OCF is to specify profiles for multiple vertical markets within IoT. Resources are specified in RESTful API Modelling Language (RAML) and each resource definition contains a unique identifier, an indication whether the resource is an actuator or a sensor or another type, a list of supported methods and a JSON schema for input and output for each method [23].

2.3.2 IoTivity IoTivity is an open source reference implementation of the OCF standard specifica- tion, although it is not strictly limited to those requirements. It runs as a middleware and aims to provide seamless connectivity device to cloud and device to device. The software framework is licensed under the Apache license version 2.0. As of January 2017, IoTivity is compliant with the OIC specification version 1.1 [24].

2.3.3 Architecture Overview The OIC architecture is based on the principles of Resource-Oriented Architecture (ROA), and the operations on physical entities should be RESTful, meaning they should comply with the Representational State Transfer (REST) architecture style. OCF aims to provide a framework for communication and interoperability, adapt- able to various IoT market segments such as consumer, industry, automotive, and health. Further it should be portable to various hardware platforms, operating systems (OSs), and communication and transport layer technologies. The architecture is intended to be suitable for constrained as well as resource- rich smart devices. Therefore, OCF has aimed to make it scalable and adaptable to varying device capabilities. The architecture’s functional blocks required for operation are L2 connectivity, networking, transport, the OIC framework and the application profiles, as shown in Figure 2.3. L2 connectivity refers to functionality required to set up the network

16 Chapter 2. Theoretical Background connection on the physical and data link layers. Application profiles contains the data models and functionality required in a specific market segment, such as smart home or smart health. The specification defines the roles of a server and a client, and interactions be- tween these roles. A server is a device hosting resources, providing resource state information and facilitating remote interaction with these resources. A client is a device accessing a resource on a server. The OIC framework components are described in the subsequent sections.

Figure 2.3: The functional blocks of the OCF framework architecture (adapted from Figure 2 of [2]).

2.3.4 Core Framework The core framework consists of Identification and addressing, the Create, Retrieve, Update, Delete, and Notify (CRUDN) operation definitions, Resource model, Mes- saging, Discovery, Device management, and Security components, described below. This information was found in the OIC specification version 1.1 [2].

Identification and addressing Identification and addressing defines how to uniquely identify, name and address elements in the network. The identifier must be unique within a context or domain, or guaranteed to be unique across all contexts and domains. Within the private domain, such as a smart home where devices communicate via a gateway, an IP- address could be an identifier. Resources can be identified with a Uniform Resource Identifier (URI), and if the URI is a Uniform Resource Locator (URL), it can also be used for addressing. If a URI is not applicable, the resource may have a property whose value is the resource identifier.

Messaging Operations CRUDN are the set of operations defined for data and resource management. These operations are performed by clients on resources made available by a server. With

17 Chapter 2. Theoretical Background the Create command, a client can request a creation of a new resource instance on a server. The Retrieve command is used for querying the current representation state of a resource. When a client wants to do a partial or complete update of a resource representation, it can use the Update command. The Delete command requests removal of a resource instance. Lastly, the Notify command is used to subscribe to asynchronous notifications whenever a resource state changes. A middleware messaging component maps the CRUDN operations to a specific communication protocol. In version 1.1. of the OIC specification, it is specified how to map the CRUDN operations to the Get, Post, Put, Delete methods in CoAP.

Resource Model The resource model presented in the OCF framework provides concepts and mecha- nisms for semantic interoperability. The model is intended to capture the semantics of artifacts, devices, resources and their contexts. Sharing a semantic model is a prerequisite for two devices to interact in a meaningful way. The OCF intends to make their resource model mappable to various transport protocols, so that de- vices can interact independent of physical transport, with help from a translating intermediary. The main concepts of the resource model are entity, resource, URI, resource type, property, representation, interface, collection and link. The mechanisms applicable on these concepts are the CRUDN operations. The concepts and mechanisms are meant to be combined in various ways to achieve the rich semantic modeling required in the diverse range of use cases within IoT. An entity describes something that needs to be visible, accessible, and manip- ulable in the network. The entity is abstracted, or encapsulated, by a resource. Each resource has a unique address, a URI, and properties describing aspects and capabilities of the resource. This is illustrated in Figure 2.4.

Figure 2.4: The concepts of entity, resource, URI, property, and representation in the OCF resource model.

A resource is derived from a resource type, which is the class or category of a resource, such as sensor, switch, or battery. The resource type is described in the property list of the resource, together with the device type describing the device the resource is hosted on. A snapshot of the properties of a resource is called a representation of a re- source, also illustrated in Figure 2.4. A representation captures the state of a re- source, meaning the current values of the properties, at a particular point in time.

18 Chapter 2. Theoretical Background

Representations are used for interactions with the resource, in accordance with the principles of REST. When retrieving or updating the state of a resource, represen- tations of the resource state are exchanged, in a request-response communication pattern. If a resource has one or several links, it is called a collection. A collection is a basic building block in the OCF framework used to model and map structures and relationships among resources occurring in different application contexts. It can be used to create groups or hierarchies of resources, such as tree, mesh, or fan-out structures. The link describes the relationship between resources which is unidirectional. The parameters defining a link include target URI, context URI, relationship between target and context URIs such as "contains" or "activates", and metadata elements. An example of a collection could be the group of resources hosted on a device, as shown in Figure 2.5. The intention of the collection concept is to provide a means to refer to a set of linked resources with a single handle.

Figure 2.5: An example illustrating the concepts of collection and link in the OCF resource model.

Table 2.1 shows an example of property definitions for a resource abstracting a dimmable light bulb. Properties describe aspects and capabilities of a resource, as well as metadata related to the resource. The property is represented with a key-value pair, expressed as < P ropertyName >=< P ropertyV alue >. The OCF framework specifies resource type, resource interface, name, and resource ID as common properties, applicable for all resources. The interface property declares the interfaces supported by the Resource. An interface provides a view of a resource, and defines the allowed requests and response interactions on that view. The OCF framework have defined standard interfaces, some of which are shown in Table 2.2. OCF has further defined core resources enabling functional interactions. Among these, the default, platform, and device resources must be supported by all devices.

19 Chapter 2. Theoretical Background

Table 2.1: An example of properties of a light resource represented with the OCF resource model (adapted from Table 30 in [2]).

Property Property Value Value Access Unit Mandatory Description title name type rule mode Name n string R,W no Human-friendly name On/Off control On-Off of boolean R,W yes 0=Off 1=On Resource which can take a range Dimmer dm integer 0-100 R,W yes of values. Min: 0 Max: 100

Table 2.2: A table presenting some of the standard resource interfaces defined in the OCF framework (adapted from Table 8 in [2]).

Applicable Interface Description Methods The baseline interface defines a view into all Retrieve properties of a resource including the meta baseline Update properties. This interface is used to operate on the full representation of a resource. The read-write interface exposes only those Retrieve properties that may be both “read” and read-write Update “written” and provides methods to read and write the properties of a resource. Create The actuator interface is used to read or actuator Retrieve write the properties of an actuator resource. Update The batch interface is used to interact with a collection of resources at the same time. Retrieve This removes the need for the client batch Update to first discover the resources it is manipulating – the server forwards the requests and aggregates the responses.

Discovery Discovery is a function component enabling both endpoint discovery and resource based discovery. The OIC specification defines several mechanisms for device dis- covery, and there is a default discovery mechanism that should be supported by all devices. This default mechanism requires that all devices update their local core resource hosting the discoverable resources every time a new resource is instantiated on the device. Then, any device wishing to discover resources on one or more other remote devices, makes a unicast or multicast retrieve request. The remote devices receiving the request responds with their list of resources. The requester might then ask for further information about the available resource, now that it knows it exists.

20 Chapter 2. Theoretical Background

Device Management In version 1.1 of the OIC specification, only basic device management functions are defined. These are diagnostics and maintenance features, intended to be used by administrators to resolve problems occurring in the device when it is deployed and in operation. The diagnostics and maintenance features are exposed through an optional core resource type named maintenance, which up to now only contains the two properties factory reset and reboot. The factory reset should perform a rollback to the default state of the device by restarting it and resetting all device configurations. The reboot should perform a restart of the device but keep most of the configurations intact. Manufacturers and developers can specify their own device management re- sources and properties to use for maintenance and diagnostics, in addition to the maintenance core resource.

Security The aim of the OIC security specification is to protect all OIC resources, by providing a set of security mechanisms ensuring that a server enables access its hosted resources in a secure manner. Some robustness aspects of the security are dependent of the hardware platform hosting the OIC device. The specification describes a security theory of operation in three steps. Step one is that the OIC client establishes a network connection to the OIC server. Both the server and client are OIC devices with a unique DeviceID used in the security policy. Step two is to establish an end-to-end communication channel, which should protect the exchange of messages and resources. Step three is that the server’s secure resource manager decides if the client has permission to access the requested resource. The security specification further defines security mechanisms for access control, secure on-boarding of devices, secure bootstrap process, security provisioning, and secure device discovery.

2.3.5 Architectural Design Patterns On a high level, the OCF architecture implements a set of metadesign patterns. First of all, it is a middleware solution, acting as an abstraction layer, and virtu- alizing the things connected to the network. Having consistent abstractions gives the ability to connect various sensors, actuators or other objects, to various appli- cation programs, since the applications all understand the same abstractions. All in all, the virtualization of things by means of a middleware opens up the door for many-to-many interactions between things and application programs. The abstractions are accomplished with a data model, which has to be rich and consistent in order to provide interoperability and adaptability. Only then can it enable multiple and diverse applications to operate in a consistent way with any given endpoint device.

21 Chapter 2. Theoretical Background

The most characteristic feature of the OCF architecture is that it is resource ori- ented and RESTful. This entails a number of design patterns affecting the behaviour of several of the most important functional blocks. OCF has further integrated a variant of the observer pattern, enabling clients to receive notifications about state changes of observed resources. Moreover, patterns for resource discovery are identi- fied in the specification. These patterns are described in the following subsections.

Representational State Transfer Architectural Style The REST architectural style defines a set of design principles to accomplish key fea- tures and functionality for a distributed hypermedia system, targeting high levels of interoperability, scalability, and generality. In order to retain the principles guiding REST, certain interaction constraints are applied on elements of the architecture. REST can be explained by looking at its design principles of architectural el- ements. The main design principles of REST are the client-server communication pattern, stateless interactions, cacheable responses, uniform interfaces, and layered system. The abstract architectural elements of REST are divided into data elements, connectors, and components [25].

Data elements The first and fundamental data element is the resource, which is the concept for information abstraction in REST. A resource is any information or object, virtual or physical, that can be named. Other data elements exist to describe the nature and state of a resource, as well as define the permitted interactions with a resource. URI is a data element used to identify the particular resource involved in an interaction between components. Next there is the representation, used to perform actions on a resource. The representation captures the current or intended state of a resource, and is transferred between components along with representation meta- data. There is also resource metadata, describing information about the resource not tied to any specific representation. The last data element is the control data, de- scribing the purpose of a message between components, such as the required action or the meaning of a response [25]. A request consists of control data, a resource identifier, and an optional repre- sentation. A response consists of control data, optional resource metadata, and an optional representation.

Connectors The connectors in REST provide generic interfaces for accessing and manipulating resources. The purpose of connectors is to simplify the communication with components by separating the concerns and hiding the details of the underlying implementation of resources and communication mechanisms. The primary connector types are the client and server. A client initiates com- munication by making a request, a server listens for connections and responds to requests. A component may include both client and server connectors managing its network communication. Other connectors are cache, resolver and tunnel. The cache can be placed in the client or server interface to save cacheable responses to be reused in later interactions.

22 Chapter 2. Theoretical Background

A resolver translates the resource identifiers into the network information needed to establish a connection between components. A tunnel carries communication across a connection boundary, such as a firewall or gateway [25].

Components The REST components, origin server, gateway, proxy, and user agent, are categorized according to their role in an application. The user agent can use a client connector to initiate a request, and should ultimately receive the response. The origin server uses a server connector to provide representations for its resources and to receive requests intending to modify its resources. The origin server hides the details of the particular implementation of a resource behind a generic interface. Gateway and proxy are intermediary components, acting as both client and server in order to forward requests and responses between other components, and providing services such as data translation and security protection. The difference between a proxy and a gateway is that the client can choose when to use a proxy [25].

Client-Server The first design principle of REST is the separation of concerns in the client-server communication model. This aims to simplify component imple- mentation, reduce complexity of connector semantics, and increase the scalability of server components [25].

Stateless interactions The second principle states that all interactions should be stateless. That is, each request should contain all the information necessary for a connector to understand and serve it, independent of any preceding requests. It further allows for components to act as either destinations or intermediaries, removes any need for connectors to retain application state between requests, and enables interactions to be processed in parallel [25].

Uniform interfaces The third principle is uniform interfaces, concerning the identification of resources, manipulation of resources through representations, self- descriptive messages, and Hypermedia as the Engine of Application State (HATEOAS). According to HATEOAS, the RESTful architecture should provide means to link resources to one another, provide unambiguous semantics for following and embed- ding these links in resource representations, and thereby make it possible to discover and connect to other resources through the links [25].

Layered system The fourth principle is that of a layered system, concerning the ability to insert intermediaries at various points in the communication, with- out having to change the interfaces between components. Intermediaries can assist in communication translation, or in large-scale, shared caching. The principle of intermediary processing builds upon the other principles of uniform interfaces and stateless interactions [25].

Cache The fifth and last principle states that each response should be explicitly marked as cacheable or non-cacheable. The ability to reuse a cached response,

23 Chapter 2. Theoretical Background although adding some latency to each individual request due to lookup overhead, can result in a considerable improvement in overall request latency even when only a small percentage of requests result in cache hits [25].

Mapping of REST to OCF Framework The OCF framework has largely adopted all design principles of REST. Some concepts in the OCF resource model are directly taken from the REST data elements such as resource, representation, and URI. The set of properties describing the parameters of a resource in the OCF framework can be mapped to the value set of a resource in REST. The collection and link concepts in the framework address the connectedness and HATEOAS principle of REST.

Observer Pattern The OCF framework has added Notify to the original Create, Retrieve, Update, and Delete (CRUD) operations. Notify is an operation used to request asynchronous notification of state changes. If the server providing access to the resource supports the Notify operation, the resource is said to be observable. The observe mechanism consists of five steps, shown in Figure 2.6.

Figure 2.6: The five steps of the observe mechanism in the OCF framework (adapted from Figure 32 of [2]).

In the first step, the client sends a retrieve request with an observe indication to the resource it wants updates from. The message should contain both the requested resource URI, and the client URI, so that the server knows to who it should send notifications. When the server receives the request, it has to validate that the client has right to perform the requested action. If successful, the server caches the information related to the observe request. Thereafter, the server sends a retrieve response to the client, including the resource representation requested by the client, the result of the retrieve operation, and an indication if the response was made into

24 Chapter 2. Theoretical Background an observe request. Now, the server monitors the state of the observed resource, and sends another retrieve response to the observing client if a change occurs. Whenever a client wants to cancel an observation, it can do so by sending a new retrieve request to the same resource without the observe indication [2]. This pattern is commonly referred to as the observer pattern, the publish- subscribe pattern, or the callback pattern. It provides notification to a set of inter- ested clients that relevant data has changed. The problem addressed by the solution pattern is that it would be too resource intensive if the clients should periodically be polling a server to discover resource state changes [26]. Instead, the observer pattern adds the possibility to subscribe to a notification list. Then a client can choose to subscribe to the list by adding a reference to its unique identifier. The dynamic modification of the subscriber list adds run-time flexibility to the software, and the pattern is resource efficient since the clients are only updated when necessary [26].

Resource Discovery Patterns The discovery mechanisms enable clients to discover relevant information about other peers in the network. The information can include instances of resources, resource interfaces, resource types, or any other information from the resource model that a peer wants other peers to discover. The OCF framework defines three resource based discovery mechanisms [2]. Re- source based means the discovery is enabled by defining a particular resource for discovery, whose representation contains information about discoverable resources hosted on a device. In these mechanisms, resource directory, resource discovery, and resource registration patterns are identified.

1. Direct discovery: The resources are registered locally at the device hosting them and are discovered though peer inquiry.

2. Indirect (resource directory based) discovery: The resources are registered and discovered at a third party device.

3. Advertisement discovery: The particular resource enabling discovery is hosted on the device seeking to discover other resources. Other remote peers will pub- lish relevant information about their discoverable resources to this particular discovery resource. The client’s discovery request can then be a local retrieve request against its own particular discovery resource.

Depending on the chosen mechanism, the publishing of information about dis- coverable resources, also called resource registration, can be done either locally or remotely. The discovery process, to find this information, is performed with a re- trieve request to the particular resource enabling discovery. The discovery retrieve request can be sent to a single device (unicast) or to multiple devices (multicast). The resource directory based, or indirect, discovery mechanism can be useful when a server device is constrained, or for some reason cannot always answer dis- covery requests. Resources can be located on different networks, or a device might need to sleep due to power limitations.

25 Chapter 2. Theoretical Background

The OCF framework defines processes for discovering third party devices acting as resource directories, selection criteria for choosing the most suitable resource directory, how a device publishes resources to a directory, how a device updates or deletes resource information, and how a device can switch to a new resource directory. The process of discovering a resource directory and how the directory supports resource queries are illustrated in Figure 2.7.

Figure 2.7: Communication for resource directory discovery and for resource directory supported discovery queries (adapted from Figure 30 of [2]).

Summary of Key Architectural Patterns In summary, the key architectural patterns identified in the OCF architecture are

• REST

– Client-Server – Stateless interactions – Uniform interfaces – Cacheable responses – Layered system

• Observer pattern

• Discovery mechanisms and processes

– Resource discovery – Resource registration – Resource directory

26 Chapter 2. Theoretical Background

2.4 Summary of Related Work

Previous work related to this project includes surveys on existing middleware so- lutions for IoT [7, 21], surveys identifying the most important functional and non- functional requirements of such middleware [3, 4, 5], and reports from organizations trying to define common concepts and models of the Internet of Things (IoT) [11, 1]. Moreover, there is work exploring RESTful architectures and REST patterns for IoT platforms [27], and authors presenting their own IoT middleware designs and in some cases evaluations [5, 27, 28]. Many surveys evaluating and comparing existing IoT middleware solutions do so by creating a check list of the features required from a middleware, and then simply ticking off the features supported by each middleware, based upon their specification. However, since previous research presents few practical evaluations of IoT middleware, this project aimed to evaluate an IoT middleware of increasing importance by implementing a prototype and perform experiments testing critical features.

27 Chapter 2. Theoretical Background

28 Methodology

This chapter presents the research methodology used in this thesis project. The Method for Evaluating Middleware Architectures (MEMS) is described and moti- vated, and the material used for the experimental setup is presented, describing the hardware, software version, operating system, and communication technology.

3.1 Method for Evaluating Middleware Architec- tures

This section explains and motivates the Method for Evaluating Middleware Archi- tectures (MEMS) and its application in this thesis project. MEMS is described in [9, 10].

3.1.1 Description and Motivation MEMS provides a systematic approach for evaluating the quality attributes of a middleware architecture. The evaluation process is based on key scenarios, which describe the behavior of an architecture with respect to relevant quality attributes. A scenario is a chain of events where the system’s response can be measured. Scenarios are useful since the quality attributes themselves are abstract and difficult to analyze without a context. According to the creators of MEMS, there is a strong relationship between the middleware technology and the resulting quality of the overall system [10]. Therefore the evaluation requires detailed input about the middleware’s mechanisms, infras- tructure, and architectural design patterns. This knowledge helps to evaluate the effect of architectural design decisions on the system quality.

3.1.2 Motivating a Case Study in MEMS MEMS is based on key scenarios describing events taking place in a system when implemented with the middleware in question. Each scenario is defined by a stimulus triggering a chain of events, and the expected response of the system. For each

29 Chapter 3. Methodology scenario, quality metrics are specified. Thereafter, experiments are designed and performed to measure the quality of the system response in each scenario. In order to perform experiments, a system prototype with applications interact- ing with the middleware is required. Moreover, the critical quality attributes to measure are usually found by looking at system specific requirements. Therefore, MEMS includes a case study of where the middleware is used to build a prototype of a particular system. In this thesis project, the case study will involve a building management system (BMS) prototype using IoTivity, as an example of an Internet of Things (IoT) application. The case study is described in Chapter 4.

3.1.3 Steps of MEMS This section explains the steps of MEMS and describes how they were applied in this project. The outcome of the first four steps was an evaluation plan, presented in Chapter 5. The validity of the experiments measuring each separate quality attribute is addressed in Section 7.1.2.

Determine Key Quality Attributes According to [9], the quality attributes chosen for evaluation in MEMS should be general attributes, such as performance, availability, or security. What is more, each quality attribute must have a defined scope in order to be meaningful. In this project, the critical quality attributes were determined by looking at pre- vious research of the most important requirements of IoT middleware architectures. The selected quality attributes and their specific concerns in the context of IoT were presented in Section 2.2.3.

Identify Key Architectural Design Patterns The next step was to identify the architectural design patterns that strongly im- pacted the behavior of the system. In order to know what patterns to look at, one can first identify the critical functional requirements of the architecture, and the functional components implementing these, and then single out the design patterns influencing these components the most. The most important functional requirements for IoT middleware were found through a literature review, and have been presented in Section 2.2.2. For the functional requirements that are addressed in the Open Connectivity Foundation (OCF) middleware architecture, the key architectural patterns were identified in the Open Interconnect Consortium (OIC) specification version 1.1 [2].

Generate Key Scenarios Multiple key scenarios were developed for each quality attribute. Each scenario was defined with a description, stimulus, expected response from the system, and related quality attribute. When applicable, specific functional requirements, architectural

30 Chapter 3. Methodology patterns, software components, and test configuration parameters were associated with the scenario. In order to organize and relate the attributes and key scenarios, an approach called ATAM utility tree [29] was applied. In this approach, the key quality at- tributes are organized in a tree structure, and for each level of the tree, the definition of the attribute is refined into sub-concerns. The sub-concerns explain the meaning of the attributes in a particular context. The leafs of the tree are the key scenarios. In this case, the sub-concerns in the utility tree were based on the descriptions of the key quality attributes for IoT middleware found in the literature review, the specific concerns of the building management system (BMS) in the case study, and on how the key architectural patterns influenced these sub-concerns.

Define Quality Metrics and Scales According to MEMS, quality metrics and scales should be defined for each key scenario. For adaptability, one can measure the effort required to impose a change in the system. For performance, it could be throughput or latency. A scale should be defined for each metric to enable analysis of the measurement results, and determine whether the results were satisfactory or not. To objectively tell if a result is good or bad can be difficult. If the system has quantified requirements, such as "client must receive response within 1 second", then it is easy to determine if the requirement is fulfilled or not. Otherwise, one must look at statistics over similar systems in order to say what is considered good or bad. In this project, only quantitative metrics were applied. The BMS in the case study did not have quantified requirements, and there were no standard target values or statistics available for quality metric scales in IoT systems. Therefore, scales were defined with the aim to give indications of the quality levels of an example IoT system using the IoTivity middleware.

Prototype The prototype developed was not meant to simulate a complete building manage- ment system. Rather it constituted a testbed or test environment integrating soft- ware components similar to those used in such a system. The required components are those that are necessary to perform the evaluation tests. The software stack consisted of an operating system (OS), IoTivity middleware, and application soft- ware.

Design Experiments The basic elements used for designing experiments were key scenarios, key compo- nents of system prototype, metrics, and test configuration parameters. By looking at how these elements are related, as suggested in MEMS, it was found that testbed components could be reused and extended, which facilitated more efficient testing. For metrics of response or processing times, that were not straightforward to measure, instrumentation was applied. This meant inserting timers at various points

31 Chapter 3. Methodology of the code and record the readings.

3.2 Equipment for System Prototype

The test environment consisted of three Raspberry Pi and one Hewlett-Packard computer, all connected via Ethernet to a local area network. Relevant details about these devices are given in Table 3.1.

Table 3.1: Device platforms used in test environment for building management system prototype.

Processor Number Device Model Operating System Architecture of Devices Hewlett-Packard ProBook AMD64 Ubuntu 14.04 1 computer 5320m Generation 2 Raspbian Jessie Lite Raspberry Pi ARM 3 Model B Kernel version 4.4

Middleware architecture IoTivity version 1.2.1 was used. IoTivity provides a base layer with C Application Programming Interface (API) and a service layer with C++ API. The base layer implements the OIC architecture specification described in Section 2.3, and therefore only the base layer was evaluated in this thesis project. The application software interacting with IoTivity base layer API was written in C++. The communication protocol used was Constrained Application Protocol (CoAP) over User Datagram Protocol (UDP)/Internet Protocol (IP).

32 Case Study

This chapter describes a theoretical case study of using the IoTivity middleware platform for an Internet of Things (IoT) system. A fictional case scenario, system software applications, and a prototype network setup are described and illustrated.

4.1 Case Scenario

This section describes a fictional case scenario of using IoTivity middleware when implementing a building management system (BMS) prototype. The following sec- tions describe the project, the team, and the building management system (BMS) prototype. The reason for including a fictional development project was to form scenarios in which the developers team imposed changes in or scaled up the IoT system pro- totype. These scenarios enabled measuring quality attributes such as adaptability and scalability.

4.1.1 Fictional Project An innovation team at a start up company has decided to explore the business op- portunities within Internet of Things, and specifically within building management systems (BMSs). The team consists of an innovation manager, developers, and a building manager. The building manager is meant to contribute with input from the end user’s point of view. The developers have experience of networking and communication, and designing embedded systems. During the first project phase, the team works to understand the market and the user needs, and obtains information that forms their vision and plan. Firstly, they become aware of the high level of heterogeneity occurring in IoT networks, and that using a middleware architecture is a good idea to provide interoperability, portability, and security. Secondly, the innovation manager realizes the benefits and importance of open source code and open standards, promoting innovation and technology advance- ment. Therefore, she decides to try out one of the open standard IoT middleware frameworks gaining recognition, called the Open Connectivity Foundation (OCF)

33 Chapter 4. Case Study framework. Conveniently, there is an open source reference implementation of this framework available, called IoTivity, which largely implements the specification but is still under development. The resulting vision and plan is to prototype a BMS with IoTivity.

4.1.2 Building Management System A building management system (BMS) is a computer-based control system used to monitor and manage the mechanical and electrical equipment of a building, such as lighting, ventilation, evacuation system, and security. Figure 4.1 depicts the building for which the BMS prototype is designed. The building has 3 floors, 15 rooms including restrooms, stairways, and an elevator reaching all floors. On the ground floor is the reception, and the control room from where the system administrator or building manager coordinates the BMS.

Figure 4.1: Overview of building for which building management system prototype was implemented.

The innovation team discusses what things and applications might be part of the BMS. The result of the discussion is a list of single resource types, collection resource types, and applications, shown in Table 4.1.

34 Chapter 4. Case Study

Table 4.1: Resources and applications in building management system prototype.

Single resource types Collection resource types Software applications Air Quality Sensor Alarm Door Door lock Alarm collection Elevator control Building light collection Light source Door lock collection Control station Location Floor light collection Building lighting system (BLS) Mode Room light collection Emergency evacuation system (EES) Motion detector Smoke detector collection Entrance security system(ESS) Operational State BLS control HVAC system (HVAC) Smoke detector EES control Surveillance camera ESS control Temperature HVAC control Thermostat Time interval Ventilation

A collection resource is a collection of links to other resources of the same or different type. If a request is sent to a collection resource, the request can be forwarded to all the linked resources of the collection. In the list below the collection resources occurring in the BMS are explained.

• Alarm collection - links to all alarms in a building. • Building light collection - links to all floor light collections, allowing client to control all light sources in the building with a single resource handle. • Door lock collection - links to all door locks in a building. • Floor light collection - links to all room light collections on a floor, allowing client to control light sources floor-wise. • Room light collection - links to all light sources in a room, allowing client to control light sources room-wise. • Smoke detector collection - links to all smoke detectors in a building. • BLS/EES/ESS/HVAC control - links to virtual resources, such as mode and operational state, used to monitor and control applications.

Next task for the developers was to define properties for each single and collec- tion resource type, according to the Open Connectivity Foundation (OCF) resource model used in IoTivity. Common properties that all resources have according to the model, are resource type, interface, name, and resource identity. A resource can have multiple resource types and interfaces. All resource type definitions for the BMS can be found in Appendix A. In the BMS, devices interact without requiring coordination by a central server. If the devices have the same physical layer transport and communication protocol, they can interact directly, peer-to-peer. Otherwise, an intermediate gateway can provide translation and forwarding of messages between devices. A software ap- plication running on one device can communicate with resource servers hosted on

35 Chapter 4. Case Study other devices in order to collect sensor data and set actuator values in an autonomic feedback loop. The system administrator can control and observe the things present in the network directly, or perform high level control and monitoring through the software applications. These communication patterns are illustrated in Figure 4.2.

Figure 4.2: Overview of communication in building management system.

4.1.3 Automatic Monitoring and Control Applications In this section, a short introduction of the four different software applications for automatic monitoring and control of the BMS is given.

Building Lighting System The building lighting system (BLS) is a software application offering automatic control of all the light sources in the building. In automatic mode, the lighting is controlled room-wise by motion detectors and timers. If motion is detected in a room, the room lighting should be turned on for a time period specified by the administrator.

Emergency Evacuation System The emergency evacuation system (EES) is used to aid a safe evacuation of people in the building in case of an emergency. The EES involves smoke detectors, alarms, door locks, and elevator control devices in the building. When a smoke detector senses fire, an emergency situation has arisen, and all alarms should sound, door locks should open, and the elevator should stop and open its doors at nearest floor. Since this is a safety system, it is crucial that all messages sent between devices really arrive.

36 Chapter 4. Case Study

Entrance Security System The entrance security system (ESS) controls the camera surveillance at the building entrance. During daytime, the camera should start recording when the entrance door opens, and stop recording 30 seconds after the door closes. During night time, the recording should start when the motion detector is activated, or when the door opens.

HVAC System HVAC stands for heating, ventilation, and air conditioning. A thermostat is placed in each room to maintain the desired temperature, by regulating heating and air conditioning. Each room or space also has ventilation and air quality sensors. The HVAC system should control the desired temperature of the thermostats, and regu- late the air flow of the ventilation units based on data from the air quality sensors.

4.2 Prototype

For the building management system (BMS) prototype, a simple network of three Raspberry Pi and one computer is set up, as shown in Figure 4.3. The IoTivity middleware is installed on all devices, and custom client and server software applications for the BMS are running on top of IoTivity.

Figure 4.3: An overview of the network setup for the building management system prototype.

The control station application is running on the Linux computer, allowing an administrator to monitor and control all resources in the network, and perform high level control through the building lighting system (BLS), emergency evacuation system (EES), entrance security system (ESS), and heating, ventilation, and air conditioning (HVAC) system applications. The BLS runs on Raspberry Pi number one, the EES and HVAC on Raspberry Pi number two, and the ESS on Raspberry Pi number three. The Raspberry Pi units also serve as platforms for all server devices involved in the BMS. The resources hosted by the server device applications are only simulated, and not real things.

37 Chapter 4. Case Study

4.2.1 Building Lighting System Device The BLS device hosts a BLS control resource, linking to a time interval resource, a mode resource and an operational state resource. Through the mode resource, the administrator can set the run mode to automatic or manual. The operational state resource serves as a device diagnostics resource, and tells the administrator if the BLS is fully operational or if a problem is preventing it from operating normally. With the time interval resource, the administrator can set the time period for which the lights should be turned on when motion is detected. The BLS application starts in manual mode. When put in automatic mode, it sends a multicast discovery request to discover all motion detectors and room light collections in the network. Thereafter, it sends an observation subscription request to all discovered motion detectors. When it gets a notification that motion is detected in a room, it sends a request to turn on the lights to the corresponding room light collection with matching location name. After the specified time interval, the application sends a new request to the same room light collection to turn off the lights. If the administrator puts the system in manual mode, the application cancels the notification subscriptions of the motion detectors and stops sending requests to the room light collections. This application requires access to the following external resources:

• All room light collections • All motion detectors

4.2.2 Emergency Evacuation System Device The EES device hosts an EES control resource, linking to a mode resource and an operational state resource. Through the mode resource, the administrator can set the run mode to automatic or manual mode. The operational state resource tells the administrator if the EES is fully operational or if there is a problem preventing it from operating normally. When the application starts, it is in manual mode. When put in automatic mode, the application sends a multicast discovery request to discover the alarm collection, the smoke detector collection, the door lock collection and the elevator control. Thereafter, it sends an observation subscription request to all smoke detectors in the building. If a smoke detector senses fire, it sends a notification to its observers. When the EES application receives a notification from a smoke detector, it sends requests to the alarm collection to activate all alarm signals, to the door lock collection to open all door locks, and the elevator control to go into emergency mode. All requests should be specified to require acknowledgment of message delivery. In manual mode, the application cancels the notification subscriptions and stops sending requests. This application requires access to the following external resources:

• Alarm collection

38 Chapter 4. Case Study

• Smoke detector collection • Door lock collection • Elevator control

4.2.3 Entrance Security System Device The ESS device hosts a ESS control resource, linking to a mode resource and an operational state resource. Through the mode resource, the administrator can set the system in automatic day, automatic night, or manual mode. The operational state resource tells the administrator if the ESS is fully operational or if there is a problem preventing it from operating normally. When the application starts, it is in manual mode. When put in automatic day mode, the application sends a discovery request in order to detect the surveillance camera and the door. Thereafter, it sends an observation subscription request to the door, so that it will be notified every time the door opens or closes. When it gets a notification that the door opens, it sends a request to the camera control to start recording. When it gets a notification that the door closes, it waits 30 seconds, and then sends a request to the camera control to stop recording. When put in automatic night mode, the application sends a discovery request in order to find the motion detector located in the entrance, and when detected, an observation subscription request. Then, either when the door opens, or whenever the motion detector is activated, the application commands the camera to start recording. When put back in automatic day mode, the application cancels all observation subscription on the motion detector. In manual mode, the application cancels the notification subscriptions and stops sending requests. This application requires access to the following external resources: • Surveillance camera •Door • Motion detector

4.2.4 HVAC System Device The HVAC device hosts an HVAC control resource, linking to a mode resource, an operational state resource, and a temperature resource. Through the temperature resource, the administrator can set the desired temperature of all thermostats in the building. Through the mode resource, the system can be set in automatic or manual mode. The operational state resource tells the administrator if the HVAC is fully operational or if there is a problem preventing it from operating normally. The application starts in manual mode. When put in automatic mode, the application sends a multicast discovery request in order to detect all thermostats, ventilations, and air quality sensors in the network. Thereafter, it sends an observa- tion subscription request to all air quality sensors. Then, every time an air quality sensor reports poor air quality, the application sends a request to the ventilation unit with matching location name to increase the air flow rate.

39 Chapter 4. Case Study

When the air quality sensor reports good air quality again, the application waits for ten minutes, and then sends a new request to the same ventilation unit to decrease the air flow to normal level. When the administrator sends an update request to the temperature resource, the HVAC application sends an update request to all thermostats in the network to update their desired temperature value. In manual mode, the application cancels the notification subscriptions and stops sending requests. This application requires access to the following external resources:

• All thermostats • All ventilations • All air quality sensors

40 Evaluation Plan

This chapter presents the plan for evaluating the IoTivity middleware architecture when used in a building management system (BMS) prototype. The plan includes the key scenarios, the metrics and scales, a description of the testbed components, and the experiment to be performed for each scenario.

5.1 Key scenarios

The key scenarios for the BMS operation are selected on the basis of the quality attributes to be measured. The quality attributes are affected by the selection of design patterns used when implementing the middleware components. Below, the quality attributes, functional requirements, functional components, and design pat- terns that form the basis for selecting scenarios are presented.

The key quality attributes identified for Internet of Things (IoT) middleware were: • Interoperability • Adaptability • Scalability • Security and Privacy (excluded from evaluation) • Real-time or Timeliness (excluded from evaluation) The key functional requirements identified for IoT middleware were: • Data management • Resource Discovery • Resource Management • Context Awareness (excluded from evaluation)

The components in the Open Connectivity Foundation (OCF) framework realizing this functionality were:

41 Chapter 5. Evaluation Plan

• Resource Model • Identification and Addressing • Discovery • Messaging • Create, Retrieve, Update, Delete, and Notify (CRUDN) operations

The key architectural design patterns affecting these components were:

• Representational State Transfer (REST) • Observer pattern • Resource discovery patterns

– Resource registration – Resource discovery – Resource directory

IoTivity does not have any context awareness feature, and the OCF framework does not address it. Neither does IoTivity support, or the framework address, applications with real-time requirements. Therefore, the quality attribute real- time/timeliness and the functional requirement context awareness were excluded from the evaluation. Furthermore, the quality attribute security and privacy was excluded since it was out of the scope of this thesis project. The quality attributes, their concerns in this specific context, and the key sce- narios were organized in a utility tree, shown in Figure 5.1. Seventeen key scenarios were defined in total. Six of them addressed interoper- ability, five of them adaptability, and six of them scalability. The key scenarios are presented in Tables 5.1 to 5.17.

42 Chapter 5. Evaluation Plan

Figure 5.1: A utility tree for organizing quality attributes, sub-concerns, and key scenarios for the evaluation.

43 Chapter 5. Evaluation Plan

Table 5.1: Key Scenario 1

Scenario #1 Client discovers all resources in network Stimulus Client device initiates a multicast discovery request to discover all re- sources in the network. Response At each server device, the default device discovery handler provided by IoTivity is called. The handler composes and sends a Retrieve response to the client containing URI, resource types, and resource interfaces of each discoverable resource the server device is hosting. Quality attribute Interoperability Func. requirements Resource discovery Arch. patterns REST, Discovery-pattern Direct Discovery Testbed components All components except simple client and simple server devices

Table 5.2: Key Scenario 2

Scenario #2 Client sends Retrieve/Update requests Stimulus Client device sends Retrieve/Update requests to all resources in BMS. The server devices are running on platforms different from the client device platform. Response Server device interprets request, accepts/rejects it, and sends appropri- ate response to client. Quality attribute Interoperability Func. requirements Resource management, data management Arch. patterns REST Testbed components All components except simple client and server devices

Table 5.3: Key Scenario 3

Scenario #3 Client sends Notify (notification subscription) requests Stimulus Client device initiates Notify requests to all observable and non- observable resources in BMS. The server devices are running on plat- forms different from the client device platform. Response Server device checks if requested resource is observable, and if so, reg- isters the requesting client as an observer of this resource, and sends a Retrieve response. If the resource is not observable, the server connector rejects request and sends appropriate response to client. Quality attribute Interoperability Func. requirements Resource management, data management Arch. patterns REST, Observer pattern Testbed components All components except simple client and server devices

44 Chapter 5. Evaluation Plan

Table 5.4: Key Scenario 4

Scenario #4 Client discovers resources linked by collection resource Stimulus Client sends Retrieve requests, with linked list interface specified, to all collection resources in BMS. Server devices are running on platforms different from the client device platform. Response At each server device hosting a collection resource, the default collec- tion entity handler provided by IoTivity composes and sends a Retrieve response to client containing the URIs of all linked resources. If the collection resource has no linked resources, the server should return an empty list. Quality attribute Interoperability Func. requirements Resource management, data management Arch. patterns REST Testbed components Alarm, door lock, lighting, smoke detector, BLS, EES, ESS, HVAC de- vices and control station

Table 5.5: Key Scenario 5

Scenario #5 Client sends Retrieve/Update requests to resources linked by collection resources Stimulus Client sends Retrieve/Update requests, with batch interface specified, to access the linked resources of all collection resources in BMS. Server de- vices are running on platforms different from the client device platform. Response At each server device hosting a collection resource, the default collection entity handler provided by IoTivity forwards the request to all linked re- sources. Each server device hosting a linked resource interprets request, accepts/rejects it, and sends appropriate response to collection resource server. The default collection entity handler aggregates responses from linked resources, and sends final response to client. Quality attribute Interoperability Func. requirements Resource management, data management Arch. patterns REST Testbed components Alarm, door lock, lighting, smoke detector, BLS, EES, ESS, HVAC de- vices and control station

45 Chapter 5. Evaluation Plan

Table 5.6: Key Scenario 6

Scenario #6 BMS is controlled automatically through BLS, EES, ESS, and HVAC systems. Building manager puts BLS, EES, ESS, and HVAC systems in automatic mode from control station. 6.1 Simulate a triggered motion detector. Stimulus 6.2 Simulate a triggered smoke detector. 6.3 Simulate the entrance door is opened. 6.4 Send Update request to temperature resource linked by HVAC con- trol device, to set the desired temperature of all thermostats in BMS. 6.1 BLS device gets notification from motion detector, sends Update request to light resource with same location name. 6.2 EES device gets notification from smoke detector, sends Update re- quests to alarm, door lock, and elevator control devices. Response 6.3 ESS device gets notification from door, sends Update request to surveillance camera device. 6.4 HVAC device accepts request, and sends Update requests to all 15 thermostat devices. Quality attribute Interoperability Func. requirements Resource management, data management Arch. patterns REST, Observer pattern Testbed components All BMS devices and control station. Number of air quality sensors, motion detectors, thermostats, and ventilation devices are 15.

Table 5.7: Key Scenario 7

Scenario #7 BMS server device is ported to another platform supported by IoTivity Stimulus A simple server device hosting an alarm resource must be ported from HP computer running Ubuntu to Raspberry Pi running Raspbian Jessie Lite. Response Developer makes the required changes in the IoTivity build script, cross compiles middleware and application software for the Raspberry Pi on the Linux computer, and copies the binary files to the Raspberry Pi. Quality attribute Adaptability Testbed components Control station and simple server device

Table 5.8: Key Scenario 8

Scenario #8 New alarm resource is added to BMS server device Stimulus Building manager wants to include an alarm device in the BMS. Response Developer adds an alarm resource in a server application, gives it an actuator interface, and creates a resource request handler for it. Quality attribute Adaptability Func. requirements Resource management Arch. patterns REST Testbed components Control station and simple server device

46 Chapter 5. Evaluation Plan

Table 5.9: Key Scenario 9

Scenario #9 Increase number of alarm resources on server device to 15 Stimulus Building manager wants to improve safety and place one alarm in each room of the building, adding up to 15 alarms in total. Response Developer does the required software changes/additions to increase the number of alarm resources hosted on device from 1 to 15 Quality attribute Adaptability Func. requirements Resource management Arch. patterns REST Testbed components Control station and simple server device

Table 5.10: Key Scenario 10

Scenario #10 Add new alarm collection resource to server device, linking to all 15 alarms Stimulus Building manager wants to create an alarm system, connecting all alarms together, so that the sound of all alarms in building can be turned on with a single request. Response Developer adds an alarm collection resource in a server application, gives it batch and linked list interfaces, sets the default collection entity han- dler as request handler, and binds all 15 alarm resources to it. Quality attribute Adaptability Func. requirements Resource management Arch. patterns REST Testbed components Control station and simple server device

Table 5.11: Key Scenario 11

Scenario #11 Change structure of lighting control system resource, from one collection resource linking to 90 lights, to a fan-out structure with 4 levels: 1 building, 3 floors, 15 rooms, 90 lights. Stimulus Building manager wants to be able to control the lighting in the building from the control station, not only on building level, but also floor-wise, room-wise, and on individual light level. Response Developer does the required additions/changes in server device software to create 1 building light collection, linking to 3 floor light collections, linking to 5 room collections each, linking to 6 light sources each. She creates request handlers for each collection resource, and sets proper interfaces. Quality attribute Adaptability Func. requirements Resource management Arch. patterns REST Testbed components Control station and lighting device

47 Chapter 5. Evaluation Plan

Table 5.12: Key Scenario 12

Scenario #12 Verify that all smoke detectors in BMS are still alive For safety reasons, all smoke detectors must send keep-alive messages to the control station every 30 seconds. 3 different methods: Stimulus 12.1 Client sends a Retrieve request to each smoke detector 12.2 Client sends a Retrieve request to the smoke detector collection 12.3 Smoke detector server devices notify the observing client 12.1 Each smoke detector sends a Retrieve response to client. 12.2 Collection resource forwards request to all smoke detectors, each Response smoke detector sends Retrieve response back to collection resource server, and collection resource server sends aggregated response to client. 12.3 Client receives Retrieve responses from all smoke detector devices. Quality attribute Scalability Arch. patterns REST, Observer pattern Testbed components Simple client device and smoke detector device Parameters Number of smoke detector resources on device

Table 5.13: Key Scenario 13

Scenario #13 State of observed smoke detector resource changes and all ob- servers are notified. Stimulus Smoke detector resource with subscribed observers changes state. Response Server hosting smoke detector notifies all observers by sending a Retrieve response to all clients subscribed as observers. Quality attribute Scalability Func. requirements Data management, resource management Arch. patterns REST, Observer pattern Testbed components Simple client device and smoke detector device Parameters Number of observers of resource

Table 5.14: Key Scenario 14

Scenario #14 Building manager turns off all the lights in the building Client initiates Update requests to all light sources by: 14.1 Sending 1 request to the building light collection resource Stimulus 14.2 Sending 3 requests, one to each floor light collection resource 14.3 Sending 15 requests, one to each room light collection resource 14.4 Sending 90 requests, one to each light source resource Response At each server hosting a collection resource, the default collection en- tity handler will forward the request to its linked resources. At each light resource server, the request will be interpreted, and if correct, the state of the light resource will change locally. Each light resource server responds with the updated resource representation to the collection re- source server, which sends the aggregated response back to client. Quality attribute Scalability Func. requirements Resource management, data management Arch. patterns REST Testbed components Simple client device and lighting device Parameters Number of light resources in the building

48 Chapter 5. Evaluation Plan

Table 5.15: Key Scenario 15

Scenario #15 Minimize disk space required for running simple server device with IoTivity Stimulus Building manager wants to reduce costs by minimizing the required memory resources for the simplest server devices. Response Developer removes middleware modules from the build in order to min- imize the size of the binary files required to run IoTivity and simple server application. Everything but the C API for resource constrained devices provided by IoTivity is removed. Quality attribute Scalability Testbed components Control station and smoke detector device Parameters Platform - Ubuntu (AMD64)/Raspbian (ARM)

Table 5.16: Key Scenario 16

Scenario #16 Measure RAM required for running simple server device with IoTivity Stimulus Building manager wants to reduce costs by minimizing required memory resources for the simplest server devices. Response Developer measures the RAM required to run IoTivity and simple server application, with tool Htop process viewer for Linux. Quality attribute Scalability Testbed components Control station and smoke detector device Parameters Platform - Ubuntu (AMD64)/ Raspbian (ARM)

Table 5.17: Key Scenario 17

Scenario #17 High QoS for communication with smoke detector devices is required, acknowledgment used to confirm delivery. Stimulus Client device sends Retrieve requests to all smoke detector devices in network. Response Smoke detector devices respond to requests. Quality attribute Scalability Func. requirements Resource management, data management Arch. patterns REST Testbed components Simple client device and smoke detector device 1. Low/high quality of service of requests Parameters 2. Number of smoke detector devices running on each Raspberry Pi 3. Number of resources hosted by each smoke detector device

Table 5.18 presents the quality metric and scale applied in each scenario. Re- garding the fail and pass metric scales, there are really no industry standards or common reference values to consider good or bad. Therefore, these scales are to be seen as indications only, used as a basis for discussion. Concerning the number of logical lines of code (LLOC) and software modules changed, there are no guidelines available, because it varies with programming lan- guage and application area. 40 LLOC and 3 modules could possibly represent what an application developer considers a reasonably low effort for imposing minor code

49 Chapter 5. Evaluation Plan

Table 5.18: Metrics and scales for key scenarios.

Quality Scale Metric Scenario(s) attribute Fail Pass Percentage of requests correctly Interoperability 1-6 <100% 100% processed. Number of logical lines of code Adaptability 7-11 >40 40 (LLOC) added/changed in source files. Number of software modules that Adaptability 7-11 >3 3 require changes. Time required to build/compile Adaptability 7 >1 h 1h IoTivity and application for the first time on new platform. Number of requested resources before Scalability 1, 12, 14, 17 <500 500 exceeding 10 sec round-trip delay time (RTD). OWD or RTD per request decreases/ Decreases increases as the number of requested Scalability 1, 12-14, 17 Increases or no resources increases. change Number of observers of resource before Scalability 13 <500 500 exceeding 10 sec OWD for notifying all observers. Size of binary files Scalability 15 >2 MB 2MB Size of data and stack segments in Scalability 16 >2 MB 2MB RAM changes. The same applies to the compile time of one hour which is a subjective as- sessment of what is acceptable for a developer. This refers to compiling the complete project for the first time or recompiling after fundamental changes. Medium size buildings in a BMS context are those measuring up to around 5000 square meters [30]. If there are 10 sensor, actuator, or controller resources per 100 square meters in the building, there are in total 500 resources in the building. If looking at response times from a usability perspective, 10 seconds is considered to be about the limit for keeping a user’s attention. If longer, she will want to perform other tasks in between and get an indication of when the computer expects to be done [31]. This is the background of the scalability metric numbers. The memory restrictions of 2 MB is just a generous example from the upper range of memory sizes for microcontrollers used in IoT applications.

5.2 Testbed Components

Table 5.19 presents the testbed components required for the experiments in the evaluation. The BMS server devices were simple applications hosting only one type of resource and in some cases collections linking to the same resources. They had resource request handlers specific for the resource type and interface. The BLS, EES, ESS, and HVAC devices were used in experiments measuring interoperability, to see whether the device-to-device communication was functioning correctly. The functionality of these devices have been described in Section 4.2. The smoke detector device was used in experiments measuring scalability, and therefore required the

50 Chapter 5. Evaluation Plan capability to measure one-way delay time (OWD). The simple server device was used in experiments measuring adaptability, and did not host any resources initially. The application code was extended in each experiment, adding resources and request handlers. The simple client device worked as a request generator performing a large number of discovery, Retrieve, Update, and Notify requests. It measured the round-trip delay time (RTD) for resource requests and data processing time when receiving notifications. The time measurements were printed to a file. The control station had a user interface and more complex data processing than the simple client device, and was not used for measuring RTDs or OWDs. The information retrieved at each resource request was stored in a linked list of resource objects, which the user could choose to print to a file. When processing responses, several checks were performed to see that requests had been processed correctly. Table 5.19: Testbed components used in the experiments.

Testbed component Resources (amount) Client/Server Air quality sensor device Air quality sensor (1) Server Alarm (15) Alarm device Server Alarm collection (1) Door device Door (1) Server Door lock (15) Door lock device Server Door lock collection (1) Elevator control device Elevator control (1) Server Light source (90) Location (15) Lighting device Room light collection (15) Server Floor light collection (3) Building light collection (1) Motion detector device Motion detector (1) Server Smoke detector (15) Smoke detector device Server Smoke detector collection (1) Surveillance camera device Surveillance camera (1) Server Thermostat device Thermostat (1) Server Ventilation device Ventilation (1) Server BLS control(1) Time interval (1) BLS device Both Mode (1) Operational State (1) EES control(1) EES device Mode (1) Both Operational State (1) ESS control (1) ESS device Mode (1) Both Operational State (1) HVAC control(1) Temperature (1) HVAC device Both Mode (1) Operational State (1) Control station - Client Simple client device - Client Simple server device - Server

51 Chapter 5. Evaluation Plan

5.3 Procedures for Interoperability Experiments

In this section the procedure for each experiment measuring interoperability is pre- sented. In key scenarios 1-5, the control station made different kinds of requests to access resources hosted on servers in the network. In key scenario 6, the building manager performed high level control through the software applications BLS, EES, ESS, and HVAC. In turn, these performed automatic monitoring and control of the BMS resources. The procedures in key scenarios 1-6 required that the control station and all BMS devices were running.

Procedure Key Scenario 1-5 1. Send requests from control station. The request types and target resources are specified in the key scenario description. 2. Control station processes all received responses and updates a local resource list containing resource data and metadata. 3. Print control station’s local resource list to a file. 4. Manually control against a check list that all requests were processed correctly.

Procedure Key Scenario 6 This scenario required that the control station client had discovered and retrieved the property values of all involved resources.

1. Send Update requests to BLS, EES, ESS, HVAC control resources from control station, in order to put the subsystems in automatic mode. 2. Simulate a triggered motion detector by sending an Update request to motion detector, set motion detected property to true. 3. Verify that light resource with same location name was turned on.* 4. Simulate a triggered smoke detector by sending an Update request to smoke detector, set smoke detected property to true. 5. Verify that all alarms, door locks, and elevator control were updated.* 6. Simluate an opened door by sending an Update request to door, set open state property to true. 7. Verify that surveillance camera resource state was updated.* 8. Send Update request to temperature resource on HVAC device, set desired temperature. 9. Verify that all thermostats have received the new desired temperature.*

*Verification was done by sending Receive requests to the concerned resources from the control station client.

52 Chapter 5. Evaluation Plan

5.4 Procedures for Adaptability Experiments

This section presents the procedures for the experiments measuring adaptability. Scenario 7 was meant to measure the effort required to port a BMS server device to another platform supported by IoTivity. Scenarios 8-11 were intended to measure the effort required to change or add basic application functionality. The applied metrics of effort were logical lines of code (LLOC) and number of software modules requiring modifications. An LLOC was defined as a statement terminated with a semicolon. A software module was defined as a source file and, if applicable, a header file containing type and function declarations implemented in the same source file. The number of software modules requiring modification could indicate the cohesion level of the system, meaning the degree to which the elements of a module belong together. The simple server device was used in the experiments for key scenarios 8-10. These experiments were built on each other and had to be performed in order, as the application code was extended in each experiment.

Procedure Key Scenario 7 1. Make required changes in IoTivity build scripts. 2. Measure time taken to cross compile IoTivity and BMS software for ARM architecture. 3. Copy binary files to ARM platform. 4. Test running BMS on ARM platform to verify it is working.

Procedure Key Scenario 8-11 1. Make required additions/changes in simple server application. 2. Test Discovery/Retrieve/Update requests to new resources with control sta- tion. 3. Count number of software modules that required additions/changes. 4. Count number of added/changed LLOC in simple server application.

5.5 Procedures for Scalability Experiments

This section presents the procedures for the experiments measuring scalability. In the experiments for scenarios 12-14 and 17, the ability to deal with large networks and data volumes was explored by gradually increasing the amount of re- sources and devices in the network, while measuring communication and processing times. The experiments for scenarios 15 and 16 explored the memory requirements for running a simple device application and the IoTivity middleware. Key scenario 17 aimed at exploring the scalability of the system as the network and data volumes grew, in the case where delivery of messages must be confirmed

53 Chapter 5. Evaluation Plan with an acknowledgment. Requiring message acknowledgments is here referred to as requiring high quality of service (QoS). The time measurements in these experiments were expected to require a gran- ularity of microseconds. Since the platforms in the experiments were Linux based, the function clock_gettime with the CLOCK_MONOTONIC clock found in time.h could be used for measuring elapsed time in the application. Since measurements of communication and execution time can be unreliable, each experiment was performed at least five times. Graphs showing how the round-trip delay time (RTD) and one-way delay (OWD) changed with the number of requested resources were plotted. From these graphs, the results for the applied metrics could be determined.

Procedure Key Scenario 12 This scenario required that the simple client had already discovered the smoke de- tector collection resource and all smoke detector resources in the network. For scenario 12.1 and 12.2, the RTD of requests and responses was measured. RTD was defined as the time from when the client initiated the Retrieve request, until it had received and processed all responses. In scenario 12.3, a notification, which is really a Retrieve response, was sent from server to client. This implied one way communication, and OWD was measured instead of RTD. Since the client and server applications were running on different physical devices, the time from the message was sent until it was received could not be measured without performing clock synchronization and timestamping, which was inconvenient in this test setup. What was measured instead was the time required at each server to initiate and send the message, and the time required at the client to receive and process all responses. These time periods were aggregated to get an OWD, which excluded the time the message was transported in the network.

1. Send a Retrieve request without any specified interface from simple client device to each smoke detector. Measure RTD. 2. Send a Retrieve request with batch interface from simple client device to the smoke detector collection resource. Measure RTD. 3. Send a Notify request from simple client to all smoke detectors, and verify all Notify requests have been accepted. 4. Send notification from each smoke detector to the simple client device. Mea- sure OWD. 5. Repeat previous steps while increasing number of smoke detectors, until RTD or OWD exceeds 10 seconds.

54 Chapter 5. Evaluation Plan

Procedure Key Scenario 13 This scenario required that all clients had already discovered the smoke detector. Note that the difference here from scenario 12 was that the number of notification subscribers (clients) increased instead of the number of smoke detectors (servers).

1. Send a Notify request from 100 simple clients, to a smoke detector resource. 2. Verify that all subscription requests are accepted. 3. Send a notification from the smoke detector to all clients. 4. Measure time spent at smoke detector sending notifications, time spent at clients receiving and processing notification, and aggregate time measure- ments. 5. Start 100 new clients, and repeat all steps, until OWD exceeds 10 seconds.

Procedure Key Scenario 14 This scenario required that the simple client had already discovered all resources hosted by the lighting device.

1. Send update requests from simple client to lighting device, in 4 different ways.

(a) Send 1 Update request to building light collection resource. (b) Send 3 Update requests, one to each floor light collection resource. (c) Send 15 Update requests, one to each room light collection resource. (d) Send 90 Update requests, one to each light source resource.

2. Measure RTD in simple client application. 3. Repeat previous steps while increasing number of light sources. 4. Note number of resources when RTD exceeds 10 seconds. 5. Compare slopes of RTD per resource as number of resources in cases 1a-1d. The least steep slope is the most scalable alternative.

Procedure Key Scenario 15 1. In IoTivity build scripts, remove all middleware modules not required for a simple server to use the C API of IoTivity base layer. 2. Build IoTivity project and simple server application for Ubuntu/AMD64 plat- form. 3. Run simple server application, and verify functionality by sending requests from control station. 4. Note size of project binary files. 5. Repeat above steps for Raspbian/ARM platform.

55 Chapter 5. Evaluation Plan

Procedure Key Scenario 16 The simple server device used in this scenario hosts one smoke detector resource.

1. Start simple server device on Raspbian/ARM platform. 2. Start Htop process viewer. 3. Note size of data, stack, and text in RAM, using Htop process viewer, when...

(a) simple server is running idle. (b) simple server handles Discovery request. (c) simple server handles Retrieve request. (d) simple server handles Update request.

4. Repeat above steps for Ubuntu/AMD64 platform.

Procedure Key Scenario 17 When starting this experiment, one smoke detector device hosting 100 smoke detec- tor resources was running on each Raspberry Pi. A simple client device was running on the HP computer.

1. Send multicast discovery request from simple client. Measure RTD. 2. Send Retrieve request to all smoke detector resources from simple client with low QoS. 3. Start an additional smoke detector device application on each Raspberry Pi. 4. Repeat steps 1-3, until each Raspberry Pi is running 10 smoke detector devices, or until RTD exceeds 10 seconds. 5. Start over, and perform the same procedure with high QoS (requiring acknowl- edgments of message delivery) for the Retrieve requests.

56 Results

This chapter presents the results of the experiments performed to evaluate the qual- ity attributes of IoTivity middleware architecture when used in a building manage- ment system (BMS) prototype. The key scenarios and experiment procedures have been described in Chapter 5.

6.1 Results of Experiments Testing Interoperability

In key scenarios 1 to 6, the administrator controls the BMS resources directly with the control station prototype, or performs high level control through the BLS, EES, ESS, and HVAC system prototypes. The results from the experiments measuring interoperability in these scenarios are presented in Table 6.1.

Table 6.1: Experiment results of interoperability metric: Percentage of requests correctly processed.

Scenario Description Result Pass/Fail 1 Client discovers all resources in network 100% Pass 2 Client sends Retrieve/Update requests 100% Pass 3 Client sends Notify (notification subscription) requests 100% Pass 4 Client discovers resources linked by collection resources 100% Pass 5 Client sends Retrieve/Update requests to resources linked 100% Pass by collection resources 6 BMS is controlled automatically through BLS, EES, ESS, 100% Pass and HVAC systems

6.2 Results of Experiments Testing Adaptability

This section presents the results of the experiments measuring adaptability in key scenarios 7 to 11. Tables 6.2 and 6.3 present the results per adaptability metric. The server device application that was extended in scenarios 8 to 10 initially contained 26 logical lines of code (LLOC), while the lighting device application had 124 LLOC.

57 Chapter 6. Results

Table 6.2: Experiment results of adaptability metric: Number of logical lines of code (LLOC) added/changed in source files.

Scenario Description Result Pass/Fail 7 BMS server device is ported to another platform supported 0 Pass byIoTivity 8 New alarm resource is added to BMS server device +40 Pass 9 Increase number of alarm resources on server device to 15 +8, -5 Pass 10 Add new alarm collection resource to server device, linking +6 Pass toall 15 alarms 11 Change structure of lighting control system resource, from +59, -7 Fail one collection resource linking to 90 lights, to a fan-out structure with 4 levels: 1 building, 3 floors, 15 rooms, 90 lights

Table 6.3: Experiment results of adaptability metric: Number of source code software modules that required changes.

Scenario Description Result Pass/Fail 7 BMS server device is ported to another platform supported 0 Pass byIoTivity 8 New alarm resource is added to BMS server device 1 Pass 9 Increase number of alarm resources on server device to 15 1 Pass 10 Add new alarm collection resource to server device, linking 1 Pass toall 15 alarms 11 Change structure of lighting control system resource, from 1 Pass one collection resource linking to 90 lights, to a fan-out structure with 4 levels: 1 building, 3 floors, 15 rooms, 90 lights

In key scenario 7, a simple server device is ported to another platform supported by IoTivity. The only action required to port the device application was to install a set of software packages on the new platform, and then specify the target architec- ture and operating system when running the build script provided by IoTivity. No changes were required in the application or middleware source code. In the experiment for key scenario 7, the IoTivity build script was modified in order to minimize the time required to build the middleware and the simple server application software. Unnecessary modules, such as unused features, services, and the C++ Application Programming Interface (API), were removed from the build. In total, this required commenting out 19 lines of code, in 2 out of 178 build scripts occurring in the IoTivity project. The compile times with the modified build script were: • Platform: AMD64 architecture, Linux OS - 22 seconds • Platform: ARM architecture, Linux OS - 5 minutes and 40 seconds For the ARM platform, which was a Raspberry Pi unit, the software was cross compiled on the Ubuntu computer. The Ubuntu computer was a HP ProBook 5320m with a dual-core Intel core i5 processor, clock frequency 2.4 GHz, 3 MB cache, and 4 GB RAM. The test required the compile time to be less than an hour, and so the test passed for both platforms.

58 Chapter 6. Results

6.3 Results of Experiments Testing Scalability

This section presents the results of the experiments for key scenarios 12 to 17. It was not possible to perform the experiment for key scenario 14, since it turned out that IoTivity version 2.1 does not support linking of resources in a fan-out structure with more than one level. The default collection resource request handler provided by IoTivity could only forward requests to its own linked single resources, and not the linked resources of a linked collection resource. The results are summarized per scalability metric in Tables 6.4 to 6.6.

Table 6.4: Experiment results of scalability metric: RTD per request decreases/increases as the number of requested resources increases.

Scenario Description Result Pass/Fail Verify that all smoke detectors in BMS are still alive 12.1 Increased Fail 12.1 Client sends a Retrieve request to each resource Verify that all smoke detectors in BMS are still alive 12.2 Increased Fail 12.2 Client sends a Retrieve request to collection resource 14 Building manager turns off all the lights in the building - - High QoS for communication with smoke detector devices No change 17 is required, acknowledgment used to confirm delivery Pass initially Client sends a Retrieve request to each resource

Table 6.5: Experiment results of scalability metric: OWD per request decreases/increases as the number of requested resources increases.

Scenario Description Result Pass/Fail Verify that all smoke detectors in BMS are still alive 12.3 Increased Fail 12.3 Smoke detector server devices notify all observers 13 Status of observed smoke detector resource changes and all No change Pass observers are notified

Table 6.6: Experiment results of scalability metric: Number of requested resources before exceeding 10 sec RTD or OWD.

Scenario Description Result Pass/Fail Verify that all smoke detectors in BMS are still alive 12.1 >1500 Pass 12.1 Client sends a Retrieve request to each resource Verify that all smoke detectors in BMS are still alive 12.2 250 Fail 12.2 Client sends a Retrieve request to collection resource Verify that all smoke detectors in BMS are still alive 12.3 >1500 Pass 12.3 Smoke detector server devices notify all observers 13 Status of observed smoke detector resource changes and >500 Pass allobservers are notified 14 Building manager turns off all the lights in the building - - High QoS for communication with smoke detector devices 17 is required, acknowledgment used to confirm delivery 2100 Pass Client sends a Retrieve request to each resource

59 Chapter 6. Results

In all data samples from the tests for key scenarios 12, 13, and 17, there were two distinguishable subsets of sample points. The first subset consisted of higher values, and in an unexpected way kept increasing and decreasing with the number of requested resources, as depicted in Figure 6.1. The graph in Figure 6.2 shows that, when plotting the higher subset from scenario 12.3, the total request processing times at the server and client decrease as the number of requests increase, which seems contradictory. The plots in Figures 6.3 to 6.5 are based on the values from the second subset of the samples with lower values. Only the values from this second subset of the samples were used when evaluating the results. In all graphs, there are error bars showing the standard deviation from the mean for each sample. In many cases, the standard deviation is too small to be visible in the plot.

5.5 Key Scenario 12.1 Key Scenario 12.2

] 5 Key Scenario 17 High QoS s 4.5

4

3.5

3

2.5

Total round-trip delay time [ 2

1.5

000 100 200 300 400 500 100 200 300 400 500 600 700 800 900 , , , , , , 1 1 1 1 1 1 Number of resources requested

Figure 6.1: A line chart showing resource request delay times in scenarios 12.1, 12.2, and 17. A marker represents the average value of the sample subset with larger, unexpected values. Error bars show standard deviation from the mean.

60 Chapter 6. Results ] s 5.5 Key Scenario 12.3 Client Key Scenario 12.3 Server 5

4.5

4

3.5

3

2.5

2

1.5

Total request processing time at server/client [ 000 100 200 300 400 500 100 200 300 400 500 600 700 800 900 , , , , , , 1 1 1 1 1 1 Number of resources requested

Figure 6.2: A line chart showing resource request delay times in scenario 12.3. A marker represents the average value of the sample subset with larger, unexpected values. Error bars show standard deviation from the mean.

Each data sample in the experiment for key scenario 12.2 consisted of 5 round- trip delay time (RTD) sample points. In the experiments for scenarios 12.1, 12.3, 13, and 17, the samples of RTD or one-way delay time (OWD) had 30 sample points. In all tests, the median and average values of the samples were close, and therefore resulted in plots with slightly different positioning but with the same appearance. In Figures 6.3 to 6.5, the average values of the samples are presented. High quality of service (QoS) was specified for resource requests in the experi- ments for key scenarios, which meant that acknowledgments were used to confirm delivery of messages. If no acknowledgment was received, the message was sent again, with a limited number of attempts. If low QoS was specified for requests, messages were lost as the number of requested resources approached 100 in scenarios 12.2, 12.3, and 13. Figure 6.3 shows a plot of the RTD per requested resource, measured in the experiments for key scenarios 12.1 and 12.2. In scenario 12.2, a client sends a Retrieve request with batch interface to a collection resource. When the number of resources linked by the collection resource exceeded 250, the collection resource’s request handler sent an error code as response to the request. Figures 6.3 and 6.4 show that the RTD or OWD per resource request increased with the number of resource requests sent in key scenarios 12.1, 12.2, and 12.3. In key scenario 13, OWD per resource remained the same throughout the experiment. In scenario 17, the RTD per resource was unchanged until the number of requested resources exceeded 1200, as depicted in Figure 6.5.

61 Chapter 6. Results

2

] Key Scenario 12.1 High QoS Key Scenario 12.2 High QoS .

ms 1 75

1.5

1.25

1

0.75

0.5

0.25 Round-trip delay time/request [ 0

000 100 200 300 400 500 100 200 300 400 500 600 700 800 900 , , , , , , 1 1 1 1 1 1 Number of resource requests sent

Figure 6.3: A line chart showing how the round-trip delay time per request changes with the number of requested resources in key scenarios 12.1 and 12.2. Error bars show standard deviation from the mean.

1 Key Scenario 12.3 High QoS Key Scenario 13 High QoS ] 0.9 ms 0.8 0.7 0.6 0.5 0.4 0.3 0.2

One-way delay time/request [ 0.1 0

000 100 200 300 400 500 100 200 300 400 500 600 700 800 900 , , , , , , 1 1 1 1 1 1 Number of resource requests sent

Figure 6.4: A line chart showing how the one-way delay time per request changes with the number of requested resources in key scenarios 12.3 and 13. Error bars show standard deviation from the mean.

62 Chapter 6. Results

] Key Scenario 17 Low QoS Key Scenario 17 High QoS

ms 6

5

4

3

2

1 Round-trip delay time/request [ 0

200 500 800 100 400 300 600 900 , , , , , 1 1 1 2 2 Number of resource requests sent

Figure 6.5: A line chart showing how the round-trip delay time per resource changes with the number of requested resources in key scenario 17, comparing results for low and high quality of service (QoS). Error bars show standard deviation from the mean.

In the experiment for key scenario 15, the IoTivity build script was modified in order to minimize the size of the binary files created when compiling the middleware and the simple server application software. The sizes of the binary files after compilation with the modified build script were: • Platform: AMD64 architecture, Linux OS - 3.5 MB (failed test) • Platform: ARM architecture, Linux OS - 2.8 MB (failed test) In the experiment for key scenario 16, the RAM required to run a simple server device was measured with Htop process viewer. The RAM required to run a simple server application with IoTivity middleware: • Platform: AMD64 architecture, Linux OS - 3.2 MB (failed test) – of which text segment was 24 kB, stack was 136 kB, and memory for shared libraries used by the process was 2904 kB • Platform: ARM architecture, Linux OS - 2.4 MB (failed test) – of which text segment was 8 kB, stack was 136 kB, and memory for shared libraries used by the process was 2200 kB The values for required RAM above are the maximum size of resident memory, labeled RES in Htop process viewer, registered during the experiments. RES rep- resents the text, data, and stack sections of RAM, and includes the used parts of memory storing shared libraries.

63 Chapter 6. Results

64 Discussion

This chapter gives a summary and discussion of the key findings from this thesis project. Conclusions are made with support from experiment results in order to form an answer to the research question. The importance and implications of the findings are discussed, and future work to solve open issues are suggested.

7.1 Discussion

The question in the research was how well IoTivity meets the key functional and quality requirements identified for Internet of Things (IoT) middleware, in the con- text of a building management system (BMS). In order to answer the question, the most important functional and quality re- quirements for IoT middleware first had to be identified. A literature study has shown that data management, resource discovery, resource management, and context awareness are the key functional requirements. Regarding the quality requirements, interoperability, security, timeliness, scalability, and adaptability are considered the most important. Another initial objective of the project was to identify the design patterns used when developing the IoTivity middleware architecture. As described in Section 1.1, design patterns can be seen as building blocks of a software architecture, and there- fore partly explain the behavior of a system. Three design patterns have been iden- tified in the architecture specification from Open Connectivity Foundation (OCF) and given focus in this project. These are the observer pattern, the direct resource discovery pattern, and Representational State Transfer (REST). This discussion aims to answer how IoTivity meets each and every one of these requirements, and how the design patterns have influenced the level of success.

7.1.1 Key Findings from Experiment Results • IoTivity provided the interoperability required in the case study.

The results from the interoperability experiments indicate that IoTivity can pro- vide both network, syntactic, and semantic interoperability, at least within the

65 Chapter 7. Discussion framework of the case study. The intention of the experiments for key scenarios 1 to 6 was to test IoTivity’s ability to manage heterogeneity occurring in the BMS prototype. 100 % of the requests made were processed correctly in all experiments.

• Effort required to port an IoTivity device to a new platform is low.

In key scenario 7, a simple server device application is ported from a PC with AMD64 architecture and Ubuntu operating system (OS), to a Raspberry Pi with ARM architecture and Jessie Lite OS. Apart from the additional effort required to cross compile software, the only actions needed were to install the required software packages on the new platform, and then specify the target architecture and OS when building the source code. Moreover, if the SCons build script provided by IoTivity to compile the source code was modified to remove redundant features and test files, the project build time for the Raspberry Pi platform was less than 6 minutes when cross compiling. The cross compilation was performed on a Linux computer with a 2.5 GHz dual-core Intel Core i5 processor, 4 GB RAM, and 3 MB cache memory. Both platforms used in the experiment are supported by IoTivity. The future aspiration of OCF is to support a wide range of platforms, in order to improve this interoperability aspect.

• Effort required to add or change basic functionality in a server device application is low.

Regarding adaptability, the ability to easily add or change basic functionality was tested. With the number of added/changed logical lines of code (LLOC) and mod- ified source files as metrics, the effort required to perform this adaption was low. This is thanks to the middleware providing the basic, common, functionality re- quired by all IoTivity server devices. The open connectivity stack handles discovery requests, collection resource requests, notification subscriptions and the underlying communication mechanisms such as identification, addressing, messaging. The higher number of LLOC added in the experiment for key scenario 11, was largely due to the floor and room light collection resources which required linking to a location resource hosted on the same device. Registering a new type of resource, the location resource, and providing a request handler for it accounted for around 50 % of the added LLOC.

• IoTivity is scalable in the sense that it is modular. Constrained devices can implement only the most basic functionality required to fulfill its purpose.

IoTivity provides a base layer C Application Programming Interface (API) for constrained devices, and a richer C++ API for non-constrained devices. For the BMS prototype and in the experiments, only the basic C API was used. If compiling the IoTivity 1.2.1 project source code including the C++ API, the size of the binary files was around 500 MB. After removing the C++ API, the memory requirements for an IoTivity server device hosting one resource were 2.8-3.5 MB non-volatile memory and 2.4-3.2 MB RAM for the ARM and AMD64 architectures respectively. In some contexts, this

66 Chapter 7. Discussion might be considered high with reference to resource-constrained devices. However, bearing in mind that IoTivity is an open-source project under development, the memory requirements might be reduced in the future, possibly by removing depen- dencies to certain libraries.

• As the network grows, meaning more client or server devices are added, the round-trip delay time (RTD) per resource request is unchanged.

In scenario 17, the number of server devices in the network is increased suc- cessively. The round-trip delay time (RTD) per resource request is measured as a client sends Retrieve requests to all resources on all server devices. In scenario 13, the number of client devices in the network is increased successively. The one-way delay time (OWD) per resource request is measured as a server device sends notifi- cations of a change of resource state to all client devices. In both experiments, the RTD or OWD per resource request is unchanged as the number of devices in the network increases.

• As an application grows, meaning the number of resources hosted by a single server device increases, the round-trip delay time (RTD) per resource request increases linearly.

In scenarios 12.1-12.3, the number of resources hosted by a server device appli- cation is increased successively. The RTD or OWD is measured as a client a) sends Retrieve requests to all resources, b) sends a Retrieve request to a collection linking to all resources, and c) receives notifications from all resources. In all cases, the RTD or OWD per resource request increased linearly. In scenario 12.1 and 12.3, the increasing delay is believed to be caused by linear searches performed by the server when handling a resource request. The theories for increasing RTD per resource request are explained in more depth below.

Possible explanations for rise in RTD per resource request, in the exper- iments for key scenarios 12-17 Each client or server device application has a client or server IoTivity stack. The stack is initiated as the client or server application starts. In the case of a server, the resources hosted by the server are registered in the stack, and there they are stored in a linked list of resource objects. Furthermore, the server stack keeps a linked list of all clients registered for notifications from any of the resources hosted by the server. This is a linked list of observer structures, where each structure contains a reference to the observing client and a reference to the observed resource. When a server device receives a resource request, the stack extracts the URI of the requested resource from the query. Thereafter, it iterates through the linked list of hosted resources, comparing the URI strings, in order to find the correct resource request handler to call. Iterating through the linked list is equivalent to a linear search. In the worst case, it makes n comparisons, where n is the number of resources hosted by the server device. A collection resource hosted by a server device is stored in the same linked list of resources in the stack. Therefore, when a collection resource is requested, the linear

67 Chapter 7. Discussion search is performed as for any other resource, and can result in n comparisons in the worst case. Moreover, when a resource state changes, and the server hosting the resource no- tifies all subscribed observers about the change, the stack performs a linear search as well. It iterates through the linked list of hosted resources, comparing 64 bit pointer values, in the search for the correct resource handle, only to verify its existence. Thereafter, the stack iterates through the entire linked list of observers, in order to find all observers of this particular resource.

12.1: In scenario 12.1, all resources hosted by a server are requested one by one by a client. The number of resources hosted by the server is increased successively during the experiment. Due to the linear search, requesting all resources will require 1+2+3+...+n = n(n+1)/2 comparisons, where n is the number of hosted resources. When n was increased from 100 to 200, it resulted in (200∗201−100∗101)/2 = 15050 additional URI string comparisons, which was on average 50 extra comparisons per resource request. The RTD per resource request also increased by 29 μs. If the 50 comparisons were the only reason for the 29 μs of increased RTD, it would mean almost 2 string comparisons per μs, comparing at least 21 characters in each URI. Considering that the Raspberry Pi model 2B used as server device in the experiment had a processor running at 900 MHz, the linear search probably was part of the cause of the increased RTD per resource request.

12.2: In scenario 12.2, a collection resource, linking to all other resources on the server device, was requested. The collection resource was registered last in the server stack, and was therefore unfortunately placed in the end of the linked list of resources. However, even if the linear search was performed, it was only done once for all requested resources. Therefore it should not have caused an increase in RTD per resource request. In this study, no evident explanation was found for the increase. A suggestion is that some exponential delay penalty for using larger packets occurred as the message size of the Retrieve response grew. When sending a Retrieve request to a collection resource, the response contains the resource state representations of all linked resources in one single message. IoTivity uses block-wise transfer for messages larger than 1024 bytes, a size that was exceeded in the experiment. High quality of service (QoS) was also used in the experiment, meaning acknowledgment was used to confirm message delivery, and non-confirmed messages were resent.

12.3: For scenario 12.3, linear search could also be part of the explanation. In this scenario, notifications are sent from a large number of resources to one observer. The explanation logic is the same as for 12.1, only that 8 byte pointer values were compared instead of URI strings. Moreover, the stack performs a second linear search through the entire list of observers, also comparing 8 byte pointer values. Increasing the number of resources hosted by the server from 100 to 200, therefore leads to 50 additional comparisons per resource request in the first linear search, and 100 additional comparisons per resource request in the second. This could reasonably be the cause of the 35 μs increase in RTD per request on average.

68 Chapter 7. Discussion

13: In the experiment for scenario 13, the RTD per resource request did not change. In this scenario, notifications are sent from one resource to a large number of ob- servers. Since it is only one resource during the whole experiment, the first linear search performed in 12.3 is eliminated. Furthermore, since all clients in the server stack’s linked list of observers are observing the same resource, the second linear search performed in 12.3 is only performed once for all resource requests, and there- fore does not cause an increase of the RTD per resource request as the number of requests increase.

17: In scenario 17, one Retrieve request is sent to each smoke detector resource from one single client. Initially, each Raspberry Pi was running one server applica- tion hosting 100 smoke detector resources. Then the number of server applications running on each Raspberry Pi was increased, until each was running 8 server appli- cations. Since the number of resources hosted by each server application was fixed, the length of the linked list of resources in each server stack was fixed. This elimi- nated the increasing delay of the linear search, and indeed the RTD per request did not change in the experiment, at least not until the number of requested resources exceeded 1200. A reasonable explanation for this is probably that the per process access to the processor core was decreasing as the number of server applications running on the Raspberry Pi increased. Each of the 3 Raspberry Pi had 4 processor cores. When the number of requested resources had reached 1200, each Raspberry Pi was running 4 processes, one on each processor core. As the number of resources was increased even further, each Raspberry Pi had to run more than 4 processes in parallel, forcing the processes to share processor cores. This was a limitation of the testbed, and not a weakness in the IoTivity middleware. For the sharper increase between 2100 and 2400 requested resources there was no obvious explanation found in this study.

7.1.2 Validity of Experiments This section discusses the validity of the experiments performed in order to evaluate the interoperability, adaptability, and scalability levels delivered by IoTivity. One important remark is that the test setup for these experiments had significant limitations. Simulating hundreds of devices with three Raspberry Pi units is not optimal for evaluating scalability. Neither did the BMS prototype contain real sensor or actuator resources, these were only simulated by virtual objects. The validity of the evaluation would have been improved with a real case scenario instead of a fictional. It could have provided more detailed, technical insights and requirements, which could have resulted in a more critical analysis of the IoTivity middleware platform.

Interoperability Quantifying interoperability is not an easy task. Achieving IoT system interoper- ability is largely a matter of management commitment, where the industry must agree upon which standards and conventions to use.

69 Chapter 7. Discussion

Interoperability is about allowing devices to communicate successfully despite heterogeneity in the network. In the experiments, the communication mechanisms required in key scenarios 1 to 6 were put to the test. The applied metric, percent- age of requests correctly processed, was meant to show how IoTivity managed the heterogeneity of system components occurring in the BMS prototype. The hetero- geneity in this situation arose partly from the variety of resource types, and partly from the differences between the intercommunicating platforms. The control station application were running on a Linux computer, while the other BMS devices were distributed over three Raspberry Pi units. A relevant improvement of these experiments would have been to introduce more heterogeneity into the system, such as a wider variety of platforms, communication technologies and protocols, and components such as gateways or proxies. However, it was out of the scope of this thesis project.

Adaptability Adaptability is also a quality attribute which is usually not straightforward to mea- sure. Within a company or organization, the effort to impose changes on a system can be measured in time and money, and be compared across software projects. Such metrics were not applicable in this project. Instead, the solution was to quantify the effort of changing or adding functionality as the amount of modified software. Although the number of LLOC can be a question of individual programming style, there was only a limited number of program instructions required to implement the new functionality when using the IoTivity API. In order to increase transparency, the resulting pieces of code before and after changes in key scenarios 8 to 10 have been presented in Appendix B.

Scalability According to the literature review, the two main scalability concerns for IoT mid- dleware were the possibility for resource-constrained devices to host the middleware, and the ability of the system to handle large networks and large volumes of data. One limitation of the evaluation was that key scenarios 15 and 16 only considered memory, which is just one of the possible resource constraints for IoT devices. Another limitation was the small number of platforms in the experimental net- work setup. In scenario 17, the scalability is tested as the number of smoke detector devices are increased. Since these device applications were running on the same physical device, they were sharing the processing and communication resources of the platform. As mentioned in Section 6.3, the data samples from the tests for key scenarios 12 to 17 consisted of two clearly distinguishable subsets of sample points. This issue occurred for both client and server applications, with high and low QoS, and both when including network transport delay and not in the time measurements. Plotting the subset of the data samples with high values of RTD or OWD resulted in zigzag patterns, for which it was difficult to make any kind of scalability analysis. Plotting the subset with lower values, gave graphs were the total RTD and OWD increased as the number of resource requests increased, which was the expected result. Only

70 Chapter 7. Discussion the lower subsets were used for the scalability evaluation, and no explanation was found for the higher subsets.

7.1.3 Influence of Design Patterns Observer Pattern The observer pattern, or the notification mechanism, provides a scalable alternative to polling since it eliminates the need for redundant requests to resources whose state is unchanged, which reduces network traffic. Moreover, a notification only causes a one-way delay time (OWD) and not a round-trip delay time (RTD). The experiments showed that the OWD per resource request did not increase as the number of clients subscribed to a single resource increased. Neither did the OWD per resource request increase if the number of resources that a client has subscribed to increases, as long as the resources are hosted on separate devices. IoTivity supports subscription to notifications from resources registered as ob- servable. The dynamic subscriptions and canceling of subscriptions promotes adapt- ability, since new applications and resources can be integrated after system deploy- ment and use this feature. In the BMS, the notification feature was used in the BLS, EES, ESS, and HVAC systems. One example is the building lighting system application, which subscribed to notifications from all 15 motion detectors. If motion was detected in a room, all light sources in that room should be lit without noticeable delay. Without the asynchronous notification feature, the BLS application would have to constantly poll all the motion detectors in the building at least every second. In a large system, this can create a lot of undesirable network traffic.

Direct Discovery Pattern The discovery mechanisms supported by IoTivity has been presented in Section 2.3.5. In this study, only the direct discovery mechanism was used, which meant that resources were registered locally at the hosting server, and discovered through peer inquiry to a particular resource enabling discovery. The support for multicast discovery requests, and not only unicast to a specific URI, enabled a client to find all resources available in the network, and then filter them on resource type or name in order to find the resource it needed. For example, in the BMS prototype, the emergency evacuation system could find all resources of alarm type in the building, without being required to know beforehand how many alarm resources were present or at which network addresses. This promotes adaptability since a user can add or replace resources, and give them new unique resource identifiers, without affecting the operation of client applications. If a server device is constrained or for some reason cannot always answer discovery requests, the indirect discovery mechanism can be used, where the resources are registered and discovered at a third party device. Having this option promotes scalability.

71 Chapter 7. Discussion

REST architectural style The experience from this thesis project is that the RESTful resource model from OCF was easy to comprehend and use. It was straightforward to model the things involved in the BMS according to the resource model. The principle of layered systems in the REST architectural style promotes inter- operability and scalability since it allows intermediate devices such as gateway and proxies in the chain of communication. These intermediaries can act as translators between devices using diverse communication technologies and procotols. They can further act as assistants to resource constrained or sleepy devices, handling discov- ery and other requests. This principle builds upon other REST principles such as uniform interfaces and stateless interactions. One part of the uniform interface principle of REST is HATEOAS, which says that a RESTful architecture should provide means to link resources to one another, provide unambiguous semantics for following and embedding these links in resource representations, and thereby make it possible to discover and connect to other re- sources through the links. In order to conform with this principle, OCF has adopted the concept of collec- tions and links. A collection resource contains links or references to other resources. This allows a set of resources to be referenced with a single handle. A collection can also be used to represent resource hierarchies or composite resources consisting of several base resources. In the BMS, collections were used to turn on or off all the lights in a room or floor with a single client request. It was also used to create device control resources for the BLS, EES, ESS, and HVAC subsystems. For example, the HVAC device control resource was a collection of a mode resource, an operational state resource, and a temperature resource. The state of these three, virtual, linked resources was used to monitor and control the HVAC system. A good argument for using collections to represent composite resources, is to keep the resource type definitions simple and generic. Instead of defining a large number of complex resource types with numerous properties, it could be a better idea to use collections composed by simpler resources from a standard set, which all devices in your IoT ecosystem can recognize and use. In applications with Machine- to-Machine (M2M) communication, common device data models are required for semantic interoperability and independence between IoT devices. The Open Interconnect Consortium (OIC) specification version 1.1 includes a resource type specification, which so far contains 62 different standard definitions of frequently occurring resource types. They have also released one application profile, the smart home device specification. Moreover, OCF has a parallel project with a web-based tool called oneIoTa, enabling users to specify device data models using RAML and JSON. With this tool they want to encourage crowd-sourcing of data models, and so far two releases of approved data models have been published. Considering that billions of devices are predicted to be connected to the IoT in the future, one can imagine the diverse range of devices that must be virtualized. Examples of diverse resource types in the OCF specification are ice maker, colour chroma, door, generic sensor, and night mode. Is it possible or even desirable to create standard models for all these things and concepts? This seems to be one of

72 Chapter 7. Discussion the challenges for the IoT standards organizations.

7.1.4 Further Reflections on Quality Requirements • Devices should be able to interact across heterogeneous networks, potentially using different communication technologies or protocols.

In the BMS prototype, the communication technology and protocol were the same for all devices, so the evaluation did not cover testing this requirement. How- ever, the intention of OCF is that the middleware will work across various technolo- gies such as WiFi, Bluetooth Low Energy, Zigbee, and Zwave [8]. Today IoTivity supports the Constrained Application Protocol (CoAP), and the future aim is to be able to map multiple communication protocols to the Create, Retrieve, Update, Delete, and Notify (CRUDN) operations. Intermediate gateways can be used to translate communication between nodes using different protocols.

• Middleware is intended to be reusable for a wide range of application and use scenarios, and must be adaptable to the numerous changes of environment, circumstances and application-level demands occurring within IoT.

The ability to adapt to diverse application scenarios is heavily influenced by the resource and communication models of the middleware architecture. The approach used by OCF to provide adaptability and flexibility, seems to be employing simplicity and generality. It is the resource model that provides consistency and semantic interoperabil- ity between devices in an IoT ecosystem. The challenge lies in finding a resource model, that is general enough to be adaptable to multiple application scenarios, but still expressive enough to enable meaningful interaction between devices. Another question is if it is possible or even desirable to enable devices from diverse vertical markets to interact, or if the cost of doing so outweighs the benefits. One suggestion from OCF, mentioned in the OIC specification version 1.1 [2], is to adopt multiple resource model support, rather than finding one model suiting all. In this approach, the interacting client and server has to be aware of which resource model, out of a limited set, the other one is following, in order to interpret a request correctly. OCF particularly mentions the resource models, also referred to as data models, specified by the IPSO Alliance and oneM2M. According to [2], the main differences between the resource models from OCF, IPSO Alliance, and oneM2M are found in the resource structure, name and type conventions, and whether or not resource hierarchies can be formed. As it seems, the resource model is not yet set in stone for any of these stan- dards and will probably improve as the IoT technology matures and gathers user experience from diverse application scenarios. It will be for the future to show what solution is chosen to provide interoperability among IoT devices from various vertical markets, if any at all. Regarding the adaption to different environments and application-level demands occurring within IoT, there lies a strength in the possibility to choose manufacturer, OS, and physical transport for your device. An application-level demand can also

73 Chapter 7. Discussion consist in what set of operations have to be available. The OCF communication model is based on only the five fundamental CRUDN operations. This results in both freedom and responsibility for the application developer. For example, the Retrieve operation can be used to perform discovery, collect sensor data, get metadata or current configuration of a device, or any other information request implemented by the developer at application level.

7.2 Conclusions

This thesis project aimed to answer the question how IoTivity meets the key func- tional and quality requirements identified for Internet of Things (IoT) middleware, in the context of a building management system. The conclusion is that IoTivity partly meets the identified requirements. Regarding the functional requirements, IoTivity to a certain extent provides functionality for data management and resource management, and provides three different mechanisms for resource discovery. It does not provide explicit support for context awareness. IoTivity data management features include data acquisition and transfer, or sim- ply resource consumption. Device and resource configuration can be implemented by exposing settings and operational modes as dedicated, virtual resources. Another alternative is to use the richer C++ Application Programming Interface (API) for resource configuration and diagnostics, although this API was not evaluated in this project. As to the quality requirements, IoTivity provided the interoperability required in the building management system (BMS) case study, including handling of diverse resource types and interaction between devices running on heterogeneous platforms. In the experiments, IoTivity demonstrated a high level of adaptability, since the effort required for porting a device to a new platform, and adding or changing func- tionality was low. The experiment results further showed that IoTivity provides scalability as the number of devices in the network grows, since the round-trip delay time (RTD) or one-way delay time (OWD) per resource request did not increase. When more resources were added to a single server device, the RTD and OWD per resource request increased slightly due to linear searches performed by the server stack to locate the correct resource upon a request. This could be resolved by im- plementing a more efficient search algorithm. Although the Representational State Transfer (REST) architectural style provides fast execution and response times, Io- Tivity has no inherent functionality that provides predictability of response times, and thus there is no support for real-time behavior. IoTivity is under active development and still has a way to go before it can be widely deployed in the industry. Besides, the IoT sector is still immature, and in the future, new experiences and technologies can change the conditions on the IoT market. Open Connectivity Foundation (OCF) promotes openness and coopera- tion, and encourages contribution from users and developers from various vertical markets. The Open Interconnect Consortium (OIC) specification addresses many of the challenges identified for IoT, targets simplicity and generality, and builds upon well-known and established open standards. These are aspects that can in-

74 Chapter 7. Discussion crease the chances of the OCF framework becoming one of the widely-used standard architectures in the future.

7.3 Recommendations for Future Work

• Explore how context awareness features can be applied on top of IoTivity.

• Explore how real-time behavior can be implemented when using IoTivity.

• Evaluate how IoTivity and OCF meets the security requirements imposed on IoT systems.

• Perform further scalability tests for IoTivity with truly large networks, in order to get a more valid scalability evaluation.

• Perform further interoperability tests for IoTivity, introducing additional het- erogeneity in the form of diverse communication protocols, physical transport, hardware, operating system or bare metal, and even different resource models.

75 Chapter 7. Discussion

76 Bibliography

[1] K. Rose, S. Eldridge, and L. Chapin, “The Internet of Things (IoT): An overview - Understanding the issues and challenges of a more connected world,” white paper, The Internet Society (ISOC), October 2015.

[2] OIC Core Candidate Specification V1.1.0 Part 1, 2016.

[3] S. Bandyopadhyay, M. Sengupta, S. Maiti, and S. Dutta, “Role of middleware for internet of things: A study,” International Journal of Computer Science and Engineering Survey (IJCSES), vol. 2, pp. 94–105, August 2011.

[4] M. A. Razzaque, M. Milojevic-Jevric, A. Palade, and S. Clarke, “Middleware for internet of things: A survey,” IEEE Internet of Things Journal, vol. 3, pp. 70–95, Feb 2016.

[5] J. Cecílio and P. Furtado, Wireless Sensors in Heterogeneous Networked Sys- tems: Configuration and Operation Middleware. Springer International Pub- lishing, 1 ed., 2014.

[6] T. Noergaard, Demystifying Embedded Systems Middleware. Burlington: Newnes, 1 ed., 2010.

[7] H. Derhamy, J. Eliasson, J. Delsing, and P. Priller, “A survey of commer- cial frameworks for the internet of things,” in 2015 IEEE 20th Conference on Emerging Technologies and Factory Automation (ETFA), pp. 1–8, Piscataway, NJ: IEEE Communications Society, 2015.

[8] Open Connectivity Foundation, “About open connectivity foundation.” https: //openconnectivity.org/about, 2016. Accessed October 2016.

[9] K. Foster, J. Liu, and A. Iannos, “Developing an evaluation method for middleware-based software architectures of airborne mission systems,” Tech- nical Report DSTO-TR-2204, AR-014-310, Department of Defence, Air Oper- ations Division, Defence Science and Technology Organisation, Australia, July 2007.

[10] Y. Liu, I. Gorton, L. Bass, C. Hoang, and S. Abanmi, “Mems: A method for evaluating middleware architectures,” in Quality of Software Architectures: Second International Conference on Quality of Software Architectures, QoSA

77 Bibliography

2006, Västerås, Sweden, June 27-29, 2006 Revised Papers (C. Hofmeister, I. Crnkovic, and R. Reussner, eds.), pp. 9–26, Berlin, Heidelberg: Springer Berlin Heidelberg, 2006.

[11] International Telecommunication Union (ITU), “ Recommendation ITU-T Y.2060, Overview of the Internet of things.” http://handle.itu.int/11. 1002/1000/11559, 2012. Accessed October 2016.

[12] IEEE Standard for Low-Rate Wireless Networks, IEEE Standard 802.15.4-2015.

[13] “Zigbee alliance.” http://www.zigbee.org. Accessed October 2016.

[14] “Z-wave alliance.” http://z-wavealliance.org. Accessed October 2016.

[15] “Thread Group.” http://www.threadgroup.org. Accessed October 2016.

[16] IoT6, “6LoWPAN.” http://iot6.eu/6lowpan, 2014. Accessed October 2016.

[17] S. Deering and R. Hinden, “Internet protocol, Version 6 (IPv6) Specification,” 1998.

[18] “Frequently Asked Questions.” http://mqtt.org/faq. Accessed October 2016.

[19] A. Stanford-Clark and H. L. Truong, “MQTT For Sensor Networks (MQTT- SN), Protocol Specification Version 1.2.” http://mqtt.org/new/wp-content/ uploads/2009/06/MQTT-SN_spec_v1.2.pdf, 2013. Accessed November 2016.

[20] “The Constrained Application Protocol (CoAP).” https://tools.ietf.org/ html/rfc7252. Accessed October 2016.

[21] X. Li, M. Eckert, J.-F. Martinez, and G. Rubio, “Context aware middleware architectures: Survey and challenges,” Sensors, vol. 15, no. 8, p. 20570, 2015.

[22] G. D. Abowd, A. K. Dey, P. J. Brown, N. Davies, M. Smith, and P. Steggles, “Towards a better understanding of context and context-awareness,” in Pro- ceedings of the 1st International Symposium on Handheld and Ubiquitous Com- puting, HUC ’99, pp. 304–307, London, UK, UK: Springer-Verlag, 1999.

[23] Open Connectivity Foundation, “Introduction of oic standard.” https://openconnectivity.org/wp-content/uploads/2016/01/OIC_ Specification_Overview_201501131.pdf, 2016. Accessed October 2016.

[24] IoTivity, “About.” https://www.iotivity.org/about, 2016. Accessed November 2016.

[25] R. T. Fielding and R. N. Taylor, “Principled design of the modern web archi- tecture,” ACM Trans. Internet Technol., vol. 2, pp. 115–150, May 2002.

[26] B. P. Douglass, Design Patterns for Embedded Systems in C. Boston: Newnes, 2011.

78 Bibliography

[27] C. Pautasso, E. Wilde, and R. Alarcon, eds., REST: Advanced Research Topics and Practical Applications. Springer New York, 2014.

[28] F. C. Delicato, P. F. Pires, and T. Batista, Middleware Solutions for the Internet of Things. Springer London, 2013.

[29] L. Bass, P. Clements, and R. Kazman, Software Architecture in Practice (2nd Edition). Addison-Wesley Professional, 2003.

[30] S. Katipamula, J. Granderson, R. Brown, and D. Taasevigen, “Small- and medium-sized commercial building monitoring and controls needs: A scoping study,” Technical Report pnnl-22169, United States. Dept. of Energy.;Pacific Northwest National Laboratory Richland, Washington, D.C, October 2012.

[31] J. Nielsen, Usability Engineering. San Francisco, CA, USA: Morgan Kaufmann Publishers Inc., 1993.

79 Bibliography

80 Resource Type Definitions of Build- ing Management System

A.1 Property Definitions for Single Resource Types

Table A.1: Common properties of all resources.

Property Property Value Value Access Unit Mandatory Description title name type rule mode Property to declare the Resource rt array R yes resource types Type supported by a resource. Property to declare the Interface if array R yes interfaces supported by a resource. Human- Name n string R no friendly name imple- Resource Unique id string mentation R no Identity resource id dependent

A.1.1 Air Quality Sensor

Table A.2: Air quality sensor resource properties.

Property Value Mandatory Access Description name type mode isAdequate Boolean Yes Read True: air quality is adequate only False: air quality is inadequate location String No Read Location of air quality sensor Write

I Appendix A. Resource Type Definitions of Building Management System

A.1.2 Alarm

Table A.3: Alarm resource properties

Property Value Mandatory Access Description name type mode sound Boolean Yes Read True: alarm sounds False: Write alarm is quiet location String No Read Location of the alarm Write

A.1.3 Door

Table A.4: Door resource properties

Property Value Mandatory Access Description name type mode openState Boolean Yes Read True:doorisopen only False: door is closed location String No Read Location of the door Write

A.1.4 Door Lock

Table A.5: Door lock resource properties

Property Value Mandatory Access Description name type mode lockState Boolean Yes Read True: is locked False: only is unlocked location String No Read Location of door lock Write

A.1.5 Elevator Control

Table A.6: Elevator control resource properties

Property Value Mandatory Access Description name type mode currentMode String Yes Read Current mode of elevator control Write device modes Array No Read Array of possible modes the only elevator control device supports opState String No Read Current state of operation of the only elevator Floor String No Read Current floor of elevator car only

II Appendix A. Resource Type Definitions of Building Management System

A.1.6 Light Source

Table A.7: Light source resource properties

Property Value Mandatory Access Description name type mode isOn Boolean Yes Read True: light is on only False: light is off location String No Read Location of light source Write

A.1.7 Location

Table A.8: Location resource properties

Property Value Mandatory Access Description name type mode location String Yes Read A name of a location Write

A.1.8 Mode

Table A.9: Mode resource properties

Property Value Mandatory Access Description name type mode currentMode String Yes Read Currently active mode Write modes Array Yes Read Array of supported modes only

A.1.9 Motion Detector

Table A.10: Smoke detector resource properties

Property Value Mandatory Access Description name type mode motionDet Boolean Yes Read True: motion is detected only False: no motion is detected location String No Read Location of motion detector Write

III Appendix A. Resource Type Definitions of Building Management System

A.1.10 Operational State

Table A.11: Operational state resource properties

Property Value Mandatory Access Description name type mode state String Yes Read Current state of operation only

A.1.11 Smoke Detector

Table A.12: Motion detector resource properties

Property Value Mandatory Access Description name type mode smokeDet Boolean Yes Read True: smoke is detected only False: no smoke is detected location String No Read Location of smoke detector Write

A.1.12 Surveillance Camera

Table A.13: Surveillance camera resource properties.

Property Value Mandatory Access Description name type mode isRecording Boolean Yes Read True: camera is recording Write False: camera is not recording location String No Read Location of surveillance camera Write

A.1.13 Temperature

Table A.14: Temperature resource properties.

Property Value Mandatory Access Description name type mode temperature Double Yes Read Current temperature setting or Write measurement currentUnit String No Read Current unit of temperature value Write units Array No Read Array of possible units for the only temperature value range Array No Read Array defining min/max values for only the temperature on this device

IV Appendix A. Resource Type Definitions of Building Management System

A.1.14 Thermostat

Table A.15: Thermostat resource properties

Property Value Mandatory Access Description name type mode isOn Boolean Yes Read True: thermostat is on Write False: thermostat is off desiredTemp Double Yes Read Desired temperature for thermostat Write to maintain currentTemp Double Yes Read Current temperature sensed by thermostat location String No Read Location of the thermostat Write

A.1.15 Time Interval

Table A.16: Time interval resource properties

Property Value Mandatory Access Description name type mode interval Integer Yes Read Desired time interval Write currentUnit String No Read Current time unit Write units Array No Read Array of possible time units only range Array No Read Array defining min/max values for only time interval

A.1.16 Ventilation

Table A.17: Ventilation resource properties

Property Value Mandatory Access Description name type mode powerOn Boolean Yes Read True: ventilation is powered on Write False: ventilation is powered off airFlowRate Integer No Read Rate of air flow Write unit String No Read Unit of air flow rate only range Array No Read Array defining min/max values for only air flow rate location String No Read Location of ventilation Write

V Appendix A. Resource Type Definitions of Building Management System

A.2 Required Resource Links of Collection Re- source Types

Table A.18: Collection resource type definitions.

Collection Resource Required Linked Resource Type(s) Building light collection One or multiple floor light collection resources Floor light collection One or multiple room light collection resources One or multiple light source resources Room light collection One location resource Alarm collection One or multiple alarm resources Smoke detector collection One or multiple smoke detector resources Door lock collection One or multiple door lock resources One mode resource ESS control One operational state resource One time interval resource BLS control One mode resource One operational state resource One mode resource EES control One operational state resource One temperature resource HVAC control One mode resource One operational state resource

VI Appendix A. Resource Type Definitions of Building Management System

A.3 Resource Type and Interface Definitions

Table A.19: Resource Type and Interface Definitions.

Informative Name Resource Type(s) Interface(s) Air quality sensor r.air.quality.sensor Sensor: if.s Alarm r.alarm Actuator: if.a Door r.door Sensor: if.s Door lock r.door.lock Actuator: if.a Elevator control r.elevator.control Actuator: if.a Light source r.light.source Actuator: if.a Location r.location Sensor: if.s Mode r.mode Actuator: if.a Motion detector r.motion.detector Sensor: if.s Operational state r.operational.state Actuator: if.a Smoke detector r.smoke.detector Sensor: if.s Surveillance camera r.surveillance.camera Actuator: if.a Actuator: if.a Temperature r.temperature Sensor: if.s Actuator: if.a Thermostat r.thermostat Sensor: if.s Time interval r.time.interval Actuator: if.a Ventilation r.ventilation Actuator: if.a Links list: if.ll Floor light collection r.floor.light.coll Batch: if.b Links list: if.ll Room light collection r.room.light.coll Batch: if.b Links list: if.ll Alarm collection r.alarm.coll Batch: if.b Links list: if.ll Smoke detector collection r.smoke.detector.coll Batch: if.b Links list: if.ll Door lock collection r.door.lock.coll Batch: if.b Links list: if.ll ESS control r.ess.control Batch: if.b Links list: if.ll BLS control r.bls.control Batch: if.b Links list: if.ll EES control r.ees.control Batch: if.b Links list: if.ll HVAC control r.hvac.control Batch: if.b

All resources are required to implement the baseline interface, allowing read and write operations on resource property values.

VII Appendix A. Resource Type Definitions of Building Management System

VIII Modification of Server Application Source Code in Key Scenarios 8 to 10

Listing B.1 : Simple server version 1

#include #include #include "ocstack.h" #include "ocpayload.h" #include "logger.h"

#define TAG "ocserver"

int gQuitFlag =0; /* SIGINT handler */ void handleSigInt( int signum) { if ( signum == SIGINT) { gQuitFlag =1; } }

int main() { //Init server OIC_LOG(DEBUG, TAG, "OCServer is starting..."); if ( OCInit(NULL,0,OC_SERVER)!=OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack init error"); return 0; }

//Add resources here

IX Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

// Main loop: Break from loop with Ctrl-C OIC_LOG(INFO, TAG, "Entering ocserver main loop..."); signal( SIGINT , handleSigInt); while (!gQuitFlag) { if ( OCProcess() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); return 0; } sleep(2); }

OIC_LOG(INFO, TAG, "Exiting ocserver main loop..."); if ( OCStop() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); }

return 0; }

Listing B.2 : Simple server version 2 - Adding a resource

#include #include #include "ocstack.h" #include "ocpayload.h" #include "logger.h"

#define TAG "ocserver"

typedef struct AlarmResource{ char * uri; bool sound; char location[51]; OCResourceHandle handle; } AlarmResource;

int gQuitFlag =0; /* SIGINT handler */ void handleSigInt( int signum) { if ( signum == SIGINT) { gQuitFlag =1; } }

//Handler to process alarm resource requests OCEntityHandlerResult handleOCEntity( OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest , void* callbackParam){

OCEntityHandlerResult ehResult = OC_EH_OK;

X Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

AlarmResource* alarm =(AlarmResource*) callbackParam; OCRepPayload* input = reinterpret_cast < OCRepPayload*> ( ehRequest ->payload);

if( ehRequest && (flag == OC_REQUEST_FLAG)) { //Create resource representation OCRepPayload* payload = OCRepPayloadCreate();

if( OC_REST_POST == ehRequest ->method) { bool b; char* str; if( OCRepPayloadGetPropBool(input, "sound ",&b)){ alarm->sound = b;} if( OCRepPayloadGetPropString(input, " location",&str)){ strncpy(alarm->location , str, 50); } } if((OC_REST_GET == ehRequest ->method)|| ( OC_REST_POST == ehRequest ->method )) { OCRepPayloadSetUri( payload , alarm->uri); OCRepPayloadSetPropBool( payload , "sound" , alarm->sound); OCRepPayloadSetPropString( payload , " location", alarm->location); }

//Prepare response OCEntityHandlerResponse response; response. ehResult = ehResult; response. payload = reinterpret_cast < OCPayload*>( payload); response. numSendVendorSpecificHeaderOptions =0; memset( response. sendVendorSpecificHeaderOptions , 0, sizeof response. sendVendorSpecificHeaderOptions); memset( response. resourceUri ,0,sizeof response. resourceUri); response. persistentBufferFlag =0; response. requestHandle = ehRequest -> requestHandle; response. resourceHandle = ehRequest ->resource;

//Send response if ( OC_STACK_OK != OCDoResponse(&response)) { ehResult = OC_EH_ERROR; } OCRepPayloadDestroy( payload); } return ehResult; }

XI Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

int main() { //Init server OIC_LOG(DEBUG, TAG, "OCServer is starting..."); if ( OCInit(NULL,0,OC_SERVER)!=OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack init error"); return 0; }

AlarmResource* alarm = new AlarmResource; alarm->uri =(char*)"/AlarmResURI/0"; alarm->sound = false;

// Register resource in OCstack OCCreateResource(&alarm->handle , "r.alarm", "oic.if. baseline", alarm->uri, handleOCEntity , ( void*)alarm, OC_DISCOVERABLE);

//Bind interface to resource OCBindResourceInterfaceToResource(alarm->handle , "oic.if .a");

// Main loop: Break from loop with Ctrl-C OIC_LOG(INFO, TAG, "Entering ocserver main loop..."); signal( SIGINT , handleSigInt); while (!gQuitFlag) { if ( OCProcess() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); return 0; } sleep(2); }

OIC_LOG(INFO, TAG, "Exiting ocserver main loop..."); if ( OCStop() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); }

return 0; }

Listing B.3 : Simple server version 3 - Increasing the number of resources

#include #include #include "ocstack.h" #include "ocpayload.h" #include "logger.h"

XII Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

#define TAG "ocserver"

typedef struct AlarmResource{ char * uri; bool sound; char location[51]; OCResourceHandle handle; } AlarmResource;

int gQuitFlag =0; /* SIGINT handler */ void handleSigInt( int signum) { if ( signum == SIGINT) { gQuitFlag =1; } }

//Handler to process alarm resource requests OCEntityHandlerResult handleOCEntity( OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest , void* callbackParam){

OCEntityHandlerResult ehResult = OC_EH_OK; AlarmResource* alarm =(AlarmResource*) callbackParam; OCRepPayload* input = reinterpret_cast < OCRepPayload*>( ehRequest ->payload);

if( ehRequest && (flag == OC_REQUEST_FLAG)) { //Create resource representation OCRepPayload* payload = OCRepPayloadCreate();

if( OC_REST_POST == ehRequest ->method) { bool b; char* str; if( OCRepPayloadGetPropBool(input, "sound ",&b)){ alarm->sound = b;} if( OCRepPayloadGetPropString(input, " location",&str)){ strncpy(alarm->location , str, 50); } } if((OC_REST_GET == ehRequest ->method)||( OC_REST_POST == ehRequest ->method )) { OCRepPayloadSetUri( payload , alarm->uri); OCRepPayloadSetPropBool( payload , "sound" , alarm->sound); OCRepPayloadSetPropString( payload , " location", alarm->location); }

XIII Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

//Prepare response OCEntityHandlerResponse response; response. ehResult = ehResult; response. payload = reinterpret_cast < OCPayload*>( payload); response. numSendVendorSpecificHeaderOptions =0; memset( response. sendVendorSpecificHeaderOptions , 0, sizeof response. sendVendorSpecificHeaderOptions); memset( response. resourceUri ,0,sizeof response. resourceUri); response. persistentBufferFlag =0; response. requestHandle = ehRequest -> requestHandle; response. resourceHandle = ehRequest ->resource;

//Send response if ( OC_STACK_OK != OCDoResponse(&response)) { ehResult = OC_EH_ERROR; } OCRepPayloadDestroy( payload); } return ehResult; }

int main() { //Init server OIC_LOG(DEBUG, TAG, "OCServer is starting..."); if ( OCInit(NULL,0,OC_SERVER)!=OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack init error"); return 0; }

//Define all alarm resource URIs AlarmResource* alarm[15]; const char* uri[] = { "/AlarmResURI/0", "/AlarmResURI/1", "/AlarmResURI/2", "/AlarmResURI/3", "/AlarmResURI/4", "/AlarmResURI/5", "/AlarmResURI/6", "/AlarmResURI/7", "/AlarmResURI/8", "/AlarmResURI/9", "/AlarmResURI/10", "/AlarmResURI/11", "/AlarmResURI/12", "/AlarmResURI/13", "/AlarmResURI/14" };

for( unsigned int i =0;i < 15; i ++){

alarm[i]=new AlarmResource; alarm[i]->uri =(char*)uri[i]; alarm[i]->sound = false;

// Register resource in OCstack OCCreateResource(&alarm[i]->handle , "r.alarm", "

XIV Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

oic.if.baseline", alarm[i]->uri, handleOCEntity , ( void*)alarm[i], OC_DISCOVERABLE); //Bind interface to resource OCBindResourceInterfaceToResource( alarm[i]-> handle , "oic.if.a"); }

// Main loop: Break from loop with Ctrl-C OIC_LOG(INFO, TAG, "Entering ocserver main loop..."); signal( SIGINT , handleSigInt); while (!gQuitFlag) { if ( OCProcess() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); return 0; } sleep(2); }

OIC_LOG(INFO, TAG, "Exiting ocserver main loop..."); if ( OCStop() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); }

return 0; }

Listing B.4 : Simple server version 4 - Adding a collection resource

#include #include #include "ocstack.h" #include "ocpayload.h" #include "logger.h"

#define TAG "ocserver"

typedef struct AlarmResource{ char * uri; bool sound; char location[51]; OCResourceHandle handle; } AlarmResource;

int gQuitFlag =0; /* SIGINT handler */ void handleSigInt( int signum) { if ( signum == SIGINT) { gQuitFlag =1;

XV Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

} }

//Handler to process alarm resource requests OCEntityHandlerResult handleOCEntity( OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest , void* callbackParam){

OCEntityHandlerResult ehResult = OC_EH_OK; AlarmResource* alarm =(AlarmResource*) callbackParam; OCRepPayload* input = reinterpret_cast < OCRepPayload*>( ehRequest ->payload);

if( ehRequest && (flag == OC_REQUEST_FLAG)) { //Create resource representation OCRepPayload* payload = OCRepPayloadCreate();

if( OC_REST_POST == ehRequest ->method) { bool b; char* str; if( OCRepPayloadGetPropBool(input, "sound ",&b)){ alarm->sound = b;} if( OCRepPayloadGetPropString(input, " location",&str)){ strncpy(alarm->location , str, 50); } } if((OC_REST_GET == ehRequest ->method)||( OC_REST_POST == ehRequest ->method )) { OCRepPayloadSetUri( payload , alarm->uri); OCRepPayloadSetPropBool( payload , "sound" , alarm->sound); OCRepPayloadSetPropString( payload , " location", alarm->location); }

//Prepare response OCEntityHandlerResponse response; response. ehResult = ehResult; response. payload = reinterpret_cast < OCPayload*>( payload); response. numSendVendorSpecificHeaderOptions =0; memset( response. sendVendorSpecificHeaderOptions , 0, sizeof response. sendVendorSpecificHeaderOptions); memset( response. resourceUri ,0,sizeof response. resourceUri); response. persistentBufferFlag =0; response. requestHandle = ehRequest -> requestHandle; response. resourceHandle = ehRequest ->resource;

//Send response

XVI Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

if ( OC_STACK_OK != OCDoResponse(&response)) { ehResult = OC_EH_ERROR; } OCRepPayloadDestroy( payload); } return ehResult; }

int main() { //Init server OIC_LOG(DEBUG, TAG, "OCServer is starting..."); if ( OCInit(NULL,0,OC_SERVER)!=OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack init error"); return 0; }

//Define all alarm resource URIs AlarmResource* alarm[15]; const char* uri[] = { "/AlarmResURI/0", "/AlarmResURI/1", "/AlarmResURI/2", "/AlarmResURI/3", "/AlarmResURI/4", "/AlarmResURI/5", "/AlarmResURI/6", "/AlarmResURI/7", "/AlarmResURI/8", "/AlarmResURI/9", "/AlarmResURI/10", "/AlarmResURI/11", "/AlarmResURI/12", "/AlarmResURI/13", "/AlarmResURI/14" };

for( unsigned int i =0;i < 15; i ++){

alarm[i]=new AlarmResource; alarm[i]->uri =(char*)uri[i]; alarm[i]->sound = false;

// Register resource in OCstack OCCreateResource(&alarm[i]->handle , "r.alarm", " oic.if.baseline", alarm[i]->uri, handleOCEntity , ( void*)alarm[i], OC_DISCOVERABLE); //Bind interface to resource OCBindResourceInterfaceToResource( alarm[i]-> handle , "oic.if.a"); }

//Register collection resource in OCStack OCResourceHandle collHandle = NULL; OCCreateResource(&(collHandle), "r.alarm.coll", "oic.if.baseline", "/AlarmCollResURI", NULL, NULL, ( OC_DISCOVERABLE | OC_OBSERVABLE));

XVII Appendix B. Modification of Server Application Source Code in Key Scenarios 8 to 10

//Bind interfaces to collection resource OCBindResourceInterfaceToResource( collHandle , "oic.if.b" ); OCBindResourceInterfaceToResource( collHandle , "oic.if.ll ");

//Bind alarm resources to collection resource for( unsigned i =0;i <15;i ++){ OCBindResource( collHandle , alarm[i]->handle); }

// Main loop: Break from loop with Ctrl-C OIC_LOG(INFO, TAG, "Entering ocserver main loop..."); signal( SIGINT , handleSigInt); while (!gQuitFlag) { if ( OCProcess() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); return 0; } sleep(2); }

OIC_LOG(INFO, TAG, "Exiting ocserver main loop..."); if ( OCStop() != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "OCStack process error"); }

return 0; }

XVIII TRITA-ICT-EX-2017:24

www.kth.se