WSAN COVERAGE EXTENSION OVER IP IN A HOME AUTOMATION SERVICE BASED ON Z-WAVE

Alfonso Millán Omil

Master’s Thesis presented to the Telecommunications Engineering School Master’s Degree in Telecommunications Engineering

Supervisors Felipe Gil Castiñeira Jesús Manuel García Gude

2017

I would like to dedicate this thesis to all my family and friends for supporting me throughout writing it and in my life in general. iv Abstract

Wireless Sensor and Actuator Networks (WSANs) usually have external access gateways to allow the control and the monitoring from Cloud Computing platforms, where the high level management of the data is performed. However, usually the Internet latency is a non assumable bottleneck and it is necessary to follow the paradigm, and perform part of the data processing at the edge of the network. This research pursues the creation of an architecture to capture information from sensors, process it at the edge (in a gateway controlled by the operator), send the relevant results to the cloud infrastructure, and send instructions to the actuators if necessary. It was performed in a complex LAN environment, so it was necessary to design a hierarchical infrastructure to be able to connect all the sensors and actuators to the master gateway that is directly connected to the cloud infrastructure. In this architecture it is possible to include several slave gateways that are connected to the principal gateway through Ethernet. Since this work was done in the network operator company, R Cable, it is intended to be an immediate practical application. Despite this, the development keep having academic value. This document is distributed into five sections, excluding the appendixes:

• Introduction to the project including the development context, the motivation of the research, the scope of the investigation and a plan of the tests performed.

• Analysis of the state of the art in IoT.

• Description of the smart home platform of RCable.

• Methodology and performed tests.

• Conclusions and future lines of the project. Table of contents

List of figures xi

List of tables xiv

Nomenclature xv

1 Introduction2 1.1 Context ...... 3 1.2 Motivation ...... 4 1.3 Scope ...... 5

2 State of the art 10 2.1 The IoT architecture ...... 11 2.1.1 Edge Computing ...... 11 2.1.2 ...... 11 2.2 The smart sensor and actuators ...... 12 2.2.1 IEEE 1451 standard family ...... 14 2.2.1.1 IEEE 1451.0 ...... 16 2.2.1.2 IEEE 1451.1 ...... 16 2.2.1.3 IEEE 1451.5 ...... 18 2.2.2 WSAN designs ...... 18 2.2.2.1 IEEE 802.15.4 ...... 19 Table of contents vii

2.2.2.2 Z-Wave ...... 20 2.2.2.3 Security in WSANs ...... 22 2.2.3 WSAN protocols in Smart Home ...... 22 2.3 Platform architectures ...... 23 2.3.1 Software platforms ...... 23 2.3.1.1 Operating systems for IoT ...... 24 2.3.1.2 Linux based operating systems ...... 24 2.3.1.3 Non-Linux based operating systems ...... 25 2.3.2 IoT protocols ...... 26 2.3.2.1 Infrastructure protocols ...... 26 2.3.2.2 Data protocols ...... 26 2.3.2.3 Framework architectures ...... 27 2.4 IoT cloud providers ...... 30 2.4.1 Amazon ...... 30 2.4.2 Microsoft ...... 31 2.4.3 Google ...... 31

3 The 3ollosR service 33 3.1 Sensorization ...... 36 3.1.1 End devices ...... 36 3.1.1.1 Z-Wave WSAN ...... 36 3.1.1.2 IP video cameras ...... 37 3.1.2 Master-GW hardware ...... 38 3.1.2.1 Embedded computer boards ...... 38 3.1.2.2 MMC flash memory architecture ...... 40 3.1.2.3 The enclosure ...... 41 3.1.3 Master-GW software ...... 42 3.1.3.1 Z-Wave WSAN management ...... 43 viii Table of contents

3.1.3.2 Video service ...... 45 3.1.3.3 Localnet ...... 46 3.2 Back-end ...... 47 3.2.1 External Resource Server ...... 48 3.2.2 Erlang MQTT Broker ...... 49 3.2.3 Big data storage ...... 51 3.2.4 Inventory and provision ...... 51 3.2.5 Rules ...... 52 3.2.6 Control R Management System ...... 53 3.3 User interface ...... 53

4 Development of the WSAN Bridge 56 4.1 Description of the development tools ...... 57 4.1.1 UZB ...... 58 4.1.2 ZIPR ...... 59 4.1.3 C.H.I.P...... 60 4.1.4 HP J2611B 10Base-T Hub-16U ...... 61 4.2 Z/IP Gateway management ...... 62 4.2.1 Z-Ware ...... 64 4.2.2 Z/IP Gateway over the ZIPR ...... 65 4.2.2.1 The ZIPR firmware ...... 65 4.2.2.2 Controlling the ZIPR ...... 66 4.2.3 Z/IP Gateway in a Linux machine ...... 68 4.2.4 Managing Z/IP Gateway ...... 68 4.3 Generic LAN bridge implementation ...... 69 4.3.1 Ser2net and Socat ...... 70 4.3.2 Encrypting the data stream ...... 71 4.3.3 Final prototype ...... 73 Table of contents ix

4.3.3.1 Recognizing the Z-Wave dongle ...... 73 4.3.3.2 Auto-connection script ...... 74 4.3.3.3 Disconnection script ...... 75

5 Conclusions 76 5.1 Future work ...... 77 5.1.1 Better integration of the Slave-GW in the 3ollosR environment . . . 77 5.1.2 Evolution of the Slave-GW ...... 78 5.1.2.1 Minimalistic design ...... 78 5.1.2.2 Fog Computing interpretation ...... 78

References 79

Appendix A Z-Ware Web Server 83 A.1 Compiling Z-Ware Web Server ...... 83 A.2 Installing Z-Ware Web Server: ...... 84 A.3 Starting the service: ...... 84 A.4 Controlling Z-Ware Web Server: ...... 84

Appendix B Z/IP Gateway 88 B.1 Compiling and installing Z/IP Gateway: ...... 88 B.2 Configuring Z/IP Gateway: ...... 90 B.2.1 Z/IP Gateway configuration file ...... 90 B.3 Running DTLS between Z/IP Gateway and Z-Ware ...... 92

Appendix C Implementation of the master-slave WSAN bridge architecture 94 C.1 Socat and Ser2net ...... 94 C.1.1 Slave-GW ...... 94 C.1.2 Master-GW ...... 95 C.2 Final prototype ...... 96 x Table of contents

C.2.1 Generation of the certificates ...... 96 C.2.1.1 Slave-GW ...... 96 C.2.1.2 Master-GW ...... 97 C.2.2 Udev rules ...... 97 C.2.3 The auto-tunnel establishment ...... 98 C.2.3.1 Slave-GW ...... 98 C.2.3.2 Master-GW ...... 101 List of figures

1.1 The basic Smart Home user scenario ...... 3 1.2 Proposed scenario ...... 4 1.3 Design of the stack of protocols ...... 8

2.1 OpenFog multi-tier deployment ...... 12 2.2 Basic architecture of a smart transducer ...... 13 2.3 IEEE 1451 block diagram of the NCAP and TIM interfaces ...... 15 2.4 IEEE 1451 Family of Standards and Interfaces ...... 15 2.5 The NCAP standardized implementation ...... 17 2.6 Timeslot diagram ...... 19 2.7 Transmission schedule ...... 20 2.8 PPDU data structure ...... 21 2.9 AllJoyn software stack in a device ...... 28 2.10 Overview of the Thread stack ...... 29

3.1 3ollosR basic scenario ...... 33 3.2 Authentication process ...... 34 3.3 Stack conversion in 3ollosR, from an end-point to the back-end ...... 34 3.4 The 3ollosR structure ...... 35 3.5 The 3ollosR certified WSAN nodes ...... 36 3.6 IP video cameras in 3ollosR ...... 37 xii List of figures

3.7 Single-board computers ...... 39 3.8 Cubieboard2 component view (left) and A20 block diagram (right) . . . . . 40 3.9 MMC system architecture ...... 41 3.10 Master-GW enclosure ...... 41 3.11 Block diagram of the Master-GW software ...... 43 3.12 Aeon Labs Z-Stick Gen5 ...... 43 3.13 MQTT diagram. Publishers at left. Subscribers at right ...... 50 3.14 EMQ web dashboard ...... 50 3.15 Front view of the user interface ...... 54 3.16 Configuration rules on the user interface ...... 54

4.1 Z-Wave devices in Embedded Development Kit ...... 57 4.2 UZB hardware description ...... 58 4.3 ZIPR hardware description ...... 59 4.4 C.H.I.P. board ...... 60 4.5 HP J2611B 10Base-T Hub-16U (front view) ...... 61 4.6 Scheme for LAN auditions ...... 62 4.7 Z-Wave control via Z/IP Gateway ...... 63 4.8 Forwarding mechanism of Z/IP Gateway ...... 63 4.9 Z-Ware layer model design ...... 64 4.10 ZIPR firmware design ...... 66 4.11 UDP packets captured from a communication between Z-Ware and the ZIPR 66 4.12 Format of an UDP datagram captured between Z-Ware and a ZIPR . . . . 67 4.13 ZIPR trying to establish a TLS/TCP session ...... 67 4.14 DTLS handshake between Z-Ware and Z/IP Gateway ...... 68 4.15 Format of a DTLS packet captured between Z-Ware and a ZIPR ...... 69 4.16 Remote serial implementation with Ser2net ...... 71 4.17 Remote serial implementation with encryption ...... 72 List of figures xiii

4.18 TLS handshake between the Master-GW and the Slave-GW ...... 72

A.1 Sign in Z-Ware local website ...... 85 A.2 Version of the Z-Ware Web Server ...... 85 A.3 Z/IP Gateway on LAN detected by Z-Ware Web Server ...... 86 A.4 Activate node inclusion mode on Z/IP Gateway ...... 86 A.5 Added node detected in the Z-Ware Web Server ...... 87

B.1 Z-Ware Web Client DTLS PSK introduction ...... 92 B.2 Z/IP Gateway DTLS PSK on configuration file ...... 93

C.1 Changing the serial port in OpenZWave ...... 95 List of tables

2.1 IEEE 1451 communication target technology between NCAP and TIM . . . 16 2.2 Comparison of WSAN protocols used in Smart Home ...... 23

3.1 Hardware comparison of the single-board computers ...... 39

4.1 Comparison of the 3ollosR boards and C.H.I.P...... 60

5.1 Some of the current libraries with DTLS support ...... 78 Nomenclature

Acronyms / Abbreviations

6LoWPAN IPv6 over Low power Wireless Personal Area Networks

ACK Acknowledgment

ACM Abstract Control Model

ADSL Asymmetric Digital Subscriber Line

AES Advanced Encryption Standard

AJAX Asynchronous JavaScript And XML

AP Access Point

API Application Programming Interface

ARM Advanced RISC Machine

ARP Address Resolution Protocol

ARQ Automatic Repeat-Request

ASIC Application-Specific

ASK Amplitude Shift Key

AWS Amazon Web Services

BLE Bluetooth Low Energy

BSP Board Support Package

CAN Controller Area Network xvi Nomenclature

CCD Charge-Coupled Device

CDC Communications Device Class

CE Consumer Electronics

CMOS Complementary Metal Oxide Semiconductor

CoAP Constrained Application Protocol

CoRE Constrained RESTful Environment

CPE Costumer-Premises Equipment

CPU Central Processing Unit

CRC Cyclic Redundancy Check

CRMS Control R Management System

DDR Double Data Rate

ECC Error Correction Code

ECDH Elliptic Curve Diffie Hellman

EEPROM Electrically Erasable Programmable Read-Only Memory eMMC embedded Multi-Media Controller

EMQ Erlang MQTT Broker

ERS External Resource Server

FEC Forward Error Correction

FPGA Field Programmable Gate Array

FQDN Full Qualified Domain Name

GPIO General Purpose Input and Output

GPU

GW Gateway

HAN Home Area Network Nomenclature xvii

HDMI High Definition Multimedia Interface

HS-MMC High Speed Multi-Media Controller

HTML HyperText Markup Language

HTTP(S) HyperText Transfer Protocol (Secure)

I2C Inter-Integrated Circuit

IANA Internet Assigned Numbers Authority

IC Integrated Circuit

ICMP Internet Control Message Protocol

IEEE Institute of Electrical and Electronics Engineers

IETF Internet Engineering Task Force

IFTTT If This Then That

IoT Internet of Things

IP Internet Protocol

IR Infra Red

ISM Industrial, Scientific and Medical

ITU International Telecommunication Union

JNI Java Native Interface

JSON JavaScript Object Notation

JVM Java Virtual Machine

LAN Local Area Network

LDAP Lightweight Directory Access Protocol

LDO Low Dropout

LED Light Emitting Diode

LLN Low Power Lossy Network xviii Nomenclature

LPWAN Low-Power Wide-Area Network

LR-WPAN Low-Rate Wireless Personal Area Network

LTE Long Term Evolution

LVDS Low-Voltage Differential Signaling

MCU Microcontroller Unit

MII Media-Independent Interface

MIPS Microprocessor without Interlocked Pipeline Stages

MLC Multi-Level Cell

MMC Multi-Media Controller

MPDU MAC Protocol Data Unit

MQTT-SN Message Queue Telemetry Transport for Sensor Networks

MQTT Message Queue Telemetry Transport

MVNO Mobile Virtual Network Operator

NAT Network Address Translation

NB-IoT Narrow Band IoT

NCAP Network Capable Application Processor

NIST National Institute of Standards and Technology

NMAP Network Mapper

NVRAM Non-Volatile Random Access Memory

OPSK Orthogonal Phase Key Shifting

OS

OTG On The Go

OUI Organizationally Unique Identifier

PCB Printed Circuit Board Nomenclature xix

PKI Public Key Infrastructure

PLC Power Line Communications

PSK Pre-Shared Key

QUIC Quick UDP Internet Connections

RAM Random Access Memory

REST Representational State Transfer

RFC Request For Comments

RFID Radio Frequency Identification

RFP Request For Proposal

RF Radio Frequency

RISC Reduced Instruction Set Computer

ROM Read-Only Memory

RPL IPv6 Routing Protocol for Low-Power and Lossy Networks

RTC Real Time Clock

RTOS Real Time Operating System

RTSP Real Time Streaming Protocol

SAR Segmentation and Reassembly

SATA Serial Advanced Technology Attachment

SAW Surface Acoustic Wave

SDK Software Development Kit

SD Secure Digital

SFD Start Frame Delimiter

SLC Single-Level Cell

SNMP Simple Network Management Protocol xx Nomenclature

SOAP Simple Object Access Protocol

SoC

SPI Serial Peripheral Interfazce

SQL Structured Query Language

SSL Secure Sockets Layer

TCP Transport Control Protocol

TEDS Transducer Electronic Data Sheet

TII Transducer Independent Interface

TIM Transducer Interface Module

TLS Transport Layer Security

TSCH Time Synchronized Channel Hopping

TTL Transistor-Transistor Logic

UART Universal Asynchronous Receiver-Transmitter

UI User Interface

ULE Ultra Low Energy

URL Uniform Resource Locator

USB Universal Serial Bus

VCP Virtual COM Port

VGA Video Graphics Array

VLSI Very Large Scale Integration

WAN Wide Area Network

WLAN Wireless Local Area Network

WSAN Wireless Sensor and Actuator Network

WTIM Wireless Transducer Interface Module Nomenclature xxi

XMPP Extensible Messaging and Presence Protocol

Z/IP Z-Wave over IP

ZIPR Z-Wave over IP Router Nomenclature 1 Chapter 1

Introduction

R Cable has recently launched their smart home service, known as 3ollosR. Its development started in 2013 as a technological surveillance project to track the IoT paradigm progress. R Cable was born as a cable company in the 1998, after won a public tender to deploy a hybrid fiber-coaxial network throughout the Galician territory. This network was exploited giving Internet access, television and fixed telephony. Since the telecommunications market is continuously evolving, the mission of the network operators is to track exhaustively the emerging technologies and to study how to integrate them as new potential services. After the adoption of the Mobile Internet, the next big expectation is the Internet of Things (IoT) paradigm. The 3ollosR provides remote security to their users who can survey and control their homes when they are outside. The future lines of are intended to support new services including different intelligent services as energy conservation or automated comfort, but the increasing demand is oriented to self care for the elderly and the disabled persons. The service is build with Z-Wave wireless sensors and actuators that are connected through a gateway to a cloud service. The users access transparently to this cloud service through their mobile devices using an application or a web browser. They needed to expand the capability of the service allowing the gateway to reach a larger number of sensors and actuators through a LAN. This project analyses the architecture of the service, the state of the art and the possible approaches to provide a practical solution. 1.1 Context 3

1.1 Context

Usually in the smart home services, the users connect to a Cloud Computing platform interfacing an Edge Computing gateway from each house, which perform the communication with the end physical devices. This generic flow is presented in the Figure 1.1.

Fig. 1.1 The basic Smart Home user scenario

The main advantage of having an edge gateway is that all configurations are done ona single device. In addition, mechanisms for ensuring Internet security and reliability are then necessary only on that device. The smart home services also usually take advantage of the protocols that allow smart physical devices to communicate with each other. Examples in this area are ZigBee and Z-Wave. These are different wireless networks of smart sensors technologies and although the idea is similar, they differ in the frequency they use, range of transmission and data rate. The edge gateways integrate easily the control of a WSAN using a specific dongle, which is an attached piece of hardware that provides connectivity into this networks. Then, the gateway is converted into a WSAN master node with capabilities to control and monitor all available devices in that range. The worst disadvantage of the WSAN technologies is its radio range distance is low, so it is very difficult to achieve full coverage in some scenarios. 4 Introduction

1.2 Motivation

The edge gateways are constantly improving their intelligent utilities through high level software stacks running on embedded hardware. However, the WSAN coverage range is an annoying bottleneck in many applications. Examples of limited services appear in hotels, office buildings, homes for the elderly or universities. This project is geared to expand the WSAN application range of an Edge Gateway, taking advantage of the wired Local Area Network (LAN). This involves the design of a bridge system between a LAN and a WSAN. The problem is to find out a reliable protocol stack as light as possible. The Figure 1.2 reflects the objective underlying into this project.

Fig. 1.2 Proposed scenario

From now on, the used nomenclature to refer to the Edge Computing Gateway and to the Bridge Gateway will be Master-GW and Slave-GW respectively. The Slave-GW role is directed to be the minimal hardware/software implementation, per- forming only the LAN to WSAN bridge requirements, since all of the intelligent management will be done in the Master-GW. This can be summarized in the next features:

• Bridge: interface between an Ethernet port and the WSAN.

• Security: handle cipher mechanism to protect the transmission through the LAN against malicious hosts. 1.3 Scope 5

The Master-GW must use the LAN interconnection to reach the different Slave-GWs and orchestrate its WSAN nodes by high level control software. Regarding the LAN expansion, the Master-GW must implement the next features:

• Discovery: recognizes the Slave-GWs host in the LAN and establishes a connection with them.

• Data transmission: send and receive ciphered data to different remote WSANs over the Ethernet port.

• Device management: supports configuration, provisioning and diagnostics, both Slave-GWs and associated nodes.

It is really important to keep in mind that this project has been done in a business environment, with a complete Smart Home service already established. This implies that the final solution must be marketable and compatible with it. Due to this fact, there are development constraints limiting the design of a specific bridge system. One of them was the implementation of the Slave-GW on a Linux operating system embedded on an ARM-processor board, whose resources are oversized for this purpose. The main reason was to avoid a monetary investment on specific hardware to perform the Slave-GW role, as long as using a Linux embedded hardware allow an easier re-use in other future purposes. Therefore, this thesis is more a proof of concept than a system design.

1.3 Scope

An smart home architecture is complex and involves several different technologies. In this section we provide the context to facilitate understanding this Master’s Thesis contributions. One of the main objectives is the creation of a solution that makes it possible to extend the 3ollosR scope in a complex LAN environment, so it will be necessary to work with devices that are able to provide the connectivity and execute some logic to bridge the LAN and WSAN domains. The first stage of the project was a deep documentation in the development of IoT gateways and its environment. The IEEE 1451.1 standard attempts to normalize the gateway design in sensor and actuator networks. 6 Introduction

This standard defines the Network Capable Application Processor (NCAP), a gateway that provides communication between different smart sensors and the user network or a host processor [1]. However, this standard is currently under revision and it is not concluded yet. Currently, there are many different hardware/software interpretations of the NCAP figure. Two representative IEEE articles are [2] and [3]:

• The first one uses an Intel Edison4 [ ] board which is a small board powered by an Intel processor, benefits from 1 GB RAM and 4 GB EMMC storage, integrates Wi-Fi and Bluetooth and supports I2C, SPI and GPIO signals. In this experiment, the embedded operating system running on the Edison board is Brillo, a Google development recently updated to Android Things [5]). This OS integrates core services, system Hardware Abstraction Layers (HALs) and Weave, a secured protocol used for connecting the board with mobile devices [6].

• The second one is more experimental, it is based on the DE2 kit from Altera to access smart sensors through wireless and wired interfaces [7]. This kit includes a Nios II processor running an uClinux OS and a Cyclone II 2C35 FPGA [8][9][10]. This put into practice different IEEE 1451 standards using hardware description languages and programmable logic technology and allowing the design of systems with all the capacities and flexibilities of embedded processors and customized functions.

The previous examples consist of centralized gateway approaches, which implementation is intended to handle different type of devices as ZigBee nodes or the Nest Thermostat. This purpose completely different. In fact, it is more focused on the high-level software running on the Master-GW and the WSAN implementation. Most of the current NCAPs interpretations based on WSAN management use a dongle to perform the PHY lowest layer of the WSAN. The rest of the WSAN stack of protocols is implemented by a driver installed in the software, performing the application frame format, the ACK retransmission logic and the node addressing. This kind of drivers usually implements an object-based database in charge of keeping persistent data about the provision of the end-points in the WSAN. This also helps to map the WSAN application protocol with generic actions, abstracting from the end-point technology. The architecture proposed in this Master’s Thesis consisted of a master-slave gateway topology where the Master-GW executes all the logic of the WSAN, sending and receive the WSAN frames (MPDUs) encapsulated as the payload of IP packets. 1.3 Scope 7

Meanwhile, the Slave-GW is only limited to de-encapsulate these IP packets and transparently disseminate them over the WSAN, and also to perform the inverse path i.e.to infer the WSAN frames in IP packets and forward them to the Master-GW. The simplest approach of a Slave-GW role is a device with a connected dongle that creates a tunnel allowing Master-GW to use the dongle as it was directly connected to it. This can be achieved using a tunnel over the LAN through an IP based stack, as it shown in Figure 1.3. This approach allows to reduce the computing consumption in the Master-GW. The rest of requirements of the Slave-GW design are established by the stack of protocols used. The transport layer provides end-to-end reliability over IP based networks. The best-known transport protocol is the Transmission Control Protocol (TCP). It is used for connection-oriented transmissions, whereas the connectionless User Datagram Protocol (UDP) is used for simpler messaging transmissions. TCP provides traffic control and congestion control through Automatic Repeat-Request (ARQ) techniques. Due to the expensive energy requirements imposed by the TCP end-to- end reliability, UDP and retransmission control mechanisms at application layer allow a good trade-off between energy cost and reliability [11]. As LANs are not supposed to be constrained networks, it seems UDP will prevail against TCP, due to the computing consumption resources required by TCP. It is also necessary to introduce a security layer since LANs can be hostile. To protect the architecture against malicious hosts in the LAN, the most desirable way to secure client/server applications is to use Transport Layer Security (TLS)[12]. However, TLS is only compatible with the TCP/IP stack. Since the use of UDP automatically prohibits use of TLS, the only option is to use DTLS protocol [13]. It is an UDP adaption of the TLS protocol, providing equivalent security guarantees. The Slave-GW to Master-GW protocol stack will look like Figure 1.3. As it can be deduced from the Figure 1.3, this mechanism allows the coexistence of different WSAN technologies such as Zigbee and Z-Wave, as long as the correspondent WSAN driver is executed by the Master-GW. The design of this architecture was done considering some proofs made with the Z-Wave over IP proprietary software stack from Sigma Designs (the company that owns and licenses the Z-Wave standard). The original idea was to integrate a specific device which implements that software and represents the Z-Wave nodes as IPv6 hosts in a LAN forwarding IP packets to the Z-Wave protocol. 8 Introduction

Fig. 1.3 Design of the stack of protocols

This solution was rejected by R Cable’s since it requires a monetary investment to purchase the license to use that software, and also, that it is restricted to the Z-Wave technology which would provoke a strong dependence of using it. This is the main reason why it was decided to use a master-slave gateway architecture. A proof of concept was implemented based on the use of some Linux high-level software tools, included in a complete ad hoc way in the current 3ollosR architecture. This proof consisted of the establishment of a tunnel allowing direct access to the Slave-GW serial port where the WSAN dongle is connected. The implementation was done using a TLS/TCP secure socket intended to provide direct access to the Slave-GW dongle. Then, Master-GW connects to this socket, tunneling all the WSAN raw data through it. Therefore, the Master-GW will support both physical and remote dongles This approach allows to integrate this proof of concept in the 3ollosR environment simply replacing the serial port, currently used by the 3ollosR Z-Wave driver, by this implemented socket. In fact, the socket designed was associated to a virtual serial port to minimize the impact in the current established software. It should be mentioned, the initial objective was to design a stack of protocols as the presented on the Figure 1.3, for simplicity and since the final implementation of the Slave-GW was performed over a machine with enough computing resources, the final stack was based on TLS/TCP. 1.3 Scope 9 Chapter 2

State of the art

As this project is a part of the IoT technology field, where a physical object is capable of being identified and integrated into communication networks, this chapter describes howa physical measure read from a sensor reaches a back-end. Nowadays the IoT market is not well-established yet. In fact, although some solutions have begun to converge, there is a strong competition to achieve the monopoly in each of the IoT layers. The following types of companies are distinguished:

• Device manufacturers: design sensors and actuators with complementary electronics to make them compatible with network protocols. They use one of the available solutions as Zigbee, EnOcean, Wi-Fi, Z-Wave, DECT-ULE or Wavenis. There are also wired solutions using the electric grid to perform communications as Insteon or X10.

• Platform providers: embedded hardware/software systems enabling the first (or the last) data management stage after the smart end-points. Usually, these platforms are based in a gateway role to allow, securely and reliably, a communication with a back-end cloud computing platform.

• Connectivity providers: composed by the classic Internet Service Providers (ISP), such as R Cable, and also specific connectivity enablers for the IoT like Sigfox and LoRa, which use Low-Power Wide-Area Network (LPWAN) to allow long range communications at a low bit rate.

• IoT cloud services: suited for large scale data-storage and analysis that can be col- lected but not as easily processed. This is intended to perform the emerging computing paradigms as Big Data and Machine Learning. 2.1 The IoT architecture 11

The main focus of this chapter is the wireless smart sensor networks and the current state of the gateway platforms designs. The cloud computing solutions has less importance but they will be briefly commented.

2.1 The IoT architecture

In IoT large amounts of data are produced in different remote sites, far away from the high computing platforms hosted somewhere on the Internet. Transmitting these massive amount of raw data over a network puts tremendous load on network resources. So, it can be more efficient to process data near its source and send only the data that has value over thenetwork to a remote data center. Due to this fact, different approaches are appearing to improve the quality of service (QoS) of IoT applications. The object is to set up a computing extension of the cloud platform near to the IoT devices. Edge Computing is a centralized approach while Fog Computing is distributed.

2.1.1 Edge Computing

Currently, most of the IoT architectures are based on edge computing, eliminating, or at least reducing, the core computing environment in the cloud. Edge Computing was introduced by IBM with the goal to push Java computing to the edge with a data-oriented approach. The name "edge" in edge computing is derived from network diagrams; typically, the edge in a network diagram means the point at which traffic enters or out of the network. The central element in Edge Computing is typically known as the Edge Gateway, capable, among other things, of communicate with the end-points, to process the end-point data and to establish a secure tunnel with the back-end. The major benefit of edge computing is that improves time to action and reduces response time down to milliseconds, while also keeping network resources.

2.1.2 Fog Computing

The last emerging paradigm is Fog Computing, a term proposed by Cisco, resulting on OpenFog architecture. This architecture seems to be suitable for the future of many IoT applications. However, nowadays it is not established and it is more a concept than a reality. 12 State of the art

Fog computing, also known as fog networking or fogging, is a decentralized computing infrastructure in which data compute, storage and applications are distributed in the most logical efficient place between the data source and the cloud. The goal of fogging is to improve efficiency and reduce the amount of data transported tothe cloud for processing, analysis and storage. This is often done to improve efficiency, though it may also be used for security and compliance reasons. OpenFog is the materialization of fogging. In the Figure 2.1 is shown an example of the OpenFog proposal.

Fig. 2.1 OpenFog multi-tier deployment. Extracted from [14]

The nodes at the edge are focused on sensor data acquisition, data normalization, and control of sensors and actuators. These fog nodes nearest the physical technology edge will need to operate at milliseconds order. The next higher tier is focused on data filtering, compression, and transformation and also communication between lower tier nodes. The tier nearest the back-end cloud is typically focused on aggregating data and turning the data into knowledge. In a fog environment, intelligence is at the local area network. Data is transmitted from endpoints to a gateway where it is then transmitted to sources for processing and returning transmission. This paradigm identifies the main idea of this thesis.

2.2 The smart sensor and actuators

The concept of smart transducer is underlying of the complementary electronics integrated in a transducer or a group of transducers. These electronic elements are composed by 2.2 The smart sensor and actuators 13 conditioning electronics, a controller, a memory, a communication interface and a power supply. Therefore, a smart sensor provides more functions than the necessary to generate a correct representation of the monitored physical variable. These functions are usually intended to integrate the sensor with the applications of a networking environment. The Figure 2.2 represents the basic block diagram of a smart transducer.

Fig. 2.2 Basic architecture of a smart transducer

In a smart sensor, there are distinguish the capabilities of digital processing, memory and networking. According to the communication interface, two families are distinguished: the wired networks, known as field buses, and the wireless networks or WSANs. Usually, this section is oriented to the WSAN study. The WSANs operate in free bands of the electromagnetic spectrum, called Industrial, Sci- entific and Medical (ISM). The usage of these bands is free to everybody, as longasthe power limits are respected. These constraints force errors to this kind of communications and interference tolerance, so Forward Error Correction (FEC) techniques are fundamental. Smart sensors were created in the 1970s in the military field. In that moment, the state of the art of processors was not enough to withstand the complexity of surveillance systems in noisy environments. This technology was restricted in the military field until the 1990s, when there was a great leap in the quality of the memory access and digital processing, thanks to CCD-CMOS technologies. Also, the VLSI processor manufacturing technology was fundamental to reduce considerably the size of the smart sensors [15]. In the commercial sector, Honeywell was the first company that brought additional functions to classic sensors. At first time, the motivation was to introduce signal compensation in the sensor output to achieve normalization and linearization to facilitating the usage. Then, the companies start to introduce their own interests in the smart sensor designs, as remote wireless communications, linearization, auto-calibration, auto-test or auto-identification. 14 State of the art

This caused a full incompatibility among the different smart sensors manufacturers. In September of 1993, the National Institute of Standards and Technology (NIST) and the Institute of Electrical and Electronic Engineers (IEEE), promoted a meeting to find out a solution to this problem. The result was the norm family IEEE 1451.

2.2.1 IEEE 1451 standard family

The family of smart transducer interface standards, under the designation of IEEE 1451, defines a set of common communication interfaces to standardize the connectivity oftrans- ducers (sensors and actuators) to instruments, instrumentation systems, or control/field networks. This set of standards is intended to make it easier for transducer manufacturers to develop smart devices and to interface those devices to networks, systems, and instruments by incorporating existing and emerging sensor and networking technologies. The Transducer Electronic Data Sheet (TEDS) is the heart of the standard. It consists of a template which contains the necessary data to identify and characterize a smart transducer device. These data includes a network address, the manufacturer ID, the model ID, the magnitude of the measured variable, the dynamic range, the resolution, the commands to launch or the calibration date. IEEE 1451 standardizes two interfaces: a transducer device interface and a transducer network interface. The transducer device interface is the interface between a transducer device and a network device, whereas, the transducer network interface is the interface between a network device and user applications. In IEEE 1451 terminology, a transducer device is known as Transducer Interface Module (TIM), also recognized in the industry as a sensor node or an end point. A network device is known as NCAP (Network Capable Application Processor), also recognized as a network node or a gateway device. The Figure 2.3 represents the role of each one. The TIM consists in one or more transducers with their own power supply, conditioning electronics, ADC and/or DAC, signal processing, a microcontroller and a communications module implementing the interface between this and the NCAP. The NCAP consists on hardware and software, whose mission is to provide a bridge between the different TIMs, controlling each TIM through a digital interface. Notice that, the communication between the NCAP and the TIM must be similar, defining a symmetry between them, represented as 1451.X. 2.2 The smart sensor and actuators 15

Fig. 2.3 IEEE 1451 Block diagram of the NCAP and TIM interfaces [16]

The Figure 2.4, extracted from the National Institute of Standards and Technology (NIST) official website, represents the current state of each standard of the IEEE 1451family.

Fig. 2.4 IEEE 1451 Family of Standards and Interfaces

In the 1451 family, the 1451.0 [16]is dedicated to the TEDS description and the 1451.1 [1] is intended to describe the NCAP as a gateway, interconnecting the sensor network and a user network such as Internet or a LAN. Due to this fact, the standard 1451.1 [1] purposes the usage of well-known top stack protocols as HTTP, SOAP, XMPP or SNMP. 16 State of the art

However, as it can be seen in the red color of the 1451.1 reference in the Figure 2.4, the standard is still not conclusive and needs to be newly proposed. The communication between NCAP and TIM is defined by IEEE 1451.2, IEEE 1451.3, IEEE 1451.4, IEEE 1451.5 [17], IEEE 1451.6, and IEEE 1451.7. The Table 2.1 shows the task of each one. Table 2.1 IEEE 1451 communication target technology between NCAP and TIM

Standard Target IEEE 1451.2 USB, I2C, RS-232, TII and SPI IEEE 1451.3 Multi-drop bus IEEE 1451.4 Mixed signal (analogical and digital) IEEE 1451.5 Wireless (Bluetooth, ZigBee or Wi-Fi) IEEE 1451.6 CANOpen IEEE 1451.7 RFID

As these family of standards is very extensive, this chapter is focused in 1451.0 because of its good adoption and 1451.1 because it is completely related with the main objective of this thesis. Finally, the 1451.5 is analyzed because it also has good adoption and it is intended to define the wireless protocol, so Z-Wave will be based onthat.

2.2.1.1 IEEE 1451.0

The IEEE 1451.0 is the 1451 family base, it consists on Common Functions, Communica- tion Protocols, and Transducer Electronic Data Sheet (TEDS) Formats. The TEDS is the mechanism for plug and play identification. The TEDS is composed by data blocks that specify the transducer electronic data sheet structure and content. They are intended to be stored in a nonvolatile memory within a TIM. However, there are applications in which to store them in a nonvolatile memory is not practical, so the TEDS is stored in a separated file. The values of register of the TEDS are described with parameters T/L/V (Type/Length/Value), where, the first describes the identification of the tuple, the second describes the length field, and the third stores the value of parameter.

2.2.1.2 IEEE 1451.1

The IEEE 1451.1 for NCAP Information Model establishes a standard interface for connecting network capable processors to control networks through the development of a common 2.2 The smart sensor and actuators 17 control network information or object model for smart sensors and actuators. This object model characterizes devices in the network including the transducer type, its functions, its features or its networking capabilities. The Figure 2.5 shows the recommendations in the NCAP design.

Fig. 2.5 The NCAP standardized implementation

In the Figure 2.5 the physical components are drawn in solid lines while, the logical compo- nents, in dotted lines.

• Physical view: composed by a microprocessor and its supporting circuitry. The rest of hardware is intended to the attached network and the input/output interface to the transducers that can be another kind of network.

• Logical view: is the application software that can be divided into support and services components. The support components are the operating system and the drivers of the networking protocol and the transducer interfaces. The services are intended to external hosts, providing an abstract API to execute actions in the transducers.

This standard allows the identification of the Master-GW functionalities. So, the Master-GW will be a full implementation of the NCAP while the Slave-GW will be reduced version, implemented only the transducer and network interfaces and a software bridge. 18 State of the art

2.2.1.3 IEEE 1451.5

IEEE 1451.5 standard for Wireless Communication Protocols defines a set of specifications between the WTIM (Wireless Transducer Interface Module) and the NCAP. It adopts the pop- ular 802.11 (Bluetooth and Wi-Fi) and the 802.15.4 (Zigbee) as main radio communication protocols. For each one of these technologies, it is defined a specific TEDS. The WTIM and its associated NCAP must have a similar radio module (design symmetry) to complete the radio link. The main specifications of these standard are:

• A NCAP can route data and commands between an external network and a transducer connected to a WTIM.

• A NCAP can register multiple WTIM.

• A WTIM only can be register by one NCAP.

• A WTIM can manage multiple transducers.

• The WTIM-WTIM communication is allowed.

It is important to highlight, the IEEE 1451.5 is the only standard in the 1451 family, that matches all the 1451.0 specifications without introduce modifications. The IEEE 1451.5 standard not establishes the recommendations of the wireless protocols, as this is not its purpose.

2.2.2 WSAN designs

There a wide number of implementations of wireless sensor and actuator networks. Usually, WSANs contains nodes using batteries or energy harvesting so, the power consumption efficiency becomes a really important factor. The components of the radio system are the largest power consumers when the radio is been used. However, when the radio system is off, it consumes practically nothing. So, it is critical to choose an efficient radio protocol, furthermore, when it is been used battery devices. There are two main groups of WSAN: the Low-Rate Wireless Personal Area Networks (LR-WPAN) such as Z-Wave or Zigbee, and Low Power Wide Area Network (LPWAN) that are primarily facilitated by the cellular network as NB-IoT but also with new proprietary radio technologies as SigFox and LoRa. 2.2 The smart sensor and actuators 19

As this thesis is focused in a Smart Home service, the LR-WPAN technology standardized by the norm IEEE 802.15.4 will be analyzed.

2.2.2.1 IEEE 802.15.4

IEEE 802.15.4 specifies the PHY and MAC layers propelling the power saving andthe reliableness. The PHY layer is implemented with an O-PSK (Offset-Quadrature Phase-Shift Keying) modulation and a DSSS (Direct-Sequence Spread Spectrum) technique. When a frame is sent, a preamble is transmitted during 128 µs, allowing the receptor to sync up the carrier frequency. Then, a well-known Start of Frame Delimiter (SFD) is sent indicating the starting of the payload. The MAC layer consists of a star topology, where all devices directly communicate to each other (peer to peer). The IETF 802.15.4e redesign the 802.15.4 protocol to include temporal synchronization avoiding the use of beaconing. This improves the energy efficiency performing a frequency channel hopping, creating a protocol known as Time Synchronized Channel Hopping (TSCH). The Figure 2.6, extracted from [11] shows an example of a 4 slot slotframe and a timeslot diagram of an acknowledged transmission.

Fig. 2.6 Timeslot diagram. Slotframe (left). Data frame and ACK (right)

In each transmission slot, the MAC layer checks if the packets are in the queue associated to that slot. If no, the radio system turns off. If so, the packet is transmitted and the ACK is waited. If the ACK is received, the packet is removed from the queue. If the ACK is not received, the packet is kept in the queue to future retransmissions. With the frequency diversity the reliableness is increased as the interference effect and the multihop fading are mitigated and, the network capacity is incremented because more than one device can transmit simultaneously. 20 State of the art

However, a previous transmission schedule must be set up, carefully and with continuous updates. In the Figure 2.7, there is an example of a transmission plan.

Fig. 2.7 Transmission schedule

In a centralized approach a specific manager or coordinator is in charge of building and maintaining the network schedule. In practice, this node is usually a gateway. In a distributed approach, nodes decide locally on which links to schedule with which neighbors. This standard is the base of many popularized WSAN protocols as Zigbee or Z-Wave. As Z-Wave is the protocol used in the Smart Home service of this project it will be explained below.

2.2.2.2 Z-Wave

Z-Wave was developed by Zensys, Inc. a Danish start-up company, coming to market in 2004. From the initial idea of developing their own home automation solution Zensys soon evolved into becoming a provider selling a home automation ASIC together with own firmware to sensor/actuator manufacturers. Zensys defines RF hardware, encoding type and network organization through firmware precompiled libraries that manufactures can not modify, but in the other hand, it defines specific functions on application layer that manufacturers have to use in an optimal way.So Z-Wave solution is a combination of an Atmel microcontroller and a radio transceiver. The cornerstone of Z-Wave was the foundation of the Z-Wave Alliance in 2005, a industrial alliance of manufacturers of Z-Wave compatible products. Some well-known members of the Z-Wave Alliance are Honeywell, DSC, LG, Somfy, Panasonic, Samsung, Nokia or Belkin. 2.2 The smart sensor and actuators 21

Nowadays, the Z-Wave Alliance is composed by more than 450 companies which were launched about 1700 different products and all of them are interoperable with each other. The central duty of the Z-Wave Alliance is the maintenance of the Z-Wave devices interoperability defining a common application layer. This is guaranteed by a certification program. In December of 2008 the Asiatic SoC manufacturer company, Sigma Designs, purchased Zensys/Z-Wave and, in 2012, the International Telecommunication Union (ITU) ratifies Z-Wave MAC and PHY layers as a new sub-1GHz narrow band wireless standard[18]. Z-Wave is designed to provide reliable, low-latency transmission of small data packets at data rates up to 100 [kbit/s]. The throughput is 40 [kbit/s] (9.6 [kbit/s] using old chips) and suitable for control and sensor applications. It uses the Part 15 unlicensed Industrial- Scientific-Medical (ISM) band. The header introduced into the PHY layer is composed bya preamble and a well-known frame, the SFD, as the 802.15.4 recommends. Connectivity between Z-Wave nodes is peer to peer. This is a good advantage which allows to extend the network coverage proportionally to the contained node volume. The network coordinator executes a routing algorithm to establish a network retransmission schedule between the nodes. Usually, the network coordinator is used as a gateway to allow remote access through Internet. Each network is associated with an unique 32-bit identifier (HomeID). Each node is identified by an 8-bit NodeID which only can belong to one network. A Z-Wave frame is composed by the PHY header, the MAC header and data payload which is organized by Command Classes. The HomeId and the NodeId are inferred into the MAC header to address the node that the command is directed. In the Figure 2.8 is represented the inference of a MAC Protocol Data Unit (MPDU) into a PHY Protocol Data Unit (PPDU).

Fig. 2.8 PPDU data structure

The data payload inferred in the MPDU is the application layer. It is organized by Command Classes that represent the common language of all the Z-Wave devices. 22 State of the art

2.2.2.3 Security in WSANs

WSAN are vulnerable to be attacked in different ways, the simplest is radio jamming, commonly used to obstruct alarm systems. Another threat is the unintended inclusion of a rogue node. An attacker may use a wireless sniffer to capture transmissions over the air and replay such transmissions at later time. Encrypted commands may also be replayed. As the Wi-Fi protocol, WSANs also operate with the concept of a network key. All nodes may use this key to communicate to each other. The US Government considers AES-128 safe enough for classified information up to the secret level [19]. However, the distribution of this key is a problem since it could be intercepted. The Diffie-Hellman asymmetric key exchange solves this problem. This is known asa one-way function [20]. By adding this initial step to the process, two nodes may establish a shared secret key for communication over an insecure network only by using the one-way function. Asymmetric ECDH keys used for the temporary secure channel are only used to send a few frames before nodes switch to the assigned. WSAN are also susceptible to replay attacks. To avoid them, any frame is scrambled by a long Nonce before encryption. The Nonce is singlecast and it is updated before each new transmission.

2.2.3 WSAN protocols in Smart Home

There are different protocols competing to become the market leader of Smart Home. Among them it will be compared Zigbee, DECT-ULE, EnOcean and Z-Wave. Zigbee is the most faithful representation of the IEEE 802.15.4 providing a good transmission rate with a low energy consumption. Zigbee is a complete open global standard gained ratification by IEEE in 2003. DECT-ULE works in the 1.9 GHz ISM band and its transmission range covers a distance of 100 to 300 meters. Furthermore, it offers high quality support to voice transmission, keeping the energy consumption compromise. EnOcean is a particular solution that uses special short frames to avoid the CSMA complexity and the use of ACKs. The main goal of Enocean is energy harvesting with extremely ultra-low power. It works in the 868 GHz band (in Europe) using a Amplitude Shift Key (ASK). The next table compares the main features of these protocols in an indoor environment. 2.3 Platform architectures 23

Table 2.2 Comparison of WSAN protocols used in Smart Home

Zigbee DECT-ULE EnOcean Z-Wave Tx.rate[kbps] 9.6, 40, 100 1000 120 9.6, 40, 100 Range[m] 20 70 30 15 Frequency[MHz] 868.8, 2400 1900 868.8 868.8 Tx.power[dBm] 8 25 6 0 Sensibility[dBm] -98 -98 -95 -101

All these protocols use the security protocol 128-bit AES to protect WSAN unwanted listens.

2.3 Platform architectures

This section collects some of the most used operating systems, frequently working as computing gateways, but also interfacing some smart transducer software functionalities. Regarding, the hardware, one of the main advantages of use an operating system is to be agnostic of the hardware. However, there are some hardware platforms that are becoming the most used, usually because the developers prefer them. These are the or BeagleBoard which are based on the ARM architecture and the , based on x86 . Finally, this section accomplish the most used protocols on the top of the software stack, frequently used to exchange data between the gateway and the cloud.

2.3.1 Software platforms

The exposed platforms accomplish most of the following properties: low memory footprint, high power efficiency, a modular and configurable communication stack, and strong support for specific wireless and sensor technologies. Generally, the Linux based operating systems are intended to support computing gateways with high level software running on, while real-time operating systems (RTOS) are focused in the development of end points since they are specialized in determinism. 24 State of the art

2.3.1.1 Operating systems for IoT

These are capable to run on microcontroller units (MCUs) providing smartness to very low computing devices. They provide an interface to developers who know the real time limits required to perform each action. These operating systems are dedicated to the end-point devices.

• Contiki OS: widely used, it provides extensive wireless networking support, with an IPv6 stack contributed by Cisco. Its minimal memory requirements are 10KB RAM and 30KB flash.

• TinyOS: mature project started in 1999 that supports low-power consumption on MCU targets. Written in a C dialect called nesC, it is used on low-power wireless networking, including multi-hop nets.

2.3.1.2 Linux based operating systems

Linux based kernels that are categorized as lightweight but are still largely aimed at desktop use or portable USB stick implementations, rather than headless devices. These operating systems are intended to be embedded in gateway computer platforms.

• Debian-dist: there are many Debian kernels recompiled for different embedded hard- ware based on ARM architecture. One of the most popular is the Raspbian distribution for the Raspberry Pi.

• OpenWRT: resurfaced due to the IoT uprising, it is a lightweight networking-focused embedded frequently found on routers and MIPS-based Wi-Fi boards.

• uCLinux: is the only form of Linux that can run on MCUs, and only then on specific Cortex-M3, M4, and -M7 models. It requires MCUs with built-in memory controllers that can use an external DRAM chip to meet its RAM requirements. Now merged into the mainline Linux kernel, uClinux benefits from the extensive wireless support found in Linux. EmCraft is one of the biggest boosters for uClinux on MCUs, offering a variety of Cortex-M-based modules with uClinux BSPs.

LiteOS: ranges from MCU-based devices to Android-compatible applications processors. Some of its biggest advantages are its zero configuration, auto-discovery, auto-networking or fast boot. It also offers extensive wireless support, including LTE 2.3 Platform architectures 25

and mesh networking. It is available with Huawei’s Agile IoT Solution driving its Narrow-band IoT (NB-IoT) implementation.

• Android Things: the resulting platform of the Google efforts to dominate IoT. It is the evolution of the initial Brillo project including Java support. This is a lightweight Android-based distribution adapted to different BSPs to support different boards such as Intel Edison or Raspberry Pi 3. Its future is tied to Google’s Weave communications protocol bringing discovery, provisioning, and authentication functions, which can run on as little as 32MB RAM and 128MB flash.

2.3.1.3 Non-Linux based operating systems

Some are based on the microkernel architecture. There is a diffuse line between the operating systems intended to be embedded on gateways and end points. Clearly, if the gateway is oriented to perform data analytics, the operating system must be someone of the previous section. However, when the gateway is a simple bridge (as our Slave-GW), it can use a microkernel architecture. Conversely, an end-node may implement some high level functions or implement the TCP/IP stack. So these operating systems are for both gateways and end-points.

• FreeRTOS: lacks Linux features such as device drivers, user accounts, and advanced networking and memory management. However, it has a far smaller footprint than Linux and can run on under a half KB of RAM and 5-10KB of ROM but, when used with a TCP/IP stack, it is more like 24KB of RAM and 60KB flash.

• Apache Mynewt: designed to be hardware agnostic (32-bit micro controllers, MIPS, RISC-V), it was developed by Runtime and hosted by the Apache Software Foundation. It gives wireless support, precise configurability of concurrent connections, debugging features, and granular power controls. Native support for TCP/IP, UDP and also, support for constrained networks e.g. CoAP and 6LoWPAN

• RIOT: allows application programming with the programming languages C and C++, and provides full multithreading and real-time abilities. RIOT runs on 8-bit, 16-bit and 32-bit (such as ARM Cortex) processors. It provides multiple network stacks, including IPv6, 6LoWPAN, RPL, UDP, TCP, and CoAP. 26 State of the art

• ARM OS: targeted on tiny, battery-powered endpoints running on Cortex-M MCUs with as little as 8KB of RAM. It provides multithreading and wireless support and also allows cloud services can securely extract data via an Mbed Device Connector. The project also launched a Wearable Reference Design.

2.3.2 IoT protocols

This section attempts to organize and briefly explain some protocols. The section is divided into infrastructure protocols, data protocols and multi-layer frameworks.

2.3.2.1 Infrastructure protocols

New protocols specifically created to enable some IoT applications.

• 6LoWPAN: acronym of IPv6 over Low power Wireless Personal Area Networks. It is an adaption layer for IPv6 over IEEE802.15.4 links. This protocol operates only in the 2.4 GHz frequency range with 250 kbps transfer rate. It is based on a frame format that allows header compression, adaption of the packet sizes of the two networks, address resolution, device and services discovery and also security.

• QUIC: Quick UDP Internet Connections, pronounced quick) supports a set of multi- plexed connections between two endpoints over User Datagram Protocol (UDP), and was designed to provide security protection equivalent to TLS/SSL, along with reduced connection and transport latency, and bandwidth estimation in each direction to avoid congestion.

• RPL: IPv6 Routing for Low Power Lossy Networks (LLNs), supports a wide variety of different link layers, including ones that are constrained, potentially lossy, or typically utilized in conjunction with host or router devices with very limited resources, as in Smart Home.

2.3.2.2 Data protocols

These are the most popular approaches for communication in constrained environments.

• MQTT: Message Queuing Telemetry Transport, enables a publish/subscribe messag- ing model in an extremely lightweight way. It is useful for connections with remote 2.3 Platform architectures 27

locations where a small code footprint is required and/or network bandwidth is at a premium.

• CoAP: Constrained Application Protocol, is an application layer protocol that is intended for use in resource-constrained Internet devices, such as WSAN nodes. It is designed to easily translate to HTTP for simplified integration with the web, while also meeting specialized requirements such as multicast support, very low overhead, and simplicity. The IETF Contrained RESTful Enviorments (CoRE) working group has proposed the following features: 1

– RESTful protocol design minimizing the complexity of mapping with HTTP. – Low header overhead and parsing complexity. – URI and content-type support. – Support for the discovery of resources provided by known CoAP services. – Simple subscription for a resource and push notifications. – Simple caching based on max-age.

2.3.2.3 Framework architectures

These are architectures of stack of protocols designed to simplify the developers work in the design of IoT applications. They offer an easy, reliable and secure way to exchange data between an end-point, a back-end and a user. Developers will have to compromise and make a decision based on the type of product they want to make [21].

• AllJoyn: is an open source framework that establishes an underlying bus architecture for applications to expose their services to other AllJoyn applications. The AllJoyn bus provides a platform link agnostic transport mechanism for applications on IoT devices to send notifications or exchange data. As it can be seen in Figure 2.9, at the top level, the AllJoyn framework protocol stack consists of an application providing a number of application layer services and supporting some service frameworks. These app layer services are defined by AllJoyn interfaces supported by the app. The app sits on top of the AllJoyn core library, which enables an app to invoke core AllJoyn functionality.

1RESTful is a HTTP interface method to obtain data or generate operations over the data 28 State of the art

Below the AllJoyn core library sits the AllJoyn router that implements core AllJoyn features including advertisement/discovery, session establishment, sessionless signals or authentication. The AllJoyn router supports multiple underlying transports for dis- covery and communication and provides an abstraction layer for each of the supported transport[22].

Fig. 2.9 AllJoyn software stack in a device

• IoTivity: stack composed by a RESTful API at the top, followed by an UDP transport layer secured with DTLS. It uses a CoAP based service discovery and IPv4 and IPv6 support [23]. Summarizing, it operates as middleware across all operating systems and connectivity platforms and has four essential building blocks:

– Discovery: supports multiple discovery mechanisms for devices and resources in proximity and remotely. – Data transmission: supports information exchange and control based on a messaging and streaming model. – Data management: supports the collection, storage and analysis of data from various resources. – Device management: supports configuration, provisioning and diagnostics of devices.

Iotivity supports Ethernet, Serial, PLC and Wi-Fi. In other words, the framework does not have support for any of the low power wireless technologies such as Bluetooth Low Energy (BLE) or IEEE 802.15.4 although this might come in the future. 2.3 Platform architectures 29

• Thread: combination of existing standards combined into a network stack that can be seen in Figure 2.10. It uses IEEE 802.15.4 at the physical and MAC layers. Thread is IPv6 based and uses 6LowPAN to enable IP routing over 802.15.4. It uses UDP for messaging and security is provided by DTLS together with 802.15.4 MAC security.

Fig. 2.10 Overview of the Thread stack

• Weave: application layer protocol that can be used to interact with devices. It currently supports Wi-Fi as its only transport with support for BLE under development. The protocol is part of a larger framework that can be divided into three main components:

– Cloud: enables support for things like remote access and RESTful APIs. – Device: open source C++ library called "libeweave" that aims to make it easy for manufacturers to build devices. – Client: Libraries are available for mobile devices (iOS and Android) and the web. These enable the clients to do things such as controlling devices and reading a device’s state either locally or remotely.

Weave is designed with the end users in mind and this shows in a number of ways. First, it supports device discovery and provisioning that is designed to make it simple for the end user to set up a new device in their homes.

• HomeKit: provides a consistent experience for users when using Smart Home products with Apple iOS device. It is made up of two parts, the first of these is a set ofiOS APIs that is used to develop home automation apps. The second part is the Homekit Accessory Protocol (HAP) which is the application protocol that iOS devices use when communicating with HomeKit enabled accessories. 30 State of the art

2.4 IoT cloud providers

These platforms are built to take massive volumes of data generated by devices, sensors, websites, applications, customers and partners and initiate actions in response. Most of the technological giants expose their solutions through cloud services attracting costumers. Below the powerful and most used cloud platforms are collected by the company owner.

2.4.1 Amazon

Amazon Web Services (AWS) is currently the public cloud market leader with Microsoft Azure and Google Cloud Platform at second and third, respectively. The AWS cloud operates 35 availability zones within 13 geographic regions around the world. Here are some of the features offered with Amazon’s AWS IoT platform [24]:

• AWS IoT Device SDK: provides a software development kit to help enterprises connect to hardware devices or mobile applications. It enables devices to connect, authenticate and exchange messages with AWS IoT using the MQTT, HTTP or Web- Sockets protocols. The Device SDK supports C, JavaScript and , and includes the client libraries, and developer and porting guides for manufacturers. Users also can employ an open source alternative or write their own SDK.

• Device Gateway: enables devices to securely and efficiently communicate with AWS IoT. The gateway can exchange messages using a publication/subscription model, which enables one-to-one and one-to-many communications, making it possible for a connected device to broadcast data to multiple subscribers for a given topic. The Device Gateway supports MQTT, WebSockets and HTTP 1.1 protocols.

• Authentication and authorization: provides mutual authentication and encryption at all points of connection, so data is never exchanged between a device and AWS IoT without proven identity. AWS IoT supports the AWS method of authentication – called ‘SigV4’ – as well as X.509 certificate-based authentication. Connections using HTTP can use either of these methods, while connections using MQTT use certificate-based authentication, and connections using WebSockets can use SigV4.

• Registry: establishes identities for devices and tracks metadata such as the device’s attributes and capabilities. The registry assigns a unique identity to each device that 2.4 IoT cloud providers 31

is consistently formatted regardless of the type of device or how it connects. It also supports metadata that describes the capabilities of a device.

• It allows the storage of metadata for devices at no additional charge, and metadata in the registry does not expire as long as users access or update their registry entry at least once every seven years.

2.4.2 Microsoft

Microsoft’s Azure cloud comes in second place to Amazon in terms of reach, but had a greater quarter-to-quarter growth rate than any other cloud in late 2015. Here are some of the things you can do with Azure, according to Microsoft [25]:

• Capture and analyze untapped data to improve business results.

• Get started quickly with preconfigured solutions.

• Tailor preconfigured solutions to meet your needs.

• Enhance the security of your IoT solutions.

• Support a broad set of operating systems and protocols.

• Analyze and visualize large quantities of operational data.

• Integrate with your existing systems and applications.

• Scale from proof of concept to broad deployment.

2.4.3 Google

Google is the most aggressive company trying to repeat the story happened with Android devices. Strategically, it cares about becoming the IoT platform choice for service developers, while the other technological companies are focused on its IoT cloud platforms. Android Things allows developers to build a smart device using Android APIs and Google Services. Developers will be able to use the Google Weave protocol to communicate between devices along with Google Cloud services as the Google Cloud Vision or Google Assistant. 32 State of the art

Nowadays, Android Things is completely open for developers. However, if it becomes the dominant platform, it is expected that Google will encourage to use it with Google Cloud and also to commercialize IoT closed software solutions through the Google Play. Google operates its own private fiber network with over 70 “points of presence” across33 countries, ensuring data to and from devices gets delivered at ultra-low latency. Google said this allows enhanced security because enterprise IoT devices avoid having to travel the public nternet through the majority of their time in transit. Here are some other key features of the Google Cloud Platform, according to the company [26]:

• Google-Grade Security: device-to-cloud or cloud-to-device. All the Cloud Platform APIs are secure by default with full encryption, backed by integrated and pervasive security across the entire infrastructure.

• Real-time: streams and transforms data as it arrives with Cloud Dataflow, a unified programming model for both batch and streaming data sources.

• From small to big data: Pub/Sub makes real-time, reliable processing of IoT data easy, and Google’s storage products hold all data efficiently and economically. Chapter 3

The 3ollosR service

Since this project is geared to expand the coverage of the WSAN over a LAN in the 3ollosR Smart Home service, it is important to know the concrete environment. This service uses Z-Wave as the main WSAN technology and also Wi-FI IP cameras. The Z-Wave nodes and the cameras are coordinated by a Master-GW. The last element required in the home installation is a Customer-Premise Equipment (CPE), composed by a router, a network switch, a wireless access point (Wi-Fi) and a modem (ADSL, fiber/coaxial). With these equipment, the Master-GW allows a remote cloud platform, also known as a back-end, to access the data from the WSAN and the video from the cameras. In turn, the back-end allows the service costumers to remotely control and monitor their home, from an Android/IOS application or a responsive web. This scenario is represented in the Figure 3.1

Fig. 3.1 3ollosR basic scenario

The Master-GW is an intermediary element which allows the back-end and the WSAN to achieve each other, performing the translation between Z-Wave commands and JSON which is a light data format friendly with web services. 34 The 3ollosR service

On the boot, the Master-GW always starts a SSL/TCP tunnel to the back-end, setting up a new entry in the CPE router NAT table, avoiding additional firewall configurations to allow the back-end to achieve the Master-GW from Internet. This starts an authentication process, presented in the Figure 3.2. Public key cryptography, or asymmetric cryptography, is any cryptographic system that uses pairs of keys: public keys which may be disseminated widely widely, and private keys which are known only to the owner. This accomplishes two functions: authentication, when the public key is used to verify that a holder of the paired private key sent the message, and encryption, whereby only the holder of the paired private key can decrypt the message encrypted with the public key [27].

Fig. 3.2 Authentication process

Since Internet is a best-effort network and the levels of latency oscillates due to occasional bandwidth constraints or unreliable connections, the data exchange with the back-end is buffered and sent using Message Queue Telemetry Transport (MQTT), on top of the TCP/IP stack [28]. The data travel from an end-point to the back-end is presented in the Figure 3.3

Fig. 3.3 Stack conversion in 3ollosR, from an end-point to the back-end 35

Apart from the protocol conversion, the Master-GW runs high-level software (Edge Com- puting) including the execution of the rules with the format "If this happens then, execute that", the RAM-buffering and chunk division of the video from the IP cameras, the building of periodic network maps or the unit conversion of the sensor measures. To facilitate the complete service explanation, it was divided in three different layers, pre- sented in the Figure 3.4:

• Sensorization: is the most important for this project. Composed by the indoor ele- ments as the Master-GW, the Z-Wave end-points, the Wi-Fi IP cameras and also, the CPE.

• Back-end: user-transparent layer in layer of manage all the service data.

• User interface: front view to the costumers of the service management.

Fig. 3.4 The 3ollosR structure 36 The 3ollosR service

3.1 Sensorization

The sensorization (and actuation) layer consists on a centralized approach because the Master- GW is the only coordinator of the WSAN. It consists on a very versatile design since all components are interchangeable, and there are not definitive elements. A description from the end devices to the final Master-GW software used to communicate with the back-end is attached below.

3.1.1 End devices

The end devices are purchased to external manufacturers that provides technical support. They are divided in Z-Wave nodes and the IP video cameras.

3.1.1.1 Z-Wave WSAN

Wireless Sensor Actuator Network is composed by the Master-GW, as the network master, and different Z-Wave certified wireless sensors and actuators, as slaves. Z-Wave networking is meshed, so, each node must not only capture and disseminate its own data, but also serve as a relay for other nodes. However, not all the Z-Wave nodes acts as repeaters, only the "Always On Devices", so, battery devices are simple endpoints (see Appendix A) Actually, the slave nodes certified in 3ollosR are magnetic door/window opening detectors, 4in1 multi-sensors (presence, temperature, humidity and luminosity), 6in1 multi-sensors (presence, temperature, humidity, UV radiation, luminosity and vibrations), smoke sensors, inundation sensors, energy meters, smart plugs or Z-Wave network repeaters. Figure 3.5 shows the appearance of these devices purchased to Aeon Labs.

Fig. 3.5 The 3ollosR certified WSAN nodes 3.1 Sensorization 37

There are several devices similar to those of the previous figure available on market from many different manufacturers. Among them, Aeon Labs was chosen as the main provider because its costs, the technical support and the flexibility in the orders.

3.1.1.2 IP video cameras

An IP camera consists on an standard camera with additional embedded hardware, running a very simplified Linux kernel. These cameras builds-in a microprocessor, a flash storage,a RAM and a network interface. Obviously, they also include image recording elements. The integration of IP cameras is one of the big challenges of the 3ollosR service. Three different manufacturers provide their IP video cameras: Axis, D-Link and Sercomm. The models are shown in the Figure 3.6

Fig. 3.6 IP video cameras in 3ollosR

All the features required to this cameras are exposed in a RFP (Request For Proposal) document, that was evolving over the time. This is sent to a big number of manufacturers and, if one of their products satisfy the requirements they get in touch and make a bid. The basic features collected in the RFP are:

• Video resolution: Full HD 1080.

• Video compression: H.264.

• Network interface: Ethernet 10/100 and/or Wi-Fi N.

• Network protocol: RTSP.

• Control API: REST HTTP.

Since these three cameras accomplish these features, the evolution in the IP camera model of 3ollosR was is related to find a balance between the camera price and its performance. The camera prices are: 230 C for the Axis, 99 C for the D-Link and 120 C for the Sercomm. 38 The 3ollosR service

The Axis camera has a nice behavior but it costs 100 C more than the D-Link one. However, the D-Link camera presents some problems as its slow reconnect in the falls of the Wi-Fi or the disadvantage of not have an Ethernet connector. The Sercomm is the new 3ollos incoming camera that overcomes the D-Link camera problem with an affordable price. With H.264 compressing, the video sequence comprises one I-frame (key frame), which encodes one entire image, followed by multiple P-frames (delta frames), which encode only changes in the image since the previous frame. This strategy results in a much lower data rate, especially for video surveillance footage where the majority of the image often remains the same. The more P-frames that exist between the I-frames (known as the I-frame rate, key frame rate, or GOV length), the lower the data rate will be. The advantage of the API to control the cameras is to configure the video parameters dynamically in function of the data rate admitted by the network. This configuration is intelligently done by the Master-GW

3.1.2 Master-GW hardware

It is an easy maintenance device, scalable in the services it can offer because its modular design and the software versatility. It is composed by:

• A single-board computer with embedded Linux.

• An enclosure with a secondary PCB for LED signaling.

• A 5 volts power supply giving a maximum current of 2 amperes.

• Extra elements as the Z-Wave dongle, hard drives or batteries.

The correct functioning of the single-board computer, the enclosure, the secondary board and the power supply is supported by Telecon Galicia SA.

3.1.2.1 Embedded computer boards

Since the beginning of 3ollosR in 2013, three different single-board computers have been adopted. The minimum features required to these boards are:

• CPU: ARM v9 architecture with a 400 MHz clock. 3.1 Sensorization 39

• RAM: 256 MB.

• Memory for OS, data and applications: 4 GB.

• Ethernet: One port 10/100 with LEDs.

• USB: Two ports 2.0 with embedded power supply.

• GPIO: digital I/O, I2C and UART.

The first board was the CubieBoard1, changed to the still current board, the eMMC 4.3flash memory version of the Cubieboard2. The last board, currently under test, is the Orange Pi PC. Figure 3.7 shows the appearance of each board and.

Fig. 3.7 Single-board computers

All these boards built-in an AllWinner SoC with includes an ARM processor architecture. They run a Linux kernel specifically compiled for each one, supporting all the embedded peripherals. Table 3.1 shows a comparison of their features.

Table 3.1 Hardware comparison of the single-board computers

Cubieboard1 Cubieboard2 (eMMC) Orange-Pi PC SoC AllWinner A10 AllWinner A20 AllWinner H3 CPU 1xARM Cortex-A8 2xARM Cortex-A7 4xARM Cortex-A7 Core clock 1 GHz 960 MHz 600 MHz GPU Mali-400 MP Mali-400 MP2 Mali-400 MP2 SDRAM 1 GB DDR3 1 GB DDR3 1 GB DDR3 USB 2 + 1xOTG 2 + 1xOTG 3 + 1xOTG Built-in flash 4GB raw 4GB eMMC - Storage microSD+SATA microSD+SATA microSD Ethernet 10/100 10/100 10/100 Target Price 56 C 61 C 28 C + microSD

As the Cubieboard2 is the main Master-GW embedded board, the A20 SoC block diagram and the peripheral electronics are represented in the Figure 3.8. 40 The 3ollosR service

Fig. 3.8 Cubieboard2 component view (left) and A20 block diagram (right)

In the case of the Cubieboard2 eMMC version, the element 18 of the Figure 3.8 is changed. The raw NAND flash is replaced to another IC with TSD/EMMC support. This component replacement also forces to change the Cubieboard2 kernel to drive the eMMC 4.3 natively. This is possible because the A20 SoC has support to manage a MMC. Regarding the Orange-Pi PC, it contains an AllWinner H3 SoC [29]. This SoC offers better features and a lower cost than the others. The main problem is the non-volatile Linux filesystem storage based-on SD cards.

3.1.2.2 MMC flash memory architecture

Linux filesystem is usually embedded in a flash memory, so choose well flash technology is critical. When a writing from the filesystem occurs in a raw NAND flash, it must write a page at a time, and it must be erased before writing. However, in order to erase a page it must erase an entire block which will include many pages, so if the power of the CPU is lost during an erase/write it is possible to lose the entire block and to corrupt the filesystem. In this kind of applications where memory writings are made constantly in logs, flash memory is completely critical. In fact, the first Master-GW prototype was using Cubieboard1 andit was quickly left because, in the face of an unexpected power off, the filesystem turns corrupt and it can not to be rebooted. Then, it was introduced the CubieBoard2 eMMC 4.3 version preventing the embedded Linux filesystem corruptions due to unexpected power failures. The difference was, whenan unexpected power off occurs, only the page being written turns corrupt. The eMMC system architecture [30] consists on a raw MLC NAND flash memory and a controller (Figure 3.9). 3.1 Sensorization 41

Fig. 3.9 MMC system architecture

The MMC controller has two interfaces. On the one hand, it has a HS-MMC interface which can be connected to the host controller, on the other hand, it has a NAND interface which is connected to the raw MLC NAND. The controller performs several well-known functions such as bad block management, wear leveling and error correction code (ECC), to utilize the raw MLC NAND efficiently. So, with this architecture, the CPU is more liberated from the erasing/writing routines protecting the NAND embedded Linux from unexpected power failures.

3.1.2.3 The enclosure

The enclosure of the Master-GW is designed to be the reused, supporting the replacing of the internal hardware and redeeming the investment. It contains a secondary board with LEDs connected to the Master-GW GPIOs, This gives visual feedback related to the power and the service performance. Figure 3.10 shows the design of the enclosure.

Fig. 3.10 Master-GW enclosure. Front view (left). Back view (right) 42 The 3ollosR service

The enclosure is composed by four parts: the translucent frontal, the black plastic top and lower tap with uprights to fit the boards and the back cover, where the external connections are disposed.

3.1.3 Master-GW software

The Linux kernel used in the Cubieboard2 is the 3.4.79-sun7i and the distribution of the operating system is Cubian. At least, Linux kernel must support the following features:

• MMC/SD/SDIO read/write card drivers.

• MII PHY SMSC FastEthernet driver.

• GPIO control driver.

• RAM block size configuration.

• RAM total size configuration.

• IPv4 stack.

Most of the software is written in Java and running over a JVM (Java Virtual Machine). It has a modular structure divided on drivers, adapters and services (Figure 3.11). The Java machine version is the 1.7 implemented by the open JRE 1.7 (open-jre-7) packet. Each software module has an API to be used by the other modules. They can be classified as:

• Drivers: handle all communications with end devices translating generic actions to specific protocols. They can perform two basic actions:

– To collect different kind of data as sensors reports, video recording or network maps, and send it to the adapters layer for processing. – To send commands to end devices received from the adapter layer.

• Adapters: process received data from sensors and take decisions to perform actions. It conforms the first intelligent filter after the sensorization layer. For example, they store the rules set up in the back-end to execute them locally and quickly.

• Services: resolve transversal functionalities based on the internal performance of the service. Their functions include to control the secondary board, to upgrade the Master-GW software versions or to report data to the back-end and to execute user and technician actions. 3.1 Sensorization 43

Fig. 3.11 Block diagram of the Master-GW software

It is important to emphasize the different mechanisms used in the adapters layer to exchange data with the back-end. The first approach was to use an API REST (implemented bythe SRE or ERS) based on HTTP stack to perform all communications. Due to delay problems, MQTT was introduced to accelerate the communications (see Appendix B). Currently, both systems coexist: REST as a backup and to implement the technical manage- ment tool (CRMS), and MQTT to perform the rest of the (big) data exchange.

3.1.3.1 Z-Wave WSAN management

Z-Wave WSAN is centrally orchestrated by the Master-GW, using a plugged on Z-Wave USB dongle. This dongle is purchased to Aeon Labs (Figure 3.12).

Fig. 3.12 Aeon Labs Z-Stick Gen5

There are many different Z-Wave USB dongles by many different manufactures, but all of them use the Static Controller firmware. This implies that the same driver is valid to control all of them. 44 The 3ollosR service

There are different available libraries to use the Z-Wave sticks with Static Controller firmware and, according to the document INS10247 Z-Wave Application Programmer Guide, all of them are based on Z-Wave Serial API [31]. Really, this USB compliant device behaves as it were connected with an UART interface. In fact, Serial API uses a Virtual COM Port (VCP) to handle it. Specifically, it is used the CP210x generic Linux USB-to-UART driver by Silicon Labs [32]. Serial API is the driving software which resolves the protocol stack until the bit level frames exchanged through the serial port. This includes the application layer mapping into Command Classes, ACKs and retransmission logic, MAC header or the CRC computation. Finally, the Z-Wave dongle only performs the PHY layer implementing the conversion between the port serial TTL and the Z-Wave RF. In 3ollosR is being used OpenZWave, an open source library developed by the Open Com- munity in C++. OpenZWave provides a programming interface t use the Serial API, allowing the access to all the protocol functionality, thus the application development is therefore simplified and less prone to bugs. This programming interface is based on a Manager class to push frames to the dongle and a notification callback system to notify the node events, asynchronously. The Master-GW software implements this Manager class through a JNI (Java Native Interface), a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call and be called by libraries written in other languages such as C or C++. The process to integrate a new device model in the service consists on identify the imple- menting Command Classes and how the values and are mapped. A standard configuration is established for each end node model, deciding parameters as the report period of each monitored variable or the precision of the measures. Abstractly of the WSAN technology, each device model is identified, by the triplet composed by: "Manufacturer ID", "Product ID" and "Model ID". These triplets are used to create the metadata to know how to manage each kind of device. For the rest of the software, a node is simply an object with an ID with some capabilities and parameters. When an action is carried out in a node, the adapters layer maps the protocol frame through the triplet ID of this node to a generic parameter or action. This mapping is performed through some templates built on JSON format for each node. This abstraction model is exploited by the configuration rules adapter to execute the "If-This- Then-That" rules, using a implementation of the Java Rule Engine named Drools. This has 3.1 Sensorization 45 several advantages like the facility for the data exchange through Internet using JSON data format or to allow the abstraction from the Z-Wave technology promoting the modularity. Thereby, the 3ollosR service could add or replace easily another network technology, as Zigbee, keeping static the rest of development or even executing rules between nodes that belong to different WSAN technologies. The standard execution of the WSAN control should be:

1. The rules are defined in the back-end through the user interface and they aresentto the Master-GW over the services layer.

2. These rules are stored on the adapters layer.

3. Drivers layer collects data from sensors and send them to the adapters layer.

4. Adapters layer, depending of the stored rules and the sensor data received, determine the following actions.

5. The measures are converted to standard units of measure through the UOM service.

6. The adapters layer report the WSAN activity to the back-end through the REST API or, recently, through the MQTT.

3.1.3.2 Video service

The Real Time Streaming Protocol, or RTSP, is an application-level protocol for control over the delivery of data with real-time properties. In this case, it is built over the TCP/IP stack. This protocol is intended to control multiple data delivery sessions, providing an extensible framework to enable controlled on-demand delivery of real-time data, such as audio and video. Sources of data can include both live data feeds and stored clips. The Master-GW implements a RTSP client driver to access the streaming over the LAN. This client is based on the packet ffmpeg, which provides the necessary codec to manage the H.264 video and audio streams. The video stream is obtained all the time and buffered into Master-GW RAM. This video buffer is 30 seconds long, so, when a video recoding related event occurs, it is sent and stored to the back-end, in a reliable way. The video stream handling is done in 3-second chunks. This help the transmission and the storing. FFmpeg also makes the video chunking. 46 The 3ollosR service

The 3ollosR camera integration is plug and play. When an IP camera is in the same LAN as the Master-GW, it is identified by the Localnet driver. Through an ARP request, the camera MAC is obtained and the Vendor ID and Model ID deducted from the MAC look-up table. Through this MAC information, the Master-GW developed camera driver provides an API that handles all the functions of each camera model, indistinctly and generically, accessing the video stream and configuring the video parameters.

3.1.3.3 Localnet

Master-GW discovers all hosts on its same local network, reporting the MAC and IP of the devices found. Then, the 3ollosR customers can know what devices are present on its home in each moment. This service is based on nmap open-source program [33], a network scanner that sends specially crafted packets to the target hosts and then analyzes the responses. Each minute a nmap packet were sent to all possible IP in the Master-GW subnet. The resulting information was pairs of IPs and MACs of the devices up in the LAN, The MAC has implicit information: an Organizationally Unique Identifier (OUI) is a 24-bit number that uniquely identifies a vendor, manufacturer, or other organization. These are purchased from the Institute of Electrical and Electronics Engineers, Incorporated (IEEE) Registration Authority. So, through the OUI look up table, the Master-GW also identifies the manufacturers and the products of each IP. At first, the Master-GW was using directly the nmap Linux tool to perform the host discovery. Each minute a nmap packet were sent to all possible IP hosts at the same subnet of the Master-GW. The resulting information was a table composed by an IP, a MAC and the Vendor ID and Model ID corresponding to that MAC. Its driver is also used by another software modules to recognize well-known IP devices in 3ollosR, as the video cameras. 3.2 Back-end 47

3.2 Back-end

The back-end is completely transparent for the end user and it is in charge of receive and store the sensor data, the provision and the configuration of the functional rules of the system. It is implemented in the RCable datacenter in A Coruña and it consists in a virtualized cloud computing platform. Although it is not the focus of this thesis, a description of it is introduced. It is important to mention the really important in this layer is the data management rather than the data mining. So, this development is independent from the kind of sensorization layer, enabling the management of any data mining technology. It is composed by the next elements:

• ERS: supports the message exchange over HTTP between different components of the platform, as the back-end databases, user interface and Master-GWs.

• EMQTT: broker server that implements the forwarding publish-subscribe paradigm.

• CRMS: web interface intended to provide a remote diagnostic and keeper tool to the technical support of the platform.

• Big data storage: collects and stores all the information received.

• Cross: stores the video recordings.

• Inventory and provision: keeps the provision state of the sensors and the sensor measures masters.

• Rules: keeps each user specific parametrizations, like the configuration rules.

The basic back-end services are summarized in the swsensorsrt verifying the access to all Master-GWs, and the dispatcher that collects the events generated by the rules and revises if it is necessary to send an alert to the client and finally send it via email, SMS or mobile application. To perform this functionality it uses the services of the Oracle and Cassandra databases, ERS and EMQ; offering different APIs to manage the inventory, database query, data collector and the message exchange with the Master-GWs. The implementation of each one of the back-end components is described below. 48 The 3ollosR service

3.2.1 External Resource Server

ERS allows the external services to communicate directly with the Master-GWs, and also allows the Master-GWs to send messages to different servers as the back-end databases, through Long Polling communications. ERS is developed in Erlang/OTP, a concurrent, fault-tolerant, distributed programming platform [34]. A distributed Erlang/OTP system consists of a number of Erlang runtime systems called "node". Nodes connect to each other with TCP/IP sockets and communicate by Message Passing. This platform provides the next features:

• Persistence layer: implemented used Mnesia [35], the native Erlang database. It provides strong replicate capacities and fault tolerance, so the system is prepared to easily migrate a relational database.

• Scalability and optimized performance: the system can deploy a configurable node number to divide the processing load or the Master-GW communications. To optimize the performance, ESR provides its own load balancer mechanism to support all Master- GW communications. This system has a recover mechanism to support unexpected falls.

• Communications: all server communications use HTTP with additional headers to implement the direct communication with Master-GWs and the different kind of requests supported. These HTTP communications can be ciphered using SSL protocol.

The API REST usage allows to get messages between the different platform layers i.e. the sensorization and the vertical services. These messages are HTTP kind with some special headers and they could be synchronous or asynchronous. Master-GWs are always connected to this platform allowing the transmission of all kind of resources. The Master-GWs always start this TCP/IP connection to the SRE and they keep it permanently working, using timeout messages. When a Master-GW starts the communication, it sends its MAC to identify itself and also sends some tags, Then each message directed to that MAC or to these tags, is deliver to this Master-GW. The ESR can be divided into the next modules:

• ID Adapter: centralizes the queries from or to the Master-GWs. It is the last responsi- ble of sending external service data to the Master-GWs. 3.2 Back-end 49

• Message queue: distributed database that stores and queue exchanged messages and messages that could not yet be sent.

• Request manager: manages all received requests from internal modules, external services or Master-GWs.

• Communications adapter: receives and processes received requests from external services as internal Erlang applications.

• Message bus: receives and delivers messages from communications adapter to ID adapter. It works in symbiosis with the ID Adapter.

The ESR was the original supporter of all message and data exchange in the 3ollosR back-end. Currently, MQTT is the preferred system to perform the external and also internal back-end communications because it is designed to support varying levels of latency. However, ESR is still been used as MQTT back-up and in the CRMS platform.

3.2.2 Erlang MQTT Broker

This is the server part of MQTT in 3ollosR. It is a multi-node broker that handles all MQTT connections and balances the MQTT bus traffic load, avoiding native parallelism problems. EMQTT is implemented by EMQ platform [36], a fully open source, scalable, reliable, enterprise-grade MQTT message hub. Sensors, mobiles, web browsers and application servers could be connected by EMQ brokers with asynchronous Publish/Subscribe messages. Each client that wants to receive messages subscribes to a certain Topic and EMQTT delivers all messages with the matching Topic to this client. Therefore the clients not have to know each other, they only communicate over the Topic. This architecture enables highly scalable solutions without dependencies between the data producers and the data consumers. The cluster architecture of EMQ broker is also based on distributed Erlang/OTP and Mnesia database. The cluster design could be summarized by the following two rules:

• When a MQTT client SUBSCRIBE a Topic on a node, the node will tell all the other nodes in the cluster: I subscribed a Topic.

• When a MQTT Client PUBLISH a message to a node, the node will lookup the Topic table and forward the message to nodes that subscribed the Topic. 50 The 3ollosR service

Figure 3.13 shows the publish/subscribe paradigm and some of the most popular technologies used in the publish and subscribe sides.

Fig. 3.13 MQTT diagram. Publishers at left. Subscribers at right

EMQ was chosen as the MQTT broker. It offers a very comfortable web dashboard to be managed. The Dashboard helps check running status of the broker, monitor statistics and metrics of MQTT packets, query clients, sessions, topics and subscriptions. Figure 3.14 shows a generic overview of this interface.

Fig. 3.14 EMQ web dashboard

Summarizing, highlights of the EMQ broker implementation are:

• Full MQTT V3.1/3.1.1 protocol specifications support.

• Easy and quick installation on Linux, FreeBSD, Mac and Windows.

• Massively scalable because the support of many different kind of publisher protocols. 3.2 Back-end 51

• Cluster and bridge support.

• Easy to extend by hooks and plugins to customize or extend the broker.

• Pluggable authentication using LDAP, MySQL, PostgreSQL, Redis Authentication Plugins.

3.2.3 Big data storage

This module collects and stores all the information received from sensors. It is a two layer architecture, an application with two interfaces and a Big Data storage system based on Apache Cassandra. The Storage App is a specific development for this project, written in Java and running in a Tomcat container. Apache Cassandra is a non-relational database (NoSQL), distributed and based in a "Key- Value" storage model, written on Java. It allows to store big data volumes in a distributed way. For example, Twitter platform uses it. Its main objective is the lineal scalability and availability. The Cassandra distributed architecture is based in a series of equal nodes communicated by P2P protocol, so redundancy is maximum. Cassandra is developed by Apache Software Foundation. The structure of the Big Data database composed by the Cassandra App with its two interfaces and the distributed Apache Cassandra system:

• Collector: picks up data from sensors using POST.

• Casandra Query App: allows to recover, orderly and metadated, the sensors measures using GET.

3.2.4 Inventory and provision

This element keeps the provision state of the sensors and the measure masters. Like the Big Data storage, it is composed in two layers: an app, for the queries, insertions and data operations, and another layer for the SQL storage. As the Cassandra App, the Provision App is also specific developed for this project. The relational database is Oracle, although itcould be of another kind like mysql or postgres. The Provision App works through REST actions POST, GET, PUT and DELETE:

• To register devices (Master-GWs, Z-Wave nodes or IP cameras) or services. 52 The 3ollosR service

• To consult device properties, type of measures or a Master-GW relate information .

• To consult the configuration of a marketer packet.

• To obtain all the templates associated to an Master-GW.

• To modify a device or a service configuration.

• To unregister a device or a service.

3.2.5 Rules

This element keeps the rules master, the parametrizations of each user and the basic rules over that the complex rules are composed, style of "IF-THIS-THEN-THAT". Same as the last two cases, this is composed by two layers, an app to consult, insert and operate with the rules, and other layer to SQL storage. The Rules App is a specific development of the project, written in Java and running ina Tomcat container. It has three parts:

• Inventory: handles the rules inventory and its metadata

• Rules manager: handles the specific parameters of the rules applied to each user

• Base files: keep some Drools base files

Drools is a business rule management system (BRMS) with a forward and backward chaining inference based rules engine, more correctly known as a production rule system, using an enhanced implementation of the Rete algorithm. It is opensource according with Apache license terms. The Rules App allows:

• To register a new rule associated to an Master-GW. In the rule also is registered the conditions and the actuations.

• To consult or modify a specific rule or to obtain all rules for an Master-GW. 3.3 User interface 53

3.2.6 Control R Management System

CRMS allows the RCable technical support to diagnostic and to keep each Master-GW performance via web. Its function includes:

• To check the execution state and Linux process running in the Master-GWs.

• To upgrade the Master-GW software version.

• To execute terminal commands in the Master-GW through a shell.

• To obtain the state and connection statistics between the Master-GW and the SRE.

• To access the Master-GW logs.

• To monitor the state of the Master-GW Z-Wave associated nodes and the video cameras.

• To execute actions in the Z-Wave network and video cameras.

3.3 User interface

The user interface is a visualization layer where the sensor data is monitored and the config- uration rules and the actuation devices are managed. It is developed in HTML5 response mobile, so it is used from a web browser equivalently to a mobile app. The mobile app is available in both Android and iOS operating systems. When a user signs in the 3ollosR website, it launches transparently requests to the back-end. Then, the back-end queries the database and starts to send the sensor data to the web, through the ERS module. These measures are pushed directly to the browser of the user, using MQTT and AJAX asynchronous calls. Thus, the speed of the change diffusion is much higher. The front view of the user interface is a summary of the service performance reported by the back-end, including all reported events, the current state of the devices, the current recording of each camera in the service or the programmed mode. In the Figure 3.15, it can be seen the current recording of the "cam936", the last state received from the smart plugs named as "tele" and "tele habitacion" and the state of the door lock sensors, "puertaentrada2" and "portalr". 54 The 3ollosR service

Fig. 3.15 Front view of the user interface

The configuration of the alerts, camera recordings and actions is directly related withthe back-end rules database and the Master-GW. In the figure3.16 is shown the presentation of this point in a laptop browser and in the mobile app:

Fig. 3.16 Configuration rules on the user interface. Web (left). App (right) 3.3 User interface 55

The provision of the Z-Wave devices and IP cameras is also done through the UI. When the add sensors button is clicked, the Z-Wave dongle in the Master-GW starts to send broadcast association frames and then, the Z-Wave node must be activated to finish the process. It also search in the LAN IP cameras to associate. Analogously, the removal button enable the Master-GW to send broadcast frames to erase configuration of a node in the WSAN, if the node button is pushed, it will beremovedfrom the network. Chapter 4

Development of the WSAN Bridge

As the 3ollosR service is still at an early stage, this project is intended for the future, when the service is well-established in many individual customer homes, and some companies are interested in consuming it. The R Cable’s main purpose is to extend the Z-Wave network over IP, concretely in a LAN environment. This will allow an evolution of the service and adapt it to other end users like as hotels, big buildings or urbanizations. The first approach was to use the ZIPR (Z-Wave over IP Router), a device purchased toSigma Designs in the "Z-Wave Embedded Development Kit". However, the ZIPR was quickly left because it was a reference design for hardware manufacturers and currently it is discontinued. To replace the ZIPR, Sigma Designs asks to the use their property software, Z/IP Gateway SDK on a Linux computer. In fact, Z/IP Gateway was originally developed as the software running on the ZIPR but its support was abandoned after the 1.0 release, and nowadays, the 2.61 release supports many more features as DTLS/UDP encryption. Both, the obsolete ZIPR and the recent Z/IP Gateway software installed on a Linux machine, were controlled through the Z-Ware API. This is a client software which deals with Z/IP Gateway through descriptors for networks, nodes, endpoints and interfaces. This Master’s Thesis goes beyond the simple usage of the Z/IP Gateway specific software and, therefore, a generic solution to expand any kind of WSAN over IP was developed. This solution consists of a LAN master-slave architecture where the slaves let direct access to a serial port where the WSAN dongle is connected. The Master-GW accesses remotely to this port through a bidirectional tunnel where the raw data is exchanged through a secure and reliable stack of protocols. 4.1 Description of the development tools 57

4.1 Description of the development tools

The starter equipment to develop this project is composed by:

• A Z-Wave Embedded Development Kit that includes:

– Access to download center for complete Z-Wave protocol stack and API function. – Development module for easy hardware prototyping. – Application Framework included with sample code libraries. – Developer-friendly instructions, user guides, application notes, and more. – Access to protocol SDK. – License to use Z-Wave technology world-wide. – All hardware needed to develop embedded Z-Wave applications.

• Some Z-Wave nodes, the 3ollosR Master-GW and a CPE.

• An Ethernet Hub, HP AdvanceStack 10Base-T Hub-16U model [37].

• A C.H.I.P. (single-board computer) by Next Thing Co. [38].

Most of the embedded kit content is targeted to Z-Wave end devices manufacturers so, a Z/IP hardware solution, inspired on ZIPR, could be designed. However, one of the requirements for this project was the usage of off-the-shelf devices, as the company did not want to develop specific hardware (which would require technical support and continuous updating). Anyway, the embedded kit contains helpful tools, standing out the Z-Wave RF modules presented in Figure 4.1 or the access to the download center to get the Z-Wave documentation and compatible software.

Fig. 4.1 Z-Wave devices in Embedded Development Kit. UZB (left). ZIPR (right)

On the left of the figure 4.1, there is the UZB [39], a USB v2.0 full speed low power CDC- ACM compliant Z-Wave adapter. This USB device connects a PC or any other computing platform to a Z-Wave network, emulating a serial port over USB. 58 Development of the WSAN Bridge

On the right, there is the ZIPR, the low complexity reference solution to set Z-Wave endpoints in an IP environment. A RJ45 cable is attached to ZIPR enabling it to be plugged to a router or a switch port without any additional cable.

4.1.1 UZB

As all Z-Wave dongles, a Serial API driver is required to use it. The main advantage of the UZB against commercial Z-Wave dongles, is the admission of firmware modifications to change its functionality, while commercial dongles only implements Static Controller. Figure 4.2 shows the block diagram and the PCB of the UZB.

Fig. 4.2 UZB hardware description

As it can be seen on the previous figure, the UZB is based on the SD3503 serial interface SoC, using a 32 MHz crystal, passive RF components, antenna, and regional SAW filter (868.4 EU), making it both cost effective and easy to use. The SD3503 is a MCU with code memory and Z-Wave transceiver firmware running [40]. The Serial Flash is used to store mesh network configuration related to the nodes and routing information, it is connected via SPI to the MCU. The LDO voltage regulator steps down 5V from the USB to 3.3V for the MCU powering without switching noise. The RF implementation is different depending on the ISM radio band legislated on the region where the Z-Wave network is deployed. A low pass filter is incorporated to match the impedance of Helix Antenna as well as reducing emission of high frequency noise. A SAW filter is required to achieve optimal RF performance. The SD3503 firmware is also USB upgradeable using Z-Wave PC Programmer software, available in Sigma Designs download center. The SD3503 also contains a NVRAM which is programmed at factory and not part of the firmware upgrade. Firmware upgrades can change drastically the functionality of the UZB or simply upgrade the Z-Wave SDK version. These firmware images are available in the Sigma Designs download center and they are: 4.1 Description of the development tools 59

• Zniffer: is a Z-Wave frame capturer to diagnostic bugs in the wireless network. It works together with a Windows application, presenting the frames in a graphical user interface on a PC and parsing the different fields.

• Static Controller: is the standard firmware to control a Z-Wave network over a serial interface. This is the basic firmware of all commercial Z-Wave dongles.

• Bridge Controller: works with Z/IP Gateway SDK installed on a computer, typically an embedded kind, conforming a Z/IP Gateway and replacing the ZIPR functionality.

4.1.2 ZIPR

It represents an ideal solution to carry out the project. So, it is important to understand its design directives and its role into the Z-Wave ecosystem. Really, the ZIPR is a discontinued device developed by Zensys Holding Corp, the start-up company that create Z-Wave in 2003 and acquired by Sigma Designs in 2008. The ZIPR hardware design is shown in the figure 4.3. It is also based on SD3503 and its composition is quite similar to the UZB. Its firmware is also upgradeable but only to update the Z-Wave version and the ciphering certificates.

Fig. 4.3 ZIPR hardware description

In the ZIPR stands out a new different element that is the Asix AX11005 Ethernet Controller [41]. It is an Ethernet MCU running on an external 25MHz crystal and it serves as a host controller, communicating via UART to the SD3503. ZIPR is powered by a 5V 500mA DC adapter which is stepped down to 3.3V through a low-dropout (LDO) regulator, the XC6214 [42] (3.3V 500mA). The 3.3V is filtered and supplied to SD3503, AX11005 and the rest of the components (e.g. LEDs, EEPROMS, etc). The 3.3V analog powers for SD3503 and AX11005 are filtered locally before connected to the analog power pins. 60 Development of the WSAN Bridge

4.1.3 C.H.I.P.

Since the ZIPR is a discontinued device, the master-slave architecture is the chosen solution. The Master-GW is already developed over the single-boards presented in the Chapter 3, so it is required a hardware platform to develop the Slave-GW. The C.H.I.P. was chosen because is one of the cheapest and cost-effective Linux single-board computers costing only 9 dollars. It is built around AllWinner R8 SoC, also named A13 [43]. In the next table is compared with the 2 and the Orange-Pi PC.

Table 4.1 Comparison of the 3ollosR boards and C.H.I.P.

Cubieboard2 (eMMC) Orange-Pi PC C.H.I.P. v1.2 SoC AllWinner A20 AllWinner H3 Allwinner R8 CPU (32 bits) ARM Cortex-A7 ARM Cortex-A7 ARM Cortex-A8 Cores 2 4 1 Max. Clock 960 MHz 600 MHz 1 GHz GPU Mali-400 MP2 Mali-400 MP2 Mali-400 MP SDRAM 1 GB DDR3 1 GB DDR3 512 MB DDR3 USB 2 + 1xOTG 3 + 1xOTG 1 + 1xOTG Built-in flash 4GB eMMC - 4GB eMMC External storage microSD + SATA microSD - Ethernet 10/100 10/100 - Embedded Wireless - - BT 4.2 + WiFi N Target Price 56 C 28 C + microSD C 8.15 C Release Date 09/2012 06/2013 12/2015

As it can be seen in the table, this price is quite lower than the other boards and it has enough hardware resources to support the Slave-GW role. It also could be used with other purposes in the future. The appearance of the C.H.I.P. is presented in the Figure 4.4.

Fig. 4.4 C.H.I.P. board 4.1 Description of the development tools 61

Its best advantages are:

• Its cost is affordable for the functionality.

• The eMMC flash makes it robust.

• The wireless interfaces, Bluetooth and Wi-Fi, could be useful.

While its disadvantages are:

• It not includes an Ethernet port.

• It has only one USB port and other USB OTG.

• The R8 SoC lacks of a HDMI-transmitter and a SATA-controller.

This is not the definitive board to implement the Slave-GW, but it is the most cost-effective for this low resource functionality, and this is a good opportunity to test it.

4.1.4 HP J2611B 10Base-T Hub-16U

HP J2611B AdvanceStack Hub-16U is a multiport repeater with 16 twisted-pair network ports. With this hub, Ethernet compliant devices can be connected together making them act as a single network segment. So, signal introduced at the input of any port appears at the output of every port except the original incoming. This hub model is shown in Figure 4.5.

Fig. 4.5 HP J2611B 10Base-T Hub-16U (front view)

Hubs are now largely obsolete in network installations, having been replaced by network switches. This is because hubs only support PHY layer, while switches forward the signal according to the MAC header. However, hubs are useful for network audits. Combined with Wireshark tool, all data transferred in a LAN can be captured and analyzed. The purpose of the hub usage in this case is oriented to capture the IP packets transmitted between the Slave-GW and the Master-GW in any of their implementations, paying special attention on the security and transport layers. The capture scheme to analyze the different solutions is presented in the Figure 4.6. 62 Development of the WSAN Bridge

Fig. 4.6 Scheme for LAN auditions

4.2 Z/IP Gateway management

The initial hope to expand the Z-Wave network over a LAN was to use the ZIPR. It im- plements an obsolete release of the Z/IP Gateway SDK, a software library developed in C language that makes it possible to connect Z-Wave nodes and IP applications via normal IP routing principles. Z/IP Gateways provides the following features:

• Transparent gateway to allow IP applications reach Z-Wave nodes via IP addresses.

• Mapping IPv6 host addresses to Z-Wave node IDs.

• Respond to IP Ping (ICMP Echo) on behalf of Z-Wave nodes.

• Terminate Z/IP Packets originated by IP applications and forward the Z-Wave com- mands to Z-Wave nodes.

The Z/IP packets are used to transport of Z-Wave commands over IP and may carry Z/IP- specific information between network nodes in an IP environment. Concretely, InaLAN environment Z/IP packets are encapsulated over UDP datagrams. 4.2 Z/IP Gateway management 63

Therefore, the Z/IP Gateway is a kind of router implementation. Sending a Z/IP packet to port 4123 of the IPv6 address of the target Z-Wave node will cause the Z/IP Gateway to de-encapsulate the Z-Wave command and forward it to the target node in a Z-Wave frame that forwards Z/IP packets directed to a IPv6 address of a Z-Wave target node. This mechanism is presented in the Figure 4.7.

Fig. 4.7 Z-Wave control via Z/IP Gateway

If the Z/IP Gateway receives a Z-Wave command from that same Z-Wave node within 10 seconds, that Z-Wave command is assumed to be a response to the first command. Therefore, that Z-Wave command is relayed back to the IP host. Certain Z-Wave commands cause a Z-Wave node to return other commands in response to the first command. Z-Wave response commands would be considered unsolicited framesif the Z/IP Gateway was not able to match the original Z-Wave command and the associated response command. The Figure 4.8

Fig. 4.8 Forwarding mechanism of Z/IP Gateway [44]

Z/IP Gateway implements a response-waiting timer to solve this problem. Multiple response- waiting timer instances may exist at the same time. The response frame must be returned to the source IP address and source UDP port of the original Z/IP packet. 64 Development of the WSAN Bridge

4.2.1 Z-Ware

The Z/IP Gateway compliant devices and, therefore the ZIPR, can be managed through Z-Ware, a software stack also provided by Sigma Designs offering a web server to manage different Z/IP Gateways over the LAN. It consists of two abstraction layers conformed by one RESTful API intended to web developers (exporting web API is documented in [45]). The other layer is a C development which interfaces the generation of Z/IP packets, It also offers a test web client to easily control a remote Z-Wave network with a Z/IP Gateway associated. Since the Z-Ware software stack is full compatible with Z/IP Gateway devices, it will be used to test these products through its web user interface (UI). An installation and managing guide of Z-Ware is attached on Appendix A. Summarizing, Z-Ware is a top-level Z-Wave gateway which provides an interface to easily manage Z/IP Gateways exporting an abstracted object-based model to user applications. The Z-Ware application scheme followed to perform the tests is presented in the Figure 4.9.

Fig. 4.9 Z-Ware layer model design

The main Z-Ware features are [46]:

• Network initialization: acquire the Z/IP Gateway IP address in the LAN.

• Network creation and tear down: remotely creates a network with 2 devices, one of them is a controller, while the other can be any type of node.

• Interface monitor/control: once a node is added, the client choose the variable that it wants to monitor or/and control. 4.2 Z/IP Gateway management 65

• Grouping: devices can be grouped for device specific.

• Queuing: automatic command queue for sleeping nodes.

• Firmware updates: to bring the Z/IP Gateway up to date with the latest features or bug fixes.

Z-Ware was used to perform a Z-Wave network node inclusion process in each one of the Z/IP tests. The process was captured with Wireshark to analyze the stack of protocols of the Z/IP packets exchanged.

4.2.2 Z/IP Gateway over the ZIPR

The ZIPR is designed to be connected to the Sigma Designs IoT Portal allowing remote WSAN control over Internet. However, ZIPR can be also controlled from a LAN platform through the Z-Ware and Z/IP APIs.

4.2.2.1 The ZIPR firmware

Since the ZIPR is an obsolete device, it can not support the last Z-Wave updated features but, in order to handle current 3ollosR Z-Wave devices, the last firmware version admitted for the ZIPR is pushed to it, using the PyZIP library. The PyZIP software and the last ZIPR firmware version are obtained from the Sigma Designs download center. To use PyZIP, it is required to install the Python 2.7.3 interpreter version and also the wxPython 3.0 graphical module. The ZIPR firmware design structure, presented in the Figure 4.10, is composed by the Z/IP Gateway firmware running on the AX11005 MCU and the Z-Wave Static Controller Serial API running on the SD3503. Since the firmware updates not requires any kind of authentication, this is considered as a security vulnerability to evil hosts in the LAN. The software design table of the ZIPR shows the software stack and shows some ZIPR important limitations, like it can not cipher UDP packets or that TCP sessions can be only established over the WAN. 66 Development of the WSAN Bridge

Fig. 4.10 ZIPR firmware design

4.2.2.2 Controlling the ZIPR

After pushing the last ZIPR firmware version, it was controlled successfully from theZ- Ware server. In the Figure 4.11, it is shown the correspondent UDP datagrams from a node inclusion process launched by Z-Ware to the ZIPR.

Fig. 4.11 UDP packets captured from a communication between Z-Ware and the ZIPR

As it can be seen, the association process needs at least the exchange of 15 packets between the two LAN hosts. A Wireshark capture of the format of one of these datagrams is exposed in the Figure 4.12, showing all the stack of protocols and addresses of the two hosts. The ZIPR control over UDP result effective but also insecure. Since ZIPR do not support DTLS/UDP encryption, it was tried to establish a TLS/TCP session. Through PyZIP the certificates and direction of the Z-Ware server was configured. However, this hasnotbeen achieved. Figure 4.13 shows the ZIPR trying to establish this session with the Z-Ware host in the LAN. 4.2 Z/IP Gateway management 67

Fig. 4.12 Format of an UDP datagram captured between Z-Ware and a ZIPR

Although different certificates were pushed on Z-Ware and ZIPR, this TLS/TCP ciphered session never was established. So, after query the Sigma Designs support, it was concluding the ZIPR can not handle any kind of encryption in the LAN. In the figure 4.13 it is shown the refused response in the TCP session establishment.

Fig. 4.13 ZIPR trying to establish a TLS/TCP session

The ZIPR was an interesting initial proposal but since it can not handle TLS/TCP encrypted LAN sessions neither DTLS/UDP encryption, it is not valid for this purpose. 68 Development of the WSAN Bridge

4.2.3 Z/IP Gateway in a Linux machine

The ZIPR supports a deprecated version of Z/IP Gateway but, newest versions of this software are available in the Sigma Designs and they are compilable for many Linux distributions. This allows to understand quite better the software design of the Z/IP Gateway. The objective of this section is to run Z/IP Gateway and use the UDP with DTLS encryption over the LAN to manage a Z-Wave network associated to a Z/IP Gateway. In the Appendix B, there are explained all steps followed to compile, install and use Z/IP Gateway application over a Linux operative system (concretely it has been used an Orange-Pi PC). Z/IP Gateway requires an Ethernet connection and access to the raw Ethernet frames which are achievable using a Linux TAP/TUN driver. The Z-Wave network is reached through a Z-Wave Serial API UZB dongle connected to a host USB port. However, the firmware required in this dongle can not be the classic Static Controller, it must be a Bridge Controller firmware which is only runnable over the Sigma Designs UZB dongle. The UZB firmware can be upgraded through the Z-Wave PC Programmer, a Windows application provided by Sigma Designs. This step is very simple, it is only required to install the Windows version of the CP210x USB-to-UART driver to handle the UZB through the application [32].

4.2.4 Managing Z/IP Gateway

Unlike the ZIPR, data exchanged between Z-Ware and Z/IP Gateway was successfully secured using both DTLS/UDP. To achieve this, a preconfigured PSK is shared in both hosts. For simplicity it is used the default configured in the Z/IP Gateway (see Appendix B). This PSK is introduced through the Z-Ware Web UI and then, both hosts can perform the DTLS handshake as it is shown in the Figure 4.14

Fig. 4.14 DTLS handshake between Z-Ware and Z/IP Gateway 4.3 Generic LAN bridge implementation 69

The rest of the Z/IP packets exchanged between Z-Ware and Z/IP Gatewa are now ciphered using the minimum possible computing resources, so this is an optimal solution. The format of one of these ciphered datagrams is shown in the Figure 4.15.

Fig. 4.15 Format of a DTLS packet captured between Z-Ware and a ZIPR

The Z/IP packets were also encrypted using TCP/TLS. The configuration done to achieve this was simply an exchange of the trust certificates between the Z/IP Gateway and Z-Ware.

4.3 Generic LAN bridge implementation

The principle of this experiment is very simple. It consists in accessing the port of the Slave-GW, where the Z-Wave dongle is connected, in the same way as direct connected to the Master-GW. To achieve this, the serial port must be tunneled through a LAN. When a dongle is connected to a Linux device host, it is seen by the operative system as a "tty" This abbreviation is referred to a past concept, the "Teletype", the 1920’s oldest computers. The computer considers each serial port to be a "device", most commonly called a terminal device since at one time terminals were the most common use for a serial port. 70 Development of the WSAN Bridge

For each such serial port there is an special file in the /dev directory. So, after the connection process, the WSAN dongle is attached to a serial port device "/dev/ttyXX". There are different solutions to achieve the remote use of a serial port. There is presented the evolution of the implemented methods below.

4.3.1 Ser2net and Socat

The first approach was based on the article [47] using the following Linux tools:

• Ser2net: allows Telnet and TCP sessions to be established with the serial ports of a unit. The program comes up normally as a daemon, opens the TCP ports specified in the configuration file, and waits for connections. Once a connection occurs, the program attempts to set up the connection and open the serial port. If another user is already using the connection or serial port, the connection is refused with an error message [48].

• Socat: establishes two bidirectional byte streams and transfers data between them. These byte streams can be constructed from a large set of different types of data sinks and sources. Socat is very versatile and can be used for multiple purposes, admitting the use of different protocols and ciphers [49].

The application of these tools is intended to create a virtual serial device on the Master-GW (using socat) which connects to a remote serial device on the Slave-GW (ser2net). This allows using existing software working on the Slave-GW with a Z-Wave dongle without adaption of the source code. This scheme is attached on the Figure 4.16. With this configuration, the OpenZWave driver is been cheated because it is sending theraw Z-Wave frames through a TCP socket as if it were local serial port. This is done modifying a OpenZWave configuration file where the serial port of the dongle is established. Of course, a description of the transmission parameters required by the UART to manage the dongle has been attached on the Slave-GW according to the Static Controller documentation:

• Baudrate [baud/s]: 115200.

• Parity: None.

• Stop Bits: 1.

• Data Bits: 8. 4.3 Generic LAN bridge implementation 71

Fig. 4.16 Remote serial implementation with Ser2net

The following steps to establish this tunnel are explained in the Appendix C.1.

4.3.2 Encrypting the data stream

Ser2net is a quick and convenient solution which is very easy to setup. However, it does not supports any kind of encryption. So, this step is an improvement of the last experiment to achieve a secure tunnel implementation. Since Socat is a bidirectional relay for data streams and supports different encryption methods, it can also be used on the Slave-GW as a substitution for Ser2net. The encryption performed is based on RSA-1024 public-key certificates created with OpenSSL [50]. OpenSSL is used in order to generate private keys and trust certificates for the Master-GW and all the Slave-GWs. This was based on the tutorial found in this article [51]. The procedure of this experiment (detailed in Appendix C) consists of create a public/private key pair for the Master-GW and other for the Slave-GW. From these, it was created the self signed certificates used in the authentication process. For simplicity, it was obtained two PEM files appending the private key and certificate files. An additional configuration was required in the key of the Master-GW. This involves the appending of a Diffie-Hellman key following the private and public key stored in the PEMfile. 72 Development of the WSAN Bridge

Fig. 4.17 Remote serial implementation with encryption

It is used in the establishment of the tunnel. Finally, these files are stored in the Master-GW and Slave-GW as it is shown in the Figure 4.17. The mechanism for the TLS/TCP socket establishment is:

1. The Master-GW starts to listen in the TLS/TCP well-known port attached to a virtual serial port "/dev/ttyRMT".

2. The Slave-GW starts a connection to the Master-GW IP.

3. After the authentication process a common key is shared to cipher each packet.

4. The tunnel is "kept-alive" during the process.

The TLS handshake is captured with Wireshark. It is shown in the Figure 4.18.

Fig. 4.18 TLS handshake between the Master-GW and Slave-GW

This configuration steps and the commands used are described in the Appendix C.2. 4.3 Generic LAN bridge implementation 73

4.3.3 Final prototype

The TLS/TCP tunnel satisfies the Z-Wave timing and the used Linux boards (the Cubieboard2 as the Master-GW and the C.H.I.P. as the Slave-GW) support it without any problem. However, in a bigger scenario DTLS/UDP is much more scalable, since it will require less resources per tunnel. Since the DTLS/UDP tunneling will require an specific software development because the socat tool really does not support it, the R Cable’s innovation directive has reduced the priority to the implement the DTLS/UDP tunnel because, nowadays it is not priority and for now on, the TLS/TCP tunnel is useful. The final prototype designed consists of an additional configuration of the master-slave architecture. This involves a plug-and-play capability to automatically establish the TLS/TCP tunnel, allowing the Master-GW to achieve the Slave-GW without any kind of provision process. The Linux top-level software tools used in the final design are presented in previous sections: socat and openssl; and also udev, ping and arp, below presented.

4.3.3.1 Recognizing the Z-Wave dongle

This section explains the configuration and the tools involved to recognize and control the plugging process of a dongle in a Linux machine. Specifically, the device controlled is the Aeon Z-Stick dongle and the target machine is the Slave-GW. When a device is plugged into a Linux machine, the kernel usually just assigns unpredictable device names based on the order of discovery. Meaningful symlinks or network device names provide a way to reliably identify devices based on their properties or current configuration. Udev supplies the system software with device events, manages permissions of device nodes and let the creation of additional symlinks in the "/dev" directory, or renames network interfaces [52]. Therefore, to control the actions performed by the Linux operative system when a device is plugged-on, a rules file is added in the directory "/etc/udev/rules.d". Using the udev tool, two rules are created in order to publish a connected Z-Stick and to unpublish it when disconnected. If the action is a connection:

1. Identify the idVendor and idModel of the device connected. 74 Development of the WSAN Bridge

2. If this match with the target, link the device assigned by the kernel with a fixed name link "/dev/ttyzstick".

3. Perform another actions referred to the encrypted tunnel.

If the action is a disconnection:

1. Identify the idVendor and idModel of the disconnected device.

2. If this match with the target, remove the link previously assigned "/dev/ttyzstick".

3. Kill the socat process.

The entries in the udev rules file, helpful commands or additional configuration details are attached in the Appendix C.3.

4.3.3.2 Auto-connection script

In this section it is explained the Bash-programmed script executed after recognizing a well-known device plugged in the Slave-GW. The objective is to identify the previously unknown IP of the Master-GW since it is dynamically assigned by the DHCP server running on the CPE. This IP is obtained from the MAC address of the Master-GW. Concretely, from the known Vendor ID (associated with Telecon Galicia), which is implicit in the first three bytes of the MAC address. Initially, the IP-MAC mapping of all hosts in the same subnet than the Slave-GW had to be obtained with nmap (Network Mapper) package. However, it presents problems to obtain the MAC addresses of the hosts when it was integrated in the C.H.I.P.. Due to this fact, the network map was obtained through the ping and arp packages. The strategy consists in pinging the broadcast address of the network to obtain the IP addresses of the hosts in state IP. Then, through the ARP package the MAC address is obtained from the router in the gateway interface of the subnet. The IP-MAC map is obtained is matching the known Vendor ID and the IP of the Master-GW. Then, the TLS/TCP connection is launched to this IP and previously assigned port. Logically, the Master-GW is already listening in this port, awaiting for a connection 4.3 Generic LAN bridge implementation 75

4.3.3.3 Disconnection script

This is script is much simpler than the plugging script. It only consists in to kill the socat associated processes and remove the "/dev/ttyzstick" associated file Chapter 5

Conclusions

The Smart Home platforms are very complex since several technologies are involved. As a telecommunications engineer, the convergence of these technologies including wireless communications, smart transducers, embedded systems, cloud computing, big data, real-time analytics or machine learning, results very attractive. Regarding the initial objective of the integration of the ZIPR in 3ollosR to bridge the Z-Wave and the IP network, it was quickly evolved since it is was an abandoned design by the manufacturers. However, it was a very interesting approach since it make it possible to reach the Z-Wave nodes through IPv6, enabling IP applications to achieve them. Sigma Designs now supports the Z/IP Gateway software instead of the ZIPR device. This means that the Sigma Designs business strategy nowadays is to sell software products for different hardware platforms, enabling the IP access to the Z-Wave environment. However, the R Cable’s perspective is to integrate open-source solutions and not to be limited to the Z-Wave technology. For that reason, the acquisition of the Z/IP Gateway software is not contemplated and other solutions were investigated. The Master’s Thesis presented a master-slave gateway architecture that accomplishes each one of the initial objectives and has many advantages:

• Fully open-source and not limited to any technology.

• Simple design that can be adapted to other platforms

• Minimum modifications on the current software.

• Useful also to extend the service over Internet. 5.1 Future work 77

Regard to the use of the C.H.I.P. board as the Slave-GW, it was working over Wi-Fi without any problem. This is a interesting notice because it means this architecture can be adopted in an environment with a Wi-Fi extensor or a Wi-Fi PLC, which are currently been used in some scenarios to extend the coverage of the 3ollosR Wi-Fi cameras. But not all the conclusions are positive. Since the currently 3ollosR gateway is a massive implanted centralized solution, the adoption of a master-slave architecture may be not cost- effective. There are several issues that may reduce the success of this solution:

• Logistic matters related to the new hardware solutions.

• The need to manage different software solutions for the Master-GW and the Slave-GW.

• The need to design an enclosure for the Slave-Gw clearly differentiated from the current one of the Master-GW.

• The need to train installers to support the setting up of the Slave-GW.

• The support for a new type of incidences.

Nevertheless, these problems will appear with any new solution.

5.1 Future work

Logically, this solution will require more development and design analysis in the future. Some of the main development topics are the following,

5.1.1 Better integration of the Slave-GW in the 3ollosR environment

The control of the Z-Wave nodes is handled by the OpenZWave driver which is also managed by another higher level software developed by Cinfo. This software is in charge of translating the object-based JSON format used for the communications with the back-end into the OpenZWave addressing format and vice versa. This software only contemplates the control of one Z-Wave network i.e. it only is prepared to use one HomeId. This supposes a problem to the Z-Wave network extension because it only can allocate 255 nodes. The solution is to modify the Cinfo-developed source code to handle a map of Home Id instead of only a variable with a single HomeId. 78 Conclusions

5.1.2 Evolution of the Slave-GW

The Slave-GW can evolve in two ways. The first is a minimalist design over a lightweight operating system and a low resource hardware. The second is to amplify its software scope and start to produce an object-based model.

5.1.2.1 Minimalistic design

It is required to elect a lightweigh platform such as Contiki, TinyOS, FreeRTOS, mbed OS or RIOT. It will be important to implement the DTLS/UDP stack of protocols to optimize the computing resource consumption. Currently, there are many implementations of the TLS and DTLS protocols presented in table 5.1 extracted from the article [53]. The idea is to deploy this of them over the chosen platform, prefering the DTLS 1.2 lastest version.

Table 5.1 Some of the current libraries with DTLS support

Library DTLS 1.0 DTLS 1.2 Botan Yes Yes GnuTLS Yes Yes libsystools Yes No LibreSSL Yes No mbed TLS Yes Yes MatrixSSL Yes Yes OpenSSL Yes Yes Network Security Services Yes Yes SChannel 10 Yes Yes PyDTLS Yes Yes tinydtls No Yes wolfSSL Yes Yes

5.1.2.2 Fog Computing interpretation

Attending to the Fog Computing paradigm, the computing layer nearest the smart devices executes a first object-modeling software, introducing a first abstraction layer fromthe implementation end-points. This can be complemented with a publish-subscribe protocol such as MQTT-SN (the light version of the MQTT protocol for sensor networks). References

[1] IEEE Standard for a Smart Transducer Interface for Sensors and Actuators - Network Capable Application Processor (NCAP) Information Model, IEEE Instrumentation and Measurement Society’s Sensor Technology Technical Committee, 05/1999.

[2] M. B. Irina-Ioana Patru,˘ Mihai Carabas, and L. Gheorghe, IEEE article: Smart Home IoT System, University Politehnica of Bucharest, 2014. [3] I. A. G. Tércio A.S. Filho, Alexandre C. da Silva and S. R. Rossi, IEEE article: Network Node With Wireless and Wired Interfaces. Nios II processor and uClinux to development of a NCAP embedded (IEEE 1451.1) with two interfaces, wireless (IEEE 1451.5) and wired (IEEE 1451.2), São Paulo State University, University of Limerick and Universidad Nac. del Centro Prov. de Buenos Aires, 2011. [4] Intel Edison Compute Module Rev 5, Intel, 06/2016. [5] Web resource: Android Things, Google, https://developer.android.com/things/index.html. [6] Web resource: Weave, Google, https://developers.google.com/weave/. [7] DE2 Development and Education Board V 1.4, Altera, 2016, Online. [8] Nios II Classic Processor Reference Guide, Altera, 06/2016, Online. [9] J. Dionne and M. Durrant, Web resource: uClinux, Arcturus Networks, 05/2016, http://www.uclinux.org/index.html. [10] Cyclone II Device Handbook, Volume 1, Altera, 02/2017, Online. [11] X. V. T. W. L. A. G. G. B. Maria Rita Palatella, Nicola Accettura and M. Dohler, IEEE Communications Surveys and Tutorials: Standardized Protocol Stack of the Internet of (Important) Things, IEEE Communications Society, 08/2013. [12] RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2, IEEE Network Working Group, 08/2008, Online. 80 References

[13] RFC 6347: Datagram Transport Layer Security (DTLS) Version 1.2, IEEE Network Working Group, 01/2012, Online. [14] C. B. (Cisco) and R. S. (Intel), OpenFog Reference Architecture for Fog Computing, OpenFog Consortium, 02/2017, Online. [15] C. Corsi, Smart Sensors: Why and when the origin was and why and where the future will be, Consorzio C.R.E.O., 2013. [16] IEEE Standard for a Smart Transducer Interface for Sensors and Actuators - Com- mon Functions, Communication Protocols, and Transducer Electronic Data Sheet (TEDS) Formats, IEEE Instrumentation and Measurement Society’s Sensor Technology Technical Committee, 2007. [17] IEEE Standard for a Smart Transducer Interface for Sensors and Actuators - Wireless Communication Protocols and Transducer Electronic Data Sheet (TEDS) Formats, IEEE Instrumentation and Measurement Society’s Sensor Technology Technical Com- mittee, 08/2007. [18] ITU-T G.9959: Short range narrow-band digital radiocommunication transceivers - PHY, MAC SAR and LLC layer specifications, Sigma Designs, 01/2015, Online. [19] N. S. Abhinandan Aggarwal, Gagandeep Singh, Implementation of AES algorithm, International Journal of Engineering Research and Science (IJOER), 4/2016, Online. [20] E. N. Alexander Larsson, Comparison of IoT frameworks for the smart home, Depart- ment of Electrical and Information Technology, Faculty of Engineering, LTH, Lund University, 2016, Online. [21] Diffie–Hellman key exchange, Computer Science and Engineering of the University of North Texas, Online. [22] Web Resource: AllJoyn, AllSeen Alliance, https://allseenalliance.org/framework/documentation. [23] Web resource: IoTivity, Open Connectivity Foundation, https://wiki.iotivity.org/. [24] P. Tracy, Web resource: IoT Cloud Providers, RCR Wireless News, 09/2016, http://www.rcrwireless.com/20160906/telco-cloud/iot-cloud-providers-tag31-tag99. [25] Web resource: Microsoft Azure, Microsoft, https://azure.microsoft.com. [26] Web resource: Google Cloud, Google, https://cloud.google.com/?hl=en. [27] Web Resource: Public-key cryptography, Wikipedia, https://en.wikipedia.org/wiki/Public-key_cryptography. References 81

[28] ISO/IEC PRF 20922 Message Queuing Telemetry Transport (MQTT), Andy Stanford- Clark and Arlen Nipper (Cirrus Link), 06/2016. [29] Data Sheet: H3, CO, 4/2015, Online. [30] S. Aritome, NAND Flash Memory Technologies. Wiley-IEEE Press, 2016. [31] Z-Wave ZW0201/ZW0301 Appl. Prg. Guide v5.03.00, Sigma Designs, 04/2011. [32] AN978: CP210x USB-to-UART API Specifications, Silicon Labs, Online. [33] Nmap Network Scanning: The Official Nmap Project Guide to Network Discovery and Security Scanning, Nmap Project, 01/2009. [34] S. S. Laurent, Introducing Erlang Getting Started in Functional Programming. O’Really Media, 01/2013. [35] Mnesia 4.14.3, Ericsson, 03/2017, Online. [36] EMQ - Erlang MQTT Broker, The Open Community, Online. [37] HP AdvanceStack 10Base-T Hub-16U, Hewlett Packard, 02/1996, Online. [38] C.H.I.P. documentation, Next Thing Co., 02/1996, Online. [39] Product Manual: UZB, Sigma Designs, 10/2016. [40] Data Sheet: SD3503, Sigma Designs, 08/2015. [41] Data Sheet: AX11001/AX11005 Single Chip Microcontroller with TCP/IP and 10/100M Fast Ethernet MAC/PHY, Asix Electronics Corporation, 5/2007, Online. [42] Data Sheet: XC6214, Torex, 11/2014, Online. [43] Data Sheet: R8, Allwinner Technology CO, 3/2015, Online. [44] SDS11468-3: Z/IP - Z-Wave for IP; Gateway Requirements, Sigma Designs. [45] INS12902-5: Z-Ware Portal: Web Developer’s Guide, Sigma Designs. [46] Z-Ware CE: Web Developer’s Guide, Sigma Designs, 08/2016. [47] N. Bernaerts, Web Resource: RFXtrx433 - Access your Remote USB transceiver plugged to an OpenWRT device, 04/2017, http://bernaerts.dyndns.org/ nas/342-rfxtrx433-openwrt-remote-usb-transceiver. 82 References

[48] C. Minyard, Web Resource: Ser2net man page, https://linux.die.net/man/8/ser2net. [49] G. Rieger, Web Resource: Socat man page, https://linux.die.net/man/1/socat. [50] T. H. Eric Young, Web Resource: OpenSSL, https://www.openssl.org/. [51] G. Rieger, Web Resource: Securing Traffic Between two Socat Instances Using SSL, 2007, http://www.dest-unreach.org/socat/doc/socat-openssltunnel.html. [52] K. S. Greg Kroah-Hartman, Dan Stekloff, Web Resource: Udev man page, https: //linux.die.net/man/8/udev. [53] Web Resource: Comparison of TLS implementations, Wikipedia, https://en.wikipedia. org/wiki/Comparison_of_TLS_implementations#Protocol_support. Appendix A

Z-Ware Web Server

The following steps describes how to compile, install and manage the Z-Ware Web Server over a 32 bit version of Ubuntu 14.04 (Trusty). The Z-Ware installation source files were obtained from the Sigma Designs website compressed under the file zwportal.tar.gz.

A.1 Compiling Z-Ware Web Server

1. Installing dependencies: $ sudo apt −get install make cmake libtool autoconf openjdk −7− jre g++ unzip pkg−config patch gettext l i b g l i b 2 .0− dev zlib1g zlib1g −dev flex bison

2. Uncompressing the zwportal sources tarball: $ t a r −xzvf zwportal.tar.gz

3. Changing to the directory where the zwportal sources are uncompressed: $ cd /home//zwportal

4. Running build script with the local option: $ ./build/build.sh l o c a l 84 Z-Ware Web Server

A.2 Installing Z-Ware Web Server:

1. Extracting the contents of the installer: $ t a r −zxvf zwarelocal −i386.tar.gz

2. Starting installation specifying the deployment path: $ ./install.sh

3. System settings are prompted including FQDN hostname, rotate size of the logs, web timeouts, Secure HTTP usage, settings of SMTP, LDAP, IFTTT or certificates of the website. In this case, settings will be left as default.

A.3 Starting the service:

1. Changing to deployment directory: $ cd

2. Starting all services: $ ./service/service.sh start

A.4 Controlling Z-Ware Web Server:

1. Accessing the Z-Ware Web Server UI though a web browser (by localhost or the hosting server local) and insert default credentials user:sigma password:sigmadesigns (Figure A.1).

2. Checking Z-Ware version (Figure A.2).

3. Checking if Z-Ware identifies a Z/IP Gateway, such as ZIPR, in its LAN (Figure A.3).

4. Starting a Z-Wave node inclusion in the Z/IP Gateway (Figure A.4).

5. Activating Z-Wave node inclusion process and check node inclusion (Figure A.5). A.4 Controlling Z-Ware Web Server: 85

Fig. A.1 Sign in Z-Ware local website

Fig. A.2 Version of the Z-Ware Web Server 86 Z-Ware Web Server

Fig. A.3 Z/IP Gateway on LAN detected by Z-Ware Web Server

Fig. A.4 Activate node inclusion mode on Z/IP Gateway A.4 Controlling Z-Ware Web Server: 87

Fig. A.5 Added node detected in the Z-Ware Web Server Appendix B

Z/IP Gateway

The following steps describes how to compile, install and manage Z/IP Gateway over a a Orange-Pi PC. However, Z/IP Gateway can be compiled over any ARM Linux kernel. The source files were obtained from the Sigma Designs website compressed under thefile zipgateway-2.61.0-source.tar.gz. The information collected in this appendix are half from Sigma Designs docs and the other half obtained from the experience.

B.1 Compiling and installing Z/IP Gateway:

In this first step, there are two mainly possibilities: native compiling and cross compiling. For simplicity, the following method was native compiling but, since ARM-architecture boards has lower computing resources than a current personal computer, this will require more time. The compiling is need because Sigma Designs only offers an installation for Raspberry Pi. However, in order to use zipgateway in other ARM platforms, it is needed to perform a specific compilation from the source code files.

1. Remote login the Orange-Pi PC: $ ssh root@

2. Updating repositories: $ sudo apt −g e t u p d a t e B.1 Compiling and installing Z/IP Gateway: 89

3. Installing dependences: $ sudo apt −get install libusb −1.0−0−dev radvd flex dhcp−helper parprouted bridge −utils bison gcc liblockdev1 libc6 −dev l i b s s l −dev

4. Compiling cmake 3.9.0 version (not available on repositories):

(a) Download it: $ wget https ://cmake.org/files/v3.9/cmake −3.9.0 − r c 3 . t a r . gz

(b) Uncompress the cmake sources tarball: $ t a r −xzvf cmake −3.9.0 − r c 3 . t a r . gz

(c) Change to the directory where the cmake sources are uncompressed: $ cd cmake −3.9.0 − r c 3

(d) Run build and install scripts giving it execution permissions previously: $ chmod +x bootstrap $ ./bootstrap $ make $ make install

5. Uncompress the zipgateway sources tarball: $ t a r −xzvf zipgateway −2.61.0 − source . t a r . gz

6. Change to the directory where the zwportal sources are uncompressed: $ cd /home//zipgateway −2.61.0 − source / u s r / l o c a l

7. Create build directory and change to it: $ mkdir build $ cd b u i l d

8. Run cmake and make: $ cmake . . $ make $ make package 90 Z/IP Gateway

B.2 Configuring Z/IP Gateway:

Now Z/IP Gateway can be launched with the next command: $ zipgateway − [− f l o g ] [−e eeprom ] [−s /dev/ttyXXX ] [−c c f g f i l e ] [− t t u n f i l e ]

The command line options will override the options in the default configuration file. The information attached below is extracted from the zipgateway man page.

• -f logfile: if this option is set, all communication between the Z-Wave module and the Z/IP Gateway application is logged into the logfile. Default behavior is no logging.

• -e eeprom.dat: the Z/IP Gateway needs a file to store learned network data. This file should be located on a writable non-volatile partition. The eeprom file willbe generated if it does not exist. Defaults to .I /etc/eeprom.dat

• -s /dev/ttyXXX: the serial port to which the Z-Wave serial API is connected. The Serial API connected should be of the type "Bridge Library".

• -c cfgfile: the configuration file read by the application Defaults to /usr/local/etc/zip- gateway.cfg

• -t tunfile: location of the tunnel setup script Defaults to /usr/local/etc/zipgateway.tun

B.2.1 Z/IP Gateway configuration file

The zipgateway configuration file is used to customize the Z/IP Gateway behavior. Entriesin the configuration file are written in a simple key=value format. The default location ofthe configuration file is /usr/local/etc/zipgateway.cfg. It is composed by the next entries:

• ZipSerialAPIPortName: serial port device name.

• ZipUnsolicitedDestinationIp6: IPv6 address to forward unsolicited commands which are Z-Wave command classes which are not handled by the Z/IP gateway.

• ZipUnsolicitedDestination2Ip6: A secondary unsolicited destination. B.2 Configuring Z/IP Gateway: 91

• Port Destination UDP: port to use when sending unsolicited commands. Default: 4123.

• SerialLog: log file for serial communication. Used for debugging. If this option isnot set the no logging is done.

• ZipCaCert: CA certificate location of the portal provider.

• ZipCert: Z/IP Gateway public certificate.

• ZipPrivKey: Z/IP Gateway private key.

• Eepromfile: location of eeprom file. The eeprom file must be stored in a non-volatile location.

• TunScript: location of the tun script. Default: /usr/local/etc/zipgateway.tun

• ZipPanIp6: IPv6 prefix of the Z-Wave network. All Z-Wave nodes will be assigned an IPv6 address in this prefix. The host system should make sure to establish arouteto this prefix via the ZipLanIp6. The default value is the 0::0 address, which meansthat the Z/IP Gateway.

• ZipLanIp6: IPv6 address of the Z/IP Gateway. This is LAN IP6 address of the Z/IP Gateway. This is the address which should be used when communicating with the Z/IP Gateway. This address should also be the target address of the route to the Z-Wave network.

• ZipLanGw6: IPv6 default gateway which the Z/IP Gateway will use, when sending outside the LAN or PAN.

• ZipPortal: IPv4 address of the gateway portal. The portal is a sort of a VPN host which transports IPv6 packages inside a TLS encrypted TCP tunnel. If not set the Z/IP Gateway runs without a portal.

• ZipPortalPort: TCP port to use when connecting to a remote portal. Default: 44123.

• ZipTunPrefix: prefix of the network on the other side of the tunnel. The Z/IPGateway will send all packages with destination within this prefix through the tunnel.

• ZipTunIp6PrefixLength: The length of the tunnel prefix. Default: 128.

• ZipManufacturerID: ID to set in the version report. Default: 0. 92 Z/IP Gateway

• ZipHardwareVersion: hardware version to set in the version report. Default: 1.

• ZipProductID: ID to set in the version report. Default: 1.

• ZipProductType: ID to set in the version report. Default: 1.

• ZipMBPort: destination port for Mailbox proxy. Default: 41230.

• ZipMBDestinationIp6: IP of Mailbox proxy service. Default: None.

• ZipMBMode: mode of operation of Mailbox proxy. 3: Disable Mailbox. 2: Use the Z/IP Gateway’s own Mailbox functionality. 1 :Use a Mailbox proxy service to store Mailbox messages. Default: 1.

• ZipPSK: pre shared key used in DTLS connection. Default: None.

• ExtraClasses a space separated set of command classes the Z/IP Gateway should present in its node info frame. Command class numbers must be given in decimal, or in hex preceding 0x, ie. 0x65. Version command class get frames with one of these command classes will be forwarded to the unsolicited destination.

B.3 Running DTLS between Z/IP Gateway and Z-Ware

An identical DTLS PSK must be configured in the Z/IP Gateway configuration file andin the Z-Ware web client through the web resource "/ui/eng/settings.shtml" as it shown in the Figure B.1.

Fig. B.1 Z-Ware Web Client DTLS PSK introduction B.3 Running DTLS between Z/IP Gateway and Z-Ware 93

Fig. B.2 Z/IP Gateway DTLS PSK on configuration file

The PSK in the configuration file of Z/IP Gateway is shown in the Figure B.2. By simplicity the default PSK is kept. Appendix C

Implementation of the master-slave WSAN bridge architecture

This following guide explains how to install the system built in this Master’s Thesis. This system can be deployed over every Linux distribution. The sections are divided in function of the experiments done with a progression until the final prototype.

C.1 Socat and Ser2net

This was the first test and the easiest. The implementation is basically divided intothe Master-GW and the Slave-GW configurations.

C.1.1 Slave-GW

The serial device representing the dongle connection is linked with a TCP socket:

1. Install the ser2net packet. $ sudo apt −get install ser2net

2. Start to listen in the TCP socket, associating it with the serial port where the dongle is connected. $ ser2net :raw:0:/dev/ttyUSB0:115200 NONE 1STOPBIT 8DATABITS C.1 Socat and Ser2net 95

3. This is ready to receive a TCP connect in the port .

C.1.2 Master-GW

The strategy is to cheat the OpenZWave driver to associate a virtual serial device with a network socket instead of a real USB physical serial port.

1. Install the socat command. $ sudo apt −get install socat

2. The link with the virtual serial port and a TCP socket without encryption can be established. The command is composed by two arguments associated with the two data streams. This is a single command separated with a blank space (not line break). $ socat pty,raw, echo =0,link=/dev/ttyRMT tcp::

3. Add a crontab entry to launch it periodically (each hour). $ c r o n t a b −e 0 ***** /bin bash socat pty,raw, echo =0,link=/dev/ttyRMT tcp::

4. Change the OpenZWave targeting serial port. The Figure C.1 shows the line modified. $ sudo nano /opt/core/openzwave/provision.json

Fig. C.1 Changing the serial port in OpenZWave 96 Implementation of the master-slave WSAN bridge architecture

C.2 Final prototype

Since the final prototype uses a TLS/TCP tunnel, that experiment was integrated directly into the final prototype.

C.2.1 Generation of the certificates

The public/private keys and the self signed certificates are generated in each one of the two hosts with OpenSSL and then, the self signed certificates are exchanged between them. Unlike the previous experiment, now the server is the Master-GW and the client, the Slave- GW.

C.2.1.1 Slave-GW

1. Install the OpenSSL tool. $ sudo apt −get install openssl

2. Generate a public/private key pair. $ openssl genrsa −o u t s l a v e −gw . key 1024

3. Generate a self signed certificate. $ openssl req −new −key s l a v e −gw . key −x509 −days 3653 −o u t s l a v e −gw . c r t

A prompt appears requiring parameters country code, name or region. These parameters are simply skipped because they are not needed.

4. Generate the PEM file by just appending the key and certificate files. $ c a t s l a v e −gw.key slave −gw.crt > slave −gw . pem

5. Remove the not needed files, exchange the self signed certificate and store thepub- lic/private key pair with the self signed certificate appended. $ sudo scp @: s l a v e −gw . c r t $HOME/ e t c $ rm s l a v e −gw.key slave −gw . c r t $ mkdir $HOME/etc/ $ mv s l a v e −gw . pem $HOME/ e t c C.2 Final prototype 97

C.2.1.2 Master-GW

1. Install the OpenSSL tool. $ sudo apt −get install openssl

2. Generate a public/private key pair. $ openssl genrsa −o u t master −gw . key 1024

3. Generate a self signed certificate. $ openssl req −new −key master −gw . key −x509 −days 3653 −o u t master −gw . c r t

A prompt appears requiring parameters country code, name or region. These parameters are simply skipped because they are not needed.

4. Generate the PEM file by just appending the key and certificate files. $ c a t master −gw.key master −gw.crt > master −gw . pem

5. An additional step is required in order to perform the Diffie-Hellman asymmetric key exchange in the server side.

6. Remove the not needed files, exchange the self signed certificate and store thepub- lic/private key pair with the self signed certificate appended. $ sudo scp @: master −gw . c r t $HOME/ e t c $ rm master −gw.key master −gw . c r t $ mkdir $HOME/etc/ $ mv master −gw . pem $HOME/ e t c

C.2.2 Udev rules

This section involves the enabling of the plug and play to execute the tunneling script in the Slave-GW when the Z-Wave dongle is connected. To use the udev tool the file "90-usb.rules" is created into the "/etc/udev/rules.d" with two entries correspondent to the plug and unplug actions. The syntax of these lines is: 98 Implementation of the master-slave WSAN bridge architecture

$ c a t /etc/udev/rules .d/90− usb . r u l e s

ACTION=="add" , ATTR{idVendor}=="10c4" , ATTR{idProduct}=="ea60" , RUN+="/ bin /sh /usr/local/bin/plug_zstick.sh"

KERNEL==" * " , SUBSYSTEM==" usb " , ENV{PRODUCT}== " 10 c4 / ea60 /100 " , ACTION=="remove" , RUN+=" / bin / sh /usr/local/bin/unplug_zstick.sh"

To obtain the USB parameters, they were used the udevadm tools allowing the design of the rules. Also, it is required to give execution permission to the "90-usb.rules" file.

1. To see the changes happened when plug/unplug a device. $ udevadm monitor −−p r o p e r t y

2. To reload the udev configuration after a change in the rules file. $ sudo udevadm control −−r e l o a d −r u l e s

3. To give execution permission to the rules file. $ sudo chmod +x /etc/udev/rules.d/90− usb . r u l e s

4. Finally, the following line was added in the file "/root/.profile" in order that they need the maximum permissions to be executed. This accomplish the restart of the USB driver in the boot of the computer just like the dongle is connected in this moment. echo "1" > /sys/devices/platform/soc@01c00000/ 1c14400.usb/usb2/bConfigurationValue

In older kernels this file could be "/etc/rc.local" or "/home/user/.bashrc".

C.2.3 The auto-tunnel establishment

C.2.3.1 Slave-GW

After the udev tool recognize the targeted USB plugged (or unplugged) a bash script is run. The "plug-zstick.sh" script accomplish the link of the serial device assigned by the kernel to another fixed virtual device. It also performs the search of the IP of the Master-GW fromthe C.2 Final prototype 99

Vendor ID of Telecom Galicia, and the establishment of the TLS/TCP tunnel with the virtual device link. This procedure is programmed in the following Bash-code lines. # ! / b i n / sh

PATH=/ u s r / l o c a l /sbin:/usr/ l o c a l /bin:/usr/sbin:/usr/bin:/sbin: / b i n

HOME=/home/ chip tcp_port="4433" #known Master−Gw listening port

SYMLINK=" t t y z s t i c k " #desired link device

#GET BROADCAST ADDRESS OF THE SUBNET broadcast_suffix=255

#Recognize own IP address own_ip=$( ip −4 route get 8.8.8.8 | awk {’print $7’} | tr −d ’ \ n ’ )

#Appending broadcast address to the own subnet IFS = ’ . ’ read −r −a array <<< "$own_ip" broadcast="${array[0]}"."${array[1]}"."${array[3]}"." $broadcast_suffix"

#Mapping all hosts up in the subnet sudo ping $broadcast −c 1

#Querying all the macs in the subnet and pipe the desired line=$(sudo arp −a | grep "04:44:a1") #Maste−GW−Te leco n

#Parsing the desired IP IFS = ’( ’ read −r −a array <<< "$line" IFS = ’) ’ read −r −a mastergw_ip <<< "${array[1]}"

#ESTABLISHING THE TUNNEL: TLS / TCP SOCKET − SERIAL PORT #Recognize /dev/tty assigned to the dongle 100 Implementation of the master-slave WSAN bridge architecture

TTY=$(dmesg | grep tty | grep cp210x | awk ’END{ print $NF }’)

#Link the device assigned by the OS to the desired l n −s / dev / $TTY / dev / $SYMLINK

#ESTABLISHMENT OF THE SOCKET sudo socat openssl −connect:"$mastergw_ip":"$tcp_port" , cert="$HOME"/ etc / slave −gw.pem, cafile="$HOME"/ etc /master −gw . c r t , keepalive ,reuseaddr ,method=SSL23 pty , echo =0,raw, link=/dev /"$SYMLINK" ,b115200 , parenb=0,cs8 , cstopb=1

As it can be seen, the socat command is quiet long. The meaning of each argument is:

• Cert: path to the .PEM file which contains the private/public key and the self signed certificate.

• Cafile: path to the Certification Authority of the other host. It is a self signed certificate that belongs to the other host.

• Keepalive: support for the TCP keepalive packets.

• Reuseaddr: allows reusing an address even if it is already used by socat.

• Method: sets the protocol version to be used. In this case, the SSL23 option selects the best available SSL or TLS protocol.

• Pty: establishes communication with the sub process using a pseudo terminal instead of a socket pair.

• Echo=0: switches local echo off.

• Raw: data without compression.

• Link: path to the serial device linked to the socket.

• B115200: baudrate of the UART.

• Parenb=0: deactivates parity bit.

• CS8: 8 bits of data.

• Cstopb=1: 1 stop bit C.2 Final prototype 101

The unplugging script is simpler: #Kill the socat processes ps −ef | grep socat | grep −v grep | awk ’{print $2}’ | xargs k i l l

#if /dev/ttyzstick exists , remove it i f [ −f /dev/ttyzstick ]; then rm −f /dev/ttyzstick f i

C.2.3.2 Master-GW

The Master-GW has to be previously listening on the assigned port (in this case the 4433). This is programmed in a cron entry to be verified each hour constantly. $ c r o n t a b −e 0 ***** /bin bash sudo socat openssl −listen:4433, ignoreof ,method=SSL23, cert=$HOME/ etc / master −gw . pem , cafile=$HOME/ etc / slave −gw.crt ,keepalive pty , raw , echo =0,link=/dev/ttyRMT