Universidade do Minho Escola de Engenharia

Luís Daniel Carvalho da Silva

iHotel – An Hotel Room Controller Using the Z-Wave Protocol

Tese de Mestrado Ciclo de Estudos Integrados Conducentes ao Grau de Mestre em Engenharia Electrónica Industrial e de Computadores

Trabalho efetuado sob a orientação do Professor Doutor Sérgio Adriano Fernandes Lopes

Novembro de 2011 Acknowledgements

First and foremost I would like to express how thankful I am to my su- pervisor Prof. S´ergioLopes, who followed my work closely, and advised me wisely throughout the whole time. His continuous support, with his ideas and careful thought were very important to my work. He was always there to listen and his help was invaluable in developing my ability to ask myself what was wrong or needed to be perfected. It showed me that there was still much to be done, spe- cially in the way I approached the problems I faced. I would also like to show my deepest and sincere appreciation to other two Profes- sors of mine. Professor Adriano Tavares, for all of his hard work and counselling during my Masters degree in Computer Technology. He taught me that there is nothing that cannot be done without effort and perseverance. His insightful vision lead me throughout my whole work and will for sure lead in my future life as an Engineer.I will also be forever thankful to him for his support since the moment I decided to embrace this project, he has truly been an inspiration to me. To Professor Jorge Cabral I would like to thank him for the help and inspiring counselling he gave me whenever I needed. With his support I learned that there are a number of ways to solve a problem and some of them, although not obvious will for sure contribute for a better solution. A popular expression that for this is “thinking outside the box ”. Finally, I would like to thank my family: my parents and sisters, for their patience and effort in supporting me during my Master Thesis. Without their help, without their patience I could never achieve what I have achieved until this day.

II

Abstract

This thesis report is a study on the proprietary Z-Wave protocol potentialities as a wireless communication protocol in a context. Z-Wave is a proprietary home automation protocol. Throughout this report it will be possible to get an insight on how the Z-Wave protocol works by analysing several types of information freely available on the World Wide Web, open source projects and commercial applications that use Z-Wave technology. The proposed approach to this work will be the analysis of the previously collected information to use a general set of Z-Wave commands and design a small touch screen based embedded system that features some support for the Z-Wave protocol. This console will be part of a larger concept, the iHotel concept. This concept uses a single device to control all the functionalities related to the hotel room. It should be possible to control every electronic device within a hotel room from this single interactive console. The results of this work are: (1) a working prototype of the console that controls basic Z-Wave devices such as light switches, outlets, and motion sensors; and, (2) the opening of a path, so that others can explore the Z-Wave protocol, understand it and further expand its support by adding new features.

Resumo

Este relat´oriode tese ´eum estudo das potencialidades do protocolo pro- priet´arioZ-Wave situado num contexto de automa¸c˜aoresidencial sem fios. O Z-Wave ´eum protocolo sem fios de automa¸c˜aoresidencial. Ao longo deste re- lat´orioser´aposs´ıvel ter uma ideia de como o protocolo Z-Wave funciona atrav´es de an´alisesde informa¸c˜aodispon´ıvel livremente na World Wide Web, projectos open-source e aplica¸c˜oescomerciais que usam a tecnologia Z-Wave. A abordagem proposta a este trabalho ser´aa an´alisede informa¸c˜aopreviamente adquirida para usar um conjunto de comandos b´asicose gerais Z-Wave e desenhar um pequeno sistema embebido baseado num ecrˆat´actilque suportar´acomandos Z-Wave. Esta consola far´aparte de um conceito mais abrangente, o conceito iHotel. Este conceito usa um ´unicodispositivo para controlar todas as funcionalidades relacionadas com um quarto de hotel. Dever´aser poss´ıvel controlar todos os dispositivos electr´onicos presentes num quarto de hotel a partir deste sistema embebido. Os resultados deste trabalho s˜ao: (1) um prot´otipo funcional da consola que controla dispositivos Z-Wave b´asicoscomo interruptores de parede, tomadas, term´ostatose sensores de movimento; e, (2) a abertura de um caminho, para que outros possam explorar o protocolo Z-Wave, entendˆe-loe expandir ainda mais o seu suporte adicionando-lhe novas funcionalidades.

Contents

1 Introduction3 1.1 Motivation...... 3 1.2 The iHotel Concept...... 4

2 State of the Art7 2.1 Introduction...... 7 2.2 Wireless Residential Automation Protocols...... 7 2.2.1 ...... 7 2.2.2 ...... 8 2.2.3 Zigbee...... 8 2.2.4 Z-Wave...... 8 2.3 Commercial of the Shelf (COTS) Systems...... 9 2.3.1 Introduction...... 9 2.3.2 Lagotek...... 9 2.3.3 Go Control Center...... 11 2.3.4 Silverpac Silverstat...... 11 2.3.5 Intel Home Dashboard Concept...... 13 2.3.6 Z-Wave Enabled Touch Screen...... 14 2.3.7 Electronic House Keeper...... 15

3 Platform 17 3.1 Development Board...... 17 3.2 Z-Wave Devices...... 18 3.3 Software Tools...... 18 3.4 Qt...... 19 3.4.1 Introduction...... 19 3.4.2 Widgets...... 19 3.4.3 Qt Datatypes...... 19 3.4.4 Signals and Slots...... 19 3.4.5 MOC (Meta Object Compiler)...... 20 3.4.6 Qt Class Organization...... 21

4 Z-Wave 23 4.1 Network Management...... 23 4.1.1 Self-Organizing...... 24 4.1.2 Self-Healing...... 24

V 4.1.3 Routing Principles...... 24 4.1.4 Association Process...... 25 4.1.5 Inclusion Process...... 25 4.2 Z-Wave Frame Format...... 26 4.2.1 Z-Wave Application Layer...... 27 4.2.2 Application Frame Format...... 28

5 Exploring Z-Wave Messages 31 5.1 Checksum Calculation...... 34 5.2 Node Identification...... 35 5.3 Z-Wave Version...... 36 5.4 Device Interaction...... 37 5.4.1 Basic Switch...... 37 5.4.1.1 Turn On...... 38 5.4.1.2 Turn Off...... 38 5.4.1.3 Get Status...... 39 5.4.2 Dimmer Switch...... 39 5.4.2.1 Turn On...... 39 5.4.2.2 Turn Off...... 40 5.4.2.3 Get Status...... 40 5.4.2.4 Dimm the Load...... 41 5.4.3 Power Meter...... 42 5.4.3.1 Instant Energy Consumption...... 42 5.4.3.2 Accumulated Energy Consumption...... 43 5.4.4 Sensor...... 45 5.4.4.1 Temperature...... 46 5.4.4.2 Light Measurement...... 47 5.4.4.3 Multi Instance...... 48 5.4.4.4 Battery Level...... 49 5.4.4.5 Motion Sensor...... 49 5.4.5 Device Association...... 50 5.4.6 Configuration Parameters...... 50 5.4.6.1 Dimmer Switch Configuration Parameters..... 53 5.4.7 Dimmer Switch Supported Features...... 54 5.4.8 Manufacturer Information & Device Type...... 55 5.4.9 Node Version Information...... 55

6 59 6.1 Main Screen...... 60 6.2 Socket2Serial - Graphical User Interface...... 61 6.3 Z-Wave Devices...... 64 6.3.1 Switch...... 64 6.3.2 Dimmer...... 66 6.3.3 Sensor...... 67 6.4 Configurations...... 69

VI 7 Socket2Serial Interface Software 71 7.1 Unix Signals...... 72 7.2 Serial Port Input/Output...... 73 7.2.1 Opening a Serial Device...... 74 7.2.2 Configuring the Serial Device...... 74 7.2.3 Writing to and Reading from the Serial Interface...... 75 7.2.4 Close Serial Interface...... 76 7.3 Network Sockets...... 76 7.3.1 Establishing a Socket Connection - Server Side...... 76 7.3.1.1 Creating a Server...... 76 7.3.1.2 Configuring a Socket...... 77 7.3.1.3 Bind Socket...... 78 7.3.1.4 Accept Connection...... 79 7.3.1.5 Sending and Receiving Data...... 79 7.3.1.6 Closing a Socket Connection...... 79 7.3.2 Establishing a Socket Connection - Client Side...... 79 7.4 Data Exchange...... 80 7.5 Select() Application Programming Interface...... 80 7.5.1 Communication Management...... 81 7.5.2 Registering the Socket File Descriptor...... 81 7.6 Running the Application...... 82

8 Conclusion 83 8.1 Future Work...... 83 8.1.1 Processing Power...... 83 8.1.2 Complete Z-Wave Application Programming Interface.... 83 8.1.3 Larger Display...... 83 8.1.4 iHotel Web Control...... 84 8.2 Conclusions...... 84

VII VIII List of Figures

1.1 Hotel Room Interfaces...... 5 1.2 Hotel Network...... 5

2.1 Lagotel’s HIP100 system controller...... 10 2.2 Go Control Center...... 11 2.3 SilverPac SilverSTAT 7 User Interface...... 12 2.4 Intel Home Dashboard Concept User Interface...... 13 2.5 Intel Home Dashboard Energy Consumption Overview...... 14 2.6 Electronic House Keeper...... 15

3.1 Mini2440 with 7” LCD Development Kit...... 17 3.2 Signals and Slots Example...... 20 3.3 Qt Classes Used for Building the GUI...... 21 3.4 Socket Classes...... 22

4.1 Network Topology...... 25 4.2 Routed Acknowledge Frame Type...... 25 4.3 Application Layer Organizational Diagram...... 26 4.4 Application Layer Frame Format...... 27 4.5 Interaction Between Devices During Network Inclusion...... 27 4.6 Data Monitorization Diagram...... 28 4.7 Z-Wave Application Commands General Frame Format...... 29

5.1 Qees Power...... 38 5.2 ZDM230 Dimmer Switch...... 40 5.3 HSM100 3 in 1 Sensor...... 45 5.4 Summary of Z-Wave Frame Structure for Luminance Responses.. 48 5.5 Multi Instance Command Class Structure...... 48 5.6 Multi Instance Command Class Structure Comparison...... 48 5.7 Multi Instance Data Selection Possible Diagram...... 49

6.1 System Connections Overview...... 60 6.2 Graphical User Interface Main Screen...... 61 6.3 Main Window Classes Relationship...... 62 6.4 Client Object Relationship...... 62 6.5 Switch Graphical User Interface...... 64 6.6 Dimmer Graphical User Interface...... 66 6.7 Sensor Graphical User Interface...... 67

IX 6.8 Configurations Graphical User Interface...... 69

7.1 Flow of data through Socket2Serial ...... 71 7.2 Socket2Serial Diagram of Operation...... 73 7.3 Server and Client Socket Flow Diagram...... 77

X List of Tables

4.1 Routing Table...... 24

5.1 Frame Fields...... 32 5.2 Byte masking table...... 36 5.3 Response to the version request of the Z-Tool Initialization Process 37 5.4 Response to the version request of the Z-Tool Initialization Process 37 5.5 Meter Get Command Structure...... 42 5.6 Meter Report Command Structure...... 42 5.7 Codes of Configuration Parameter for the HSM100 device...... 51 5.8 Device Type List...... 56 5.9 Manufacturer ID List...... 56

1 2 Chapter 1

Introduction

1.1 Motivation

This thesis project is a study of the proprietary Z-Wave wireless home automation protocol [1], describes a home automation based on Z-Wave, and the use of some of its features in the development of a touch screen based console aimed at a hotel room automation scenario. Recently, with the development of new technologies the market of home au- tomation has been developing at a faster pace. With this development, came the need to install home automation systems in already built houses as well as in new houses. Companies started to think in solutions that could satisfy all their current market requisites and still maintain a market price. To meet this requirement, it became obvious that only two solutions would be viable. The need for wires is, and will not be completely extinct in the near fu- ture, as such, retro-compatibility of current systems with older and wired systems is necessary during a transitional period. The other one is to disseminate the use of wireless home automation technologies as the standard to be. The advantages of not using wired installations are clear. Reduced cost, ease of installation, in- crease in range without having to install additional wiring, and specially network flexibility making it an ideal general purpose solution. To control any type of home automation system it is necessary to have at least one controller or several. Lately, a high number of touch screen console based solutions have been emerging, much because of the success of new touch screen cellphones and the easiness of use of that man-machine interface. The solu- tions currently available in the market have been widely accepted by the market, consequently it became popular to use this type of interface. Nowadays there are several home automation protocols available, some better than others, or having a certain characteristic that makes them superior for a given situation. One of the latest protocols to come to market is the Z-Wave protocol. This protocol is simple, its compatible products have low time-to-market and the range of products already available is very high. The downside is the fact that this is a closed, proprietary protocol, yet the complexity of other protocols in characteristics such as device association and interaction, make the Z-Wave

3 protocol very powerful by comparison. The fact that Z-Wave is a very powerful proprietary protocol makes it an interesting case study for the academic community and for hobbyists that seek to control a small Z-Wave device installation for a small price without being forced to spend a huge amount of money in an official development kit. This led to a very high demand for details about the protocol. A lot of people became interested in it and now currently a few initiatives are taking place to uncover all details of the protocol. Z-Wave is becoming more and more interesting as a study subject since res- idential home automation systems are becoming a part of everyday life. Z-Wave specifically is getting extremely popular. The main problem in studying and de- veloping a solution to use part of or all protocol features is the fact that there is not official documentation available that shows how the protocol works in detail and completely. To implement a working solution, one has to investigate further on other people’s works and try to extrapolate information obtained by making diverse experiments that attempt to use more and more of the protocol function- alities. This work is meant to give an insight on how this protocol works and demon- strates its potentialities. Showing a working example of an interface to Z-Wave devices is a very good way to achieve these two goals. To better illustrate the successful use of the protocol, a study around an use case was developed, namely a possible real life situation, that makes extensive use of the protocol features. In this case home automation in the context of its use in a hotel facility. This thesis is structured in the following form. The first chapter introduces the study of the protocol. How to interpret the information that is sent and received is the critical part of this study. This information will be vital to implement with a Z-Wave network. The second chapter describes how the interface with the Z-Wave network is done, how the messages are actually sent and received. The third chapter illustrates the graphical user interface that allows the end user to control the Z-Wave network, followed by the fourth chapter that shows the results of this study and its respective analysis. This reports fifth chapter, demonstrates the conclusions reached by this study and its validity as study subjects.

1.2 The iHotel Concept

The iHotel concept can be defined as an integrated management console for wireless hotel room automation. The usual hotel room user often has to deal with many different interfaces to manage his life inside the room. The telephone, a , a radio, the room lights and blinds are examples of equipments which need a friendly and interactive interface in order for the user to feel comfortable using them. The iHotel concept relies only on Z-Wave, a technology with great potential to evolve as an industry standard in home automation, since this is a wireless technology with a great diversity of devices already developed from several major automation brands such as: Danfoss, Leviton, ACT, Everspring, Homeseer, Intermatic, Merten and several

4 other. The main idea of iHotel is unification and its main appeal is the fact that one interface substitutes all other within the hotel room.

Figure 1.1: Hotel Room Interfaces

Figure 1.1 represents some of the interfaces that can be aggregated in the iHo- tel console. Each hotel room is a Z-Wave independent network, independent from any other Z-Wave network that may operate nearby. However, each iHotel inter- face is connected by means of a cable or even wirelessly to a central hotel TCP/IP network, as represented in figure 1.2. A central server would be responsible for managing all the consoles from each room and its respective Z-Wave networks.

Figure 1.2: Hotel Network

5 The advantages of using a single interface in each hotel room are clear. One interface means that the control system will be cheaper, the user will only have to deal with one equipment and the hotel will be equipped with the means to have every room under monitorization and control. Besides that, the system will provide added security for the hotel by making available detailed information about the room occupancy and usage (e.g., room services, energy costs). As a main disadvantage there is the cost of the whole system. Since the Z- Wave standard is only a few years old, cost is still an issue. A normal load switch can cost up to 5 times the cost of a normal switch. A whole room equipped with Z-Wave devices is much more expensive than with normal devices. In recent years the home automation market has been suffering major changes. Levels of automation that were impracticable a few years ago, are now possible using modern home control systems. At this time is possible to automate room temperatures, lighting, doors and windows, security, HVAC systems, surveillance systems, and other types of automation systems. Taking into account the success, acceptance and high attention the Z-Wave protocol has been having since its development, it became a desirable subject of study for the common hobbyist and the academic community.

6 Chapter 2

State of the Art

2.1 Introduction

Several different protocols developed for home control systems have been emerging in the last two decades. Most of those protocols are not considered standards since they are not adopted by the majority of the home automation users and respective industry. Some of the most relevant ones, which actually became popular standard protocols are KNX, X10, LonWorks, INSTEON, Zigbee and more recently Z-Wave.

2.2 Wireless Residential Automation Protocols

2.2.1 X10

X10 is a home automation standard already deeply established in the market. It was developed in 1975, so the number of devices already present on the market is very high. Back when the standard was developed, there were no plans to use a wireless transmission medium of transmission. The main medium of transmission at that time was the power line. The data is encoded and is transmitted, bit by bit at each zero crossing of the AC current waveform. As more solutions came to market, it became necessary to bring the X10 up to the standards that were being introduced, such as a wireless method of communication. The wireless frequency used by the system is 310 MHz in the United States and 433 MHz in European systems. The system’s wireless devices transmits packets identical to the wired version of the protocol. The most common devices available with the wireless version of the protocol are switches, fire and burglar alarms, light controllers and general device controllers. This protocol suffers from some well known issues, like being extremely slow, by comparison to other protocols, lacking encryption and suffering from some types of interferences. The protocol also has the limitation of addressing only 256 devices.

7 The only entity responsible for regulating the introduction of new devices and modifications to the protocol is the company that developed it - Pico Electronics.

2.2.2 Insteon Isteon is a protocol similar to the X10 standard, it was designed to be compatible with the X10 as well as to improve its limitations. Much as the X10, it uses the power line or a radio frequency (RF) to communicate between devices. Insteon is a wired and wireless mesh network topology. This means that any node can repeat, transmit and receive data in the network. There is no need for a network controller because the network is peer-to-peer. The devices meant to be used by the Insteon protocol are simple devices, such as light switches, sensors, fire and burglar alarms, etc. The company beyond the Insteon protocol is SmartLabs.

2.2.3 Zigbee Zigbee is not a protocol but a specification for low power, low bandwidth protocols based on the IEEE 802.15.4 standard. This specification is meant for small WPAN (Wireless Personal Area Networks), such as the case of Home Automation proto- cols. The main objective of this standard is to define a low power, low bandwidth, self-organizing mesh network that can be used not only for general purpose but also for industrial control, embedded sensing, medical data harvesting, fire and burglar alarms, building and home automation and other application fields where WPAN networks are necessary. ZigBee is a wireless mesh networking standard and provides high reliability in data transmission and extensive transmission ranges. The bands of operation are 868 Mhz in Europe, 915 Mhz in USA and 2.4 GHz in most other countries. A ZigBee chip usually comes in the form of a microcontroller with a RF radio and the Zigbee stack already programmed in it. The ZigBee stack was designed to be easy to develop applications on the microcontrollers. Much as other protocols, its regulation and interoperability are assured by a consortium of companies that form the so called ZigBee Alliance. Any new device has to be validated by passing the ZigBee Qualification Process.

2.2.4 Z-Wave The Z-Wave protocol is a low-power wireless communications protocol specially designed to be used in home automation. Zensys is the company responsible for the development of this protocol. This technology is proprietary, which means it is not possible to take full profit of it without full access to its documentation. Z-Wave uses a RF radio that operates in the sub Gigahertz frequency range. This enables Z-Wave communications not to be interfered by any device based on the IEEE 802.11 wireless standard. This sub Gigahertz frequency also enables

8 the transmission of small amounts of data at lower speeds with an extremely low power consumption. Due to the low cost of embedding a Z-Wave module in consumer electronics products, there are a lot of manufacturers trying to develop new Z-Wave con- trolled products such as remote controls, smoke alarms, sensors, thermostats, wall switches and presence sensors. Z-Wave is a mesh networking technology where each node communicates with any other on the network by sending a message through one or several nodes. This allows the possibility of communicating with nodes that are out of range due to the distance or the existence of obstacles. These devices can work alone or in groups, this enables an association of devices to be made according to certain rules defined by the user. The Z-Wave protocol and device interoperability is regulated by an interna- tional consortium of manufacturers called Z-Wave Alliance.

2.3 Commercial of the Shelf (COTS) Systems

2.3.1 Introduction At this point, some commercial home control systems with Z-Wave capabilities are going to be presented. These systems resemble themselves with the iHotel project in the sense that they feature Z-Wave device control but also other functions such as sound control or VoIP phone. Each of them consists of a touch screen embedded device from where a user can control a series of Z-Wave devices. Besides Z-Wave connectivity, most of the systems here depicted have a set of very interesting and useful features such as: sound control, VoIP phone, radio, digital frame, alarm clock among others. Since Z-Wave is a rather new technology it cannot be expected that a large market of solutions is available.

2.3.2 Lagotek Lagotek’s HIP100 is a mixture of wireless hardware and software based on the Windows CE 5.0 operating system and its .NET Compact Framework. Lagotek uses other companies Z-Wave products. It features a small LCD touch screen, a microphone, a speaker, sensors measuring temperature, light and the proximity of people nearby as well as Wi-Fi and Z-Wave controller to interface with Z-Wave compatible products. The HIP100 can regulate lighting, heating and cooling room by room, digital music, irrigation, burglar and fire-alarm systems and security cameras, as well as motorized skylights and fans. The HIP100 units can operate standalone or in a redundant wireless network, with each unit being capable of controlling the entire house if necessary, up until a Z-Wave limit of 232 devices per network. The Wi-Fi connection enables the system to communicate with a central computer for additional control, such as the case of a hotel. Where the hotel can have a sense of certain events that are happening in a room, like leaving the door room open for more than a pre-determined time,

9 or the music being too loud for a certain time, as well as simple functions like control its music library.

Figure 2.1: Lagotel’s HIP100 system controller.

A controller with a normal set of nodes, enough for 3/4 rooms, a living room, a kitchen, 3 bathrooms, a hall, a garage and a basement is meant to be installed in homes selling for 400,000$ or more, so that its price represents approximately 2% of the total price. The price of a system as previously described can go for about 8,500$. The Lagotek’s HIP100 system features:

- Lighting Control;

- Scene Modes;

- Distributed Audio;

- Climate Control;

- Video Monitoring;

- Blinds;

- Security;

- Rules;

- IR Control;

- Intercommunication;

- Irrigation Control.

10 2.3.3 Go Control Center The Go Control Center, show in Figure 2.2, is an all-in-one security and home management system. This system features an intuitive and user-friendly color touch-screen interface, a GSM (Groupe Sp´ecialMobile) radio and built-in Z-Wave RF Protocol support. The Z-Wave support enables the system to control lighting, HVAC and other home Z-Wave appliances right from the system, smart phone or computer using a Z-Wave controller connected to a USB port of a Wi-Fi connection to a Z-Wave enabled router. Besides the Go Control Center, Z-Wave nodes for the house where the system is meant to be installed are all that is necessary to buy. The Go Control Center is connected to a monitoring center via a cellular connection which allows an operator to hear what is happening in the house, through one or several Go Control Center devices and quickly dispatch emergency services.

Figure 2.2: Go Control Center

These characteristics provide important money and time-saving applications. The features of the Go Control Center are:

- Color Touch Screen Display;

- Fully Self Contained;

- Snap-in GSM Radio;

- 2-Way Voice Over Cell.

The Go Control Center is priced at 700$.

2.3.4 Silverpac Silverstat The SilverPAC SilverSTAT 7, depicted in Figure 2.3 is an advanced smart energy thermostat that seeks to replace the common household thermostat with an ad- vanced home climate control system. The SilverSTAT 7 features a Smart Energy

11 In-Home Display (IHD) to help monitoring and management of energy consump- tion and is built on Windows CE 6.0 R3 and Intel Atom platform. The device has been designed with a seven-inch touch screen display that is able to display the distribution of household energy consumption down to each individual appliance.

Figure 2.3: SilverPac SilverSTAT 7 User Interface

The SilverSTAT 7 has a touch sensitive LCD screen and thanks to its wireless 801.11 connection the device is capable of communicating with smart meters, that way the users can see instantly how much gas or electricity is being consumed at a given point in time. It also has an 802.11 Wi-Fi interface that allows it to communicate with a local area network and Internet services. It is Z-Wave enabled so it will be able to talk to and interact with Z-Wave enabled lights and appliances, programming and shutting them off as needed. Energy and budget savings can be achieved by turning off or rescheduling the use of appliances for a more cost efficient time. The SilverSTAT 7 can also be used to access information easily from a central location. One can plan for power usage and cost optimization by using weather and fuel price information obtained through the system. SilverSTAT 7 can act like a normal computer by being able to stream photos, music and content direct from the internet or the PC. In summary the SilverSTAT 7 features:

- 7” Touch Screen LCD;

- Windows Embedded CE 6.0 R3;

- 64 MB DDR RAM (upgradable to 128 MB);

- 128 MB Flash Memory (upgradable to 4 GB);

- 1 x USB (Standard A);

- Intelligent 7 day programmable thermostat for HVAC control;

- IEEE 802.15.4 ZigBee Wireless Interface to Monitor Smart Meters;

12 - 802.11g Wi-Fi Interface for Home and Internet Networking Connection;

- Z-Wave Home Automation Interface to Manage Lighting and Appliances;

- DLNA Compliant;

- FM Radio for Convenience and Local News Broadcasts and Emergency In- formation;

- Built-In Speakers;

- Digital Picture Frame and Media Player can play content from network or internet;

- Digital Clock, Calendar, Scheduler, Task Manager for Home Control and more.

The suggested retail price is 1,300$.

2.3.5 Intel Home Dashboard Concept The Intel Home Automation System is built using an Atom processor platform and a large 11” touch-sensitive OLED display, this can be seen in Figure 2.4. As a control dashboard it features a Zigbee and a Z-Wave interface in order to connect with all the electronic appliances at home. The Intel Home Automation System shows the user the most diverse informa- tions, whether they are weather, utility cost or temperature, personal messages, home security, time, internet access. The Wi-Fi connection allows the user to have access to the Internet. The Zigbee and the Z-Wave interfaces allow the user to monitor and to manage the energy consumption down to each appliance, Fig- ure 2.5 depicts this. The software controls the utilities to lower electricity use of appliances during peak cost times.

Figure 2.4: Intel Home Dashboard Concept User Interface

13 The device is meant to act as a hub for controlling the electrical appliances and the thermostats as well as gather information from smart meters. Each appliance needs to be connected to a low-cost Z-Wave and/or Zigbee transmitted socket in order for this to work. Since this is still a concept product, it still does not have a retail price available.

Figure 2.5: Intel Home Dashboard Energy Consumption Overview

With capabilities similar to those of netbooks, the system can do a number of other tasks, including being used as home communications center, access the Internet and display video from security cameras.

2.3.6 Z-Wave Enabled Touch Screen The Interactive Electronic Systems Control Touch Screen allows the control and monitoring of Z-Wave enabled devices such as lighting, thermostats, windows and a unique automated wake-up scene. Events can be scheduled and default scenes or 1 button scenes can be configured for easier operation. The system is self contained, has a backup battery. A software package is used to create pre-programmed schedules and scenes that can be used to display light and tem- perature scenarios. The Interactive Electronic systems Control Touch Screen can easily be installed in a standard 2 gang electrical box. The suggested retail price is 499.97$. This system features are: - Full featured, high resolution color display;

- Easy-to-use Lighting configuration software package for customizing of Scenes, Schedules, Rooms and Lights Manual Device and Scene Control;

- Multiple individually selectable Scheduled Events;

14 - Status indication for intensity and module response; - Battery backup for Real Time Clock; - Can be mounted into standard two-gang electrical box; - IR remote control port for future applications EasyTouch-S Touch Screen Specifications. Its specifications are: - High Brightness, High Contrast LCD display; - 3.6 inch diagonal; - LED backlight (Software controlled); - 1028 Volts DC Input Voltage; - Power Consumption approx 170 mA @ 12 Volts V DC.

2.3.7 Electronic House Keeper The Housekeeper 2.6 is a wall-mountable console with wireless communication capabilities that interfaces with electronics, appliances, heating, air conditioning, as well as water and electricity meters. The Housekeeper features Wi-Fi and Z- Wave connections. Using the latest Z-Wave technology it is possible to monitor, control and time the electricity consumption on the electrical appliances connected to the Housekeeper. The touch screen console enables the users to review the energy usage of each of the devices connected to it. Using the Wi-Fi connection is possible to control and monitor the appliances through a computer. Communication via VoIP, text messaging, access to the e-mail and web is also made possible using the Housekeeper.

Figure 2.6: Electronic House Keeper

15 The technical specifications are as follows:

- 180 x 202 x 45 cm dimensions;

- 7” Touch Screen 480x234 LCD;

- Intel 520 Mhz PXA270 processor;

- 256 MB Internal Memory;

- 5 Watt Stereo Speakers;

- FM Radio with RDS;

- Z-Wave RF Interface;

- IR controllable via B&O, Phillips, Sony, NEC, Panasonic, Daewoo, JVC, Nokia and Sharp;

- 1 x Ethernet, 4 x USB 1.1, FM Antenna and Line Out connectors;

- Movement, Temperature and Light Sensors;

- Windows CE .NET.

16 Chapter 3

Platform

3.1 Development Board

The platform used to develop this project is an embedded system based on the 400 MHz Samsung S3C2440 ARM9 processor with an ARM920T core with a 16/32- bit RISC architecture. Among these processor features are: a MMU unit, a LCD controller, UART ports, DMA channel, timers, input/output ports and several other interfaces. Designated as Mini2440, shown in Figure 3.1, it was developed by a Chinese company called Hiteg. The Mini2440 is able to run an embedded distri- bution, including Android, as well as Windows CE. Picture 3.1 below depicts a Mini2440 board with a 7” LCD display.

Figure 3.1: Mini2440 with 7” LCD Development Kit

This development platform besides the powerful processor has the following features: - 64 MB SDRAM; - 128 MB NAND Flash; - Serial Ports; - USB Host and USB device ports; - Audio Output and Input; - RJ-45 Ethernet connection;

17 - LCD and Camera Interface;

- JTAG Interface.

3.2 Z-Wave Devices

In this project, the following Z-Wave devices will be used:

- Aeon Labs USB Z-Stick;

- Qees Power Switch;

- ZDM230 Dimmer Switch;

- HSM100 3 in 1 Sensor.

The first item is the Z-Wave network controller. It is interfaced by the Home- Seer Home Automation Software to control the other three end devices. As their own names suggest the first is an outlet switch which enables a user to control a power outlet either remotely or locally, the second is a switch with an included dimmer which also features local and remote operation as well as association with different devices in order to control them, and the third is a device with three sensors embedded on it, motion, temperature, and luminance with support for de- vice association to operate autonomously in cooperation with other devices. Each of these Z-Wave devices has different characteristics which will be explored later in this project, such as specific support for commands according to the type of device, if its a switch, a dimmer or, a sensor.

3.3 Software Tools

The two software components in this project were developed in C and C++. This seemed an obvious choice both for the extensive experience with these languages as for the fact that they are ideal for embedded development. The software com- ponent that communicates directly with the Z-Wave controller was developed in C using a simple text editor and the GNU GCC compiler, in Linux. The graphical user interface, GUI, that enables the user to interact with the Z-Wave network was develop in C++ using Qt. A brief introduction to Qt programming is given in subsection 3.4. Besides the developed software mentioned earlier, a commercial Z-Wave tool was also used, the HomeSeer Home Automation Software. This tool enables a user to configure and control its own Z-Wave network. The main advantage of using it is the possibility of establishing a relationship between Z-Wave messages sent by the software and the ones that need to be generated and sent by the software to be developed in this project.

18 3.4 Qt

3.4.1 Introduction

Qt is a cross-platform application and UI (User Interface) framework to write applications once and deploy across a multitude of operating systems. It is mostly popular in the development of GUIs, but it is also used for non-GUI applications. C++ is the standard programming language to use Qt although several language bindings exist to other programming languages. In terms of licensing, Qt is free and open-source to personal use, however a license has to be obtained if any system is to be sold using Qt technology.

3.4.2 Widgets

A Widget is the basic unit of a GUI application. It can be a window, menu, button, icon, roll bar and many other items. Widgets usually follow a hierarchy, there are parent Widgets and child Widgets but independent Widgets may also be created. A widget without a parent is called a window. Widgets communicate between themselves in an indirect way. Each time an event occurs, a Widget will announce that event, for instance: mouse, keyboard, or other events from the user or window system that may trigger other widgets behaviour.

3.4.3 Qt Datatypes

When designing a GUI application using Qt, several other data types may be used besides the normal C++ data types such as: int, bool, double, char, etc. Some of these new data types can be regarded as variants of popular types of containers in C++ like QList or QVector and some of them actually simplify certain tasks such as: QDate, QDateTime, QChar, QString, QByteArray, etc, because of their specificity.

3.4.4 Signals and Slots

As said in the previous subsection, with a GUI application designed with Qt, objects communicate between themselves by using the Signals/Slots mechanism. This mechanism is what differentiates more Qt from other frameworks. This mechanism allows objects to emit events when certain actions occur and other objects to execute certain functions upon event notification. The emitted events are Signals and the executed functions are the Slots, which are almost identical to C++ member functions with public, protected or private scope. For example, if a dial button is rotated, a roll bar is moved automatically. Figure 3.2 shows connections between objects in terms of Signals and Slots.

19 Figure 3.2: Signals and Slots Example

In this example, the behaviour that is desired is that every time the dial or the slider are actuated, the other one follows and the progress bar reacts accord- ingly also showing the percentage of light intensity. In order for this to happen, four connections were made between these three GUI objects. Connection number one is used to instruct the dial to rotate when the horizontal slider moves; con- nection number two is used to make the progress bar move when the horizontal slider moves, connections number three and four are used to change the value of the dial object each time the ZDM230 horizontalSlider and ZDM230 progressBar respectively, have their values changed. Most of the GUI controls already have a set of predefined Signals, but adding more Signals is always possible. The same happens with Slots. No object cares about the Signals that are emitted and no object knows that one of its Slots is being used by any other object. Objects are completely independent. Any number of Signals can be connected to any number of Slots and even to other Signals.

3.4.5 MOC (Meta Object Compiler) The Meta Object Compiler (MOC) is what makes Qt so powerful and flexible. The name suggests that the MOC is a compiler, but in fact it is a pre-processor of Qt special reserved words. Once any of these words is found, the MOC will replace

20 it with special C++ code that can be more complicated than the original reserved word. It can be said that it extends the source code with additional functions. The MOC’s reserved words are:

-Q OBJECT;

- public slots;

- protect slots;

- private slots;

- signals.

The MOC pre-processor is invoked when and if necessary, to pre-compile all the necessary files with reserved words. After that, all the object files are created and afterwards they can be linked.

3.4.6 Qt Class Organization The application’s main window is based on Qt’s QMainWindow class; besides that one, other related classes are used for layout management, such as QButton, QWidget, QDialog, QToolBars, QDockWidgets and many more. Qt’s class QS- tackedFrame is used to avoid creating several different windows within the main window. Each page of the StackedWidget features a different system function. Fig- ure 3.3, shows the classes used for building the GUI and the relationship between them. All of those classes are part of QtGui module.

Figure 3.3: Qt Classes Used for Building the GUI

Qt already features a specific class for TCP socket communication called QTcpSocket. Figure 3.4 shows the class organization that Qt features for in- terfacing with TCP sockets. These classes are part of the Qt Core module.

21 The GUI is based on Qt’s class QMainWindow from which a class MainWin- dow derives and an object of class Client, an application class, is instantiated as part of the MainWindow class.

Figure 3.4: Socket Classes

22 Chapter 4

Z-Wave

Several amateur projects have been developed by individuals or groups of people that aim at designing Z-Wave compatible software and hardware. These projects have not had the support of the company responsible for the Z-Wave protocol, Zensys. As a consequence, most, if not all of the protocol details had to be unveiled in a trial and error basis. Z-Wave product manufacturers have provided powerful hints on how a Z-Wave device communicates. Z-Wave is a proprietary wireless protocol intended to be used in a residential context to control appliances within a household. It is a low data rate (40 kbps), low power (<25 mW) that is meant to provide reliable transmission of data as well as flexibility and simplicity. A Z-Wave network consists of up to 232 nodes and there are two types of nodes, controllers and slaves. In a Z-Wave network, although communication between two nodes may not be possible directly, other nodes can retransmit the message. This process takes place only up to a limit of 4 retransmissions per message, that is, 4 network retransmission hops. Each Z-Wave network has an unique 32 bit identifier named Home ID as stated in [2]. Each slave device obtains the Home ID from the controller upon joining a network. Each individual node is addressed in the network by a unique 8 bit identifier designated Node ID, which is unique only within the network and assigned by the network controller, also refered in [2]. A controller is able to initiate transmission and calculate network routes for messages, while a slave is just an end device that executes the controllers requests. Within the controllers category there are two distinct types: static and portable controllers. As their name says, static controllers are the ones with a fixed position within the network, the portable are the ones used to install the Z-Wave network and therefore they cannot be fixed. This happens because the controller has to be near device’s physical position at the moment of installation, to finalize it.

4.1 Network Management

The network management goal of Z-Wave is that the user should not be respon- sible for any type of actual management. The owner needs a network free of maintenance and that can be easily configured. In fact, the network must be

23 autonomous. This is certainly the greatest challenge to overcome. The following subsections describe management properties of Z-Wave networks.

4.1.1 Self-Organizing

What defines a self-organizing network is the capability of the network to recon- figure itself to discover new nodes and transmit information to those nodes in an efficient way. It should not be mandatory for every node to be in direct contact with each other. But it is important that the path to any node to be known as soon as the message initiator knows to which node it should transmit the message.

4.1.2 Self-Healing

A self-healing network will, due to obstacles or changes, adapt itself to reroute any message that cannot be sent using a pre-determined path. This re-routing process is important if a node suddenly is down, changed position in the network or obstacles have come in the way of the transmission path.

4.1.3 Routing Principles

To ensure that each device knows its position on the network and the surrounding environment (in terms of Z-Wave network topology), during the inclusion process, the controller enquiries the slave device about which nodes can be reached from the slave’s position, despite this any node can be used for its routing capabilities since all of them are always able to retransmit messages as said in [3]. A routing table is created or updated and this table represents the instant topology of the network, as it can be seen in table 4.1. The routing table represents how each node is connected within the network. Each device is represented in both a column and a row, building a matrix wherein each cell numbered one represents a connection between the devices of the corresponding column and row. For example, in table 4.1 there is a connection between device 1 and 2, as shown in Figure 4.1.

Table 4.1: Routing Table

1 2 3 4 5 1 0 1 0 0 0 2 1 0 1 1 1 3 0 1 0 1 1 4 0 1 1 0 1 5 0 1 1 1 0

24 Figure 4.1: Network Topology

The controller always tries to reach the node directly, but if it cannot, then it will try to determine its position on the network. To do this, it will use two parameters: the most used nodes list and the preferred repeaters list. The most used nodes list is a list of nodes that the controller already contacted directly and prioritized by how often they are available, after that the controller tries to reach the most used repeater nodes which represent the shortest number of hops to reach a given destination. This is detailed in reference [4]. Figure 4.2 shows how the process of retransmission of messages works.

Figure 4.2: Routed Acknowledge Frame Type

4.1.4 Association Process Besides the inclusion/exclusion process, during the initial stage of network instal- lation and configuration, nodes can be configured to be controlled or control other nodes. This is designated as association. It consists of devices being configured to act directly with other nodes, without network interference. The controller or controllers of the network can set up associations between devices. An association is a logical connection between two devices that allow one device to control an- other device function directly. Typically, a device that consists of wall switches, say four, can have one of its switches control another switch in another room.

4.1.5 Inclusion Process Nodes can be included/excluded or associated with other nodes. Inclusion/exclu- sion can only be performed by a primary controller on the network, the controller

25 that controls all other controllers and/or devices. The inclusion process is initiated by activating an initiator (typically a button or a set of buttons) on the device and the controller. When the controller receives information from a new device that had its initiator activated, it will automatically assign the Home ID and a Node ID to the device. During the inclusion process, if the device is a controller the routing tables in the primary controller are automatically transferred to the new controller.

4.2 Z-Wave Frame Format

According to [4], the Z-Wave application layer comprises two types of commands: Application Specific Commands and Z-Wave Commands. A diagram depicting this difference can be seen in [3]. Figure 4.3 shows it. This is confirmed in [5].

Figure 4.3: Application Layer Organizational Diagram

In fact [5] specifies that the Z-Wave application layer frame format consists of:

- Single/Multi/Broadcast Frame Header;

- Application Command Class;

- Application Command;

- Sequence of command-specific Parameters.

Each of these items is 8 bits long as shown in figure 4.4 of [5]. There are two set of command classes, one for each type of command:

- 0x00 - 0x1F Reserved for the Z-Wave Protocol

- 0x20 - 0xFF Reserved for the Z-Wave Application

26 Within this project’s scope, only Z-Wave Application commands will be used. Z-Wave Protocol Commands are only used by controllers to obtain either Home ID’s or Node ID’s, except in more complicated devices, not studied here, were additional network management functions might be necessary. This is referenced in [4]. To interact with different types of devices, specific classes of commands are necessary, for example: a switch makes use of a different command class than a sensor. As necessary, further along this document, the codes for command classes will be revealed, as well as specific commands within those classes. Up to this moment in the development process, the known commands include SET, GET and REPORT.

Figure 4.4: Application Layer Frame Format

4.2.1 Z-Wave Application Layer The first step to build a Z-Wave network is to include a device in the network using the controller. In this case, the Aeon Labs Z-Stick controller is used to include the Qees Switch. The controller is put on discovery mode and placed close to the device, the inclusion button on the device is pushed and both devices interact. After that the controller signals, through a blue led, that the device has been successfully added to the network. Figure 4.5 depicts this interaction between controller and device.

Figure 4.5: Interaction Between Devices During Network Inclusion

The Aeon Labs Z-Stick Z-Wave controller is connected to the computer through

27 an USB port.When the device drivers are being installed it can be seen that a CP2102 USB to UART converter from Silicon Labs is used to communicate with the microcontroller that implements the Z-Wave API in the controller. This was confirmed in [6, p. 6] this can also be confirmed in [3]. Using a serial port termi- nal/monitor to connect to the COM port of the CP2102 drive with the settings 115200 bps, 8 data bits, no parity, 1 stop bit, it is possible to see what is being sent and received between the computer and the Z-Wave controller. Figure 4.6 depicts how the monitorization of traffic takes place.

Figure 4.6: Data Monitorization Diagram

4.2.2 Application Frame Format After the inclusion process takes place, the next step is to test the device. To test the device the first thing to do is press the button on the Qees Switch. This button is used both for inclusion as well as reporting data. When this button is pressed (in either ON or OFF position) a message is sent to the controller containing certain details such as: switch state and Node ID, at least. Furthermore, by looking at [1, p. 23, Table 1] it is possible to see some of the parameters that are present in a frame. In this context, not all the details are important, but it can be assumed that a parameter length of frame, command value, command, data byte and a checksum are present and these are the most relevant right now. In the same document a few more important informations are present: the sizes of some of these commands and how the checksum is calculated.

- Source ID - 8 bit;

- Length - 8 bit;

- Command - 8 bit;

- Command Value - 8 bit;

- Data byte - 8 bit;

- Checksum - 8 bit.

This is the frame format for Z-Wave Application commands. Below is a figure to better illustrate this, Figure 4.7.

28 Figure 4.7: Z-Wave Application Commands General Frame Format

29 30 Chapter 5

Exploring Z-Wave Messages

The Qees Power Switch was included in the Z-Wave network and the setup de- scribed in 4.2.1 was used to listen to the messages exchanged between the applica- tion software. When the switch is pressed on the Qees device, the result obtained in the serial communication channel was the following byte sequence in hexadeci- mal notation, repeated 4 times with a one second interval: <01 16 00 49 84 02 10 04 10 01 85 25 70 72 31 32 77 73 75 27 86 EF 20 9D The first character of the sequence represents the direction of the message from the application perspective: ’<’ for received and ’>’ for sent messages. According to the Qees Switch datasheet [7], one push on the button performs a Send Node Info command, so it can be assumed that this is a frame that contains all the relevant information about the device. As detailed earlier in Figure 4.4, the frame starts with a header. This is tested by pushing the button on the Qees device and then using a terminal to send the hexadecimal character 0x06, which resulted in receiving only one of the frames instead of the original four repeated frames in sequence being sent by the device. The Z-Wave frame format is presented in an hexadecimal notation. Note that the first character in the frame is named Start of Header (SOH) in the ASCII table. Assuming this is in fact true, it can also be expected that the character ACK or 0x06 is the acknowledge for the Z-Wave protocol. Knowing how to calculate the checksum for a certain message is only useful if the rest of the message is correct. Using the Qees device as a test device and the Z-Tool a few messages were observed during the network initialization and device discovery process. In this process, Z-Tool asks the controller for details about the Z-Wave network, such as: home ID, number of nodes, each node ID, node type, node location regarding its neighbours and node name as well as ON and OFF buttons and a dimmer level control. The first excerpt of communication during the Z-Tool initialization process is: >01 03 00 02 FE <06 <01 25 01 02 05 00 1D 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 01 C0 >06

31 So far, the known parts of the protocol are the SOH (start of header), ACK (acknowledgement) and CHK (checksum) bytes. Also, from experience with Z- Wave devices it was found that NACK with value 0x15 and CAN with value 0x18 are also valid Z-Wave network responses when messages are not correct and a device cannot be found respectively. Naturally, there is a length byte in all frames with variable length fields as mentioned in Table 1 of [1]. By looking at the first message, byte 2 with value 0x03 can be interpreted as the length byte if the length is counted as the number of bytes between the SOF and checksum excluding both. Message 01 03 00 02 FE, has all three Z-Wave information bytes underlined. To confirm this, the network controller response is also evaluated. Byte 0x25 converted to decimal is 37. By counting the number of bytes, excluding the ones already refereed, it can be verified that the second byte in a Z-Wave message is the size of that same message in bytes. This can easily be confirmed for any Z-Wave message. After the byte that indicates the size of the payload in each frame, it was observed that the next byte was always either 0 or 1 and alternating between consecutive messages between the two devices. This pattern resembles like a ques- tion/answer pattern back and forth between the two devices. Following this line of thought, the requests are the ones identified by 0x00 and the responses the ones identified by 0x01. To completely decode the Z-Wave frame presented previously, there are still some parts missing. The original request was: >01 03 00 02 FE. Within the response frame, bytes 4 to 7 and 37 and 38 are unknown, and underlined just below: <01 25 01 02 05 00 1D 43 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 01 80 From the original request, the known parts are the following bytes: start of frame, size of payload, request/response and checksum as depicted in Table 5.1.

Table 5.1: Frame Fields

Start of Frame Size of Payload Request\Response ... Checksum

Byte 4 with value 0x02 in the request, is the command to request every node ID in the network, and as expected, a request has a correspondent response. Therefore, in the response byte, the original command is also present in position 4, 0x02. To reach this conclusion, the whole initialization process was taken into consideration and it was noticed that the fourth byte of each request, corresponded to the fourth byte of each response, therefore byte 4 with value 0x02 appears to be the code to request every node ID in the network. From this behaviour it can be assumed that this is the ”code” for the operation to perform on the network and/or device. Bytes 0x05 and 0x00 appear to have no immediate meaning, but byte 0x1D, which in decimal notation is 29, is the number of bytes by counting position 8 (0x43) and the next 28 zeroed bytes. Can these 29 bytes be used to mask the

32 whole 232 possible devices? In digital logic 1 bit is capable of identifying one unit. In [9, p. 17] states that ”... system protocol preferably comprises a procedure for masking device identifiers in a table in order to generate a string of bits making up the bitmask so that each bit corresponds to a device identifier, the value of each bit determining whether the one or more commands applies to the corresponding device.”. What this means, essentially is that 1 bit masks 1 device, so 1 bit x 8 bits per byte x 29 bytes = 232. This is the number of devices that are possible to mask. If these 29 bytes are indeed used to mask the whole Z-Wave network of devices, the bytes left, 0x03 and 0x01 should be some kind of information bytes, since network commands come before parameters in the Z-Wave frame structure as shown in 4.4. These bytes were not changed with the addition of new devices to the network. From now on the acknowledgements are omitted to focus on the messages data. The next messages in the Z-Tool initialization process (the acknowledgements were omitted, and the byte that seems to indicate the node ID’s is underlined), are: >01 04 00 41 01 BB <01 09 01 41 92 16 00 02 02 01 33 >01 04 00 41 02 B8 <01 09 01 41 D2 9C 00 04 10 01 ED >01 04 00 41 07 BD <01 09 01 41 C9 0C 00 04 11 01 67

These messages were recorded after adding the second device, with ID=7, to the network. Before that, only the first 4 messages were exchanged between the Z-Tool and the controller. Since all other bytes in the request are known, this means that the controller inquires each device, with a command 0x41 probably used for enquiring the device about its type or some other kind of initial important information regarding the device. This is repeated for each device. Up until byte with value 0x41 of the response, inclusively, the meaning is known, from that byte on until the checksum byte the meaning is still unknown. This group of unknown bytes, has some type of repetitive pattern: for every device the latest byte is 0x01, the first two bytes are different for each device. An interesting fact is that the fourth byte is the same in two devices, one is a binary switch and the other is a dimmer. Between these two devices the difference is the fifth byte 0x010 for the switch and 0x11 for the dimmer, which in some documentation is also referred as a multilevel switch. This fact leads to the conclusion that byte four, 0x04, is probably indicating that the device is a switch. This is supported by the fact that between the dimmer and the binary switch, the only thing in common is the fact that both turn a load (e.g. lamp, kitchen appliance) on and off, also the dimmer might be understood as a specialization of a switch. The fact that the device with ID=2, the network controller, has the fourth byte with value 0x02, leaves a bit of suspicion about the line of thought followed. Should not the controller be designated as the first type of device? Or is there more than one type of controller? Based on [8], there are two types of Z-Wave network controllers, Static and Portable controllers. This seems to indicate that the previous line of

33 thought was correct, but there are not enough facts to support this claim. The following messages in the Z-Tool initialization process are: >01 03 00 20 DC <01 08 01 20 00 00 62 6A 01 DF

The response to the request, byte 0x20 is pretty straightforward to interpret. The Z-Tool GUI guide indicates that the network Home ID is 00 00 62 6A, pre- cisely the number in the response to our request. Therefore, it is concluded that 0x20 is the code to request the Home ID. The second underlined byte in the re- sponse with value 0x01 also occurs in previous interpreted message responses all with the form: <01 09 01 41 XX XX XX XX XX 01 67

The meaning of this byte is still unknown, but since it repeats itself in several messages with the same value, it should not be ignored. The following request and response were: >01 03 00 07 FB <01 2B 01 07 03 07 00 00 00 01 00 01 FE 80 FE 88 0F 00 00 00 FB 97 7F 82 07 00 00 80 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47

Request 0x07 above in red, provides a response with a lot of information, 40 bytes. However, the meaning behind all of this data remains unknown, since there is no comparison term with similar messages.

5.1 Checksum Calculation

As stated in [1] the checksum is ”calculated between Home ID and the last byte of the frame. The Checksum field itself is not calculated.”. The last byte in a frame is the checksum, as it happens in other protocol specifications. The SOH does not take part in the checksum calculation since it is only a control character, it marks the beginning of a new frame. As stated before, the checksum field itself is also not subject to calculation, so the calcu- lation should use only the remaining bytes from SOH to CHK excluding both. The operation or operations to perform are not known, nor the order in which they are performed and neither is their complexity, but for what has been extrap- olated from the observations so far, the protocol is fairly simple and intuitive and so should be the checksum calculation. Using Z-Tool it was possible to intercept the communication taken place between that software and the Z-Wave controller. Although Z-Tool only performs some simple Z-Wave commands, they should be enough to provide relevant information regarding the checksum. Three examples of Z-Wave messages can be seen next: >01 03 00 02 FE <01 03 00 20 DC <01 03 00 15 E9

34 Since we have several excerpts of Z-Wave communication available, it is possi- ble to apply different checksum algorithms to try to find the one used by Z-Wave using a trial and error approach. Researching for possible checksum algorithms a small list of a few simple algorithms was found in [10], resulted in a list with three popular algorithms used to calculate 8 bit checksums:

- sum8;

- fletcher-8;

- xor8.

In a short description, the sum8 algorithm is the sum of all the bytes in the frame, the fletcher-8 is a simple sum of bytes in a slightly different way and the xor8 is the XOR operation of all the bytes in the frame. The fletcher-8 algorithm was easily discarded since its result is two 8 bit values that are appended to the message frame, not complying with the Z-Wave standard of only one checksum byte. The application of sum8 and xor8 algorithms, although size compliant with the Z-Wave checksum, resulted in values different from those expected. During the comparison process, by looking at the checksum written in binary form it was found that the Z-Wave checksum was the bitwise negation of the xor8. After some testing, this checksum calculation was found to be successful as it can be seen in the example below. Example: 0x03 ⊗ 0x00 ⊗ 0x02 = 0x01 NOT (0x01) = 0xF E

Full Message: 01 03 00 02 FE

5.2 Node Identification

A Z-Wave network is capable of addressing up to 232 devices. During the ini- tialization process, the Z-Tool identifies how many nodes are part of the network and its ID numbers. Adding one device to the network at a time and registering the differences between frames sent back and forth allowed to draw some very interesting conclusions. To begin with, mapping 232 device IDs requires, or it can be assumed to require, a fair amount of information. As stated earlier, [9, p. 17] and now [1, p. 20] ”In order to reduce the amount of data transferred in each frame, the system protocol preferably comprises operational procedures for masking the identifiers of devices addressed by a frame.”. These statements, from official Zensys documents shed important light on how the ID information can be found: it is masked. However, this masking procedure is not obvious. One thing that stands out in the first few messages the Z-Tool software exchanges with a new Z-Wave network configuration (using a device with ID=2 and before adding a second device) to obtain all the necessary information to interact with it are two

35 frames with an exceptionally large size (and with a lot of bytes with value 0x00). The frames are the following: <01 25 01 02 05 00 1D 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 01 C0 <01 2B 01 07 03 07 00 00 00 01 00 01 FE 80 FE 88 0F 00 00 00 FB 97 7F 82 07 00 00 80 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47

After adding a second device (with ID=7): <01 25 01 02 05 00 1D 43 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 01 80 <01 2B 01 07 03 07 00 00 00 01 00 01 FE 80 FE 88 0F 00 00 00 FB 97 7F 82 07 00 00 80 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47

The difference between these two situations are the above underlined bytes. Now the question is how can the byte 0x03 represent both the controller ID and the first device with ID=2 and byte 0x43 represents all the previous mentioned devices plus the second added device with ID=7? At first glance, it does not seem simple to decipher this mask, but representing these numbers in binary notation leads to a clearer view of the masking process. Taking a careful look at Table 5.2, is now clearer how the already known ID’s relate with the bytes sent. Byte 0x03 has bits 1 and 2 active, for a controller with ID=1 and a device with ID=2, and byte 0x43 has also bit 7 active and a new device with ID=7. This information seems to indicate a simple masking process, and by adding more devices to this network, it becomes a certainty: each bit represents one device ID. The bit position indicates its ID number.

Table 5.2: Byte masking table

Byte Position 8 7 6 5 4 3 2 1 0x03 0 0 0 0 0 0 1 1 0x43 0 1 0 0 0 0 1 1

5.3 Z-Wave Version

The last response to a request made by Z-tool software to the Z-Wave network is: >01 03 00 15 E9 <01 10 01 15 5A 2D 57 61 76 65 20 32 2E 37 38 00 01 9B

The response to the request with code 15 provides information that, on a first look, does not appear to be anything evident. Since there is no possible comparison, it is very difficult to make educated guesses on what that information is. Using the ASCII table as a reference, and converting the received bytes to their decimal and char equivalents it turned out to be rather interesting, as it is shown in Tables 5.3 and 5.4.

36 Table 5.3: Response to the version request of the Z-Tool Initialization Process

Hex 0x5A 0x2D 0x57 0x61 0x76 0x65 Char Z - W a v e Decimal 90 45 87 97 118 101

Table 5.4: Response to the version request of the Z-Tool Initialization Process

Hex 0x20 0x32 0x2E 0x37 0x38 Char 2 . 7 8 Decimal 32 50 46 55 58

In conclusion, the request with code 15 obtains the Z-Wave version of the protocol implemented in the Z-Wave controller can be obtained. The following information regarding Z-Wave versions can be found freely in the Internet [11]:

- 2.40 = Zensys Firmware 4.27;

- 2.48 = Zensys Firmware 5.02;

- 2.60 = Zensys Firmware 5.02 Service Pack 2;

- 2.78 = Zensys Firmware 5.02 Service Pack 3.

Hence, the Z-Wave dongle that was used in this work has a firmware with version 5.02 and a Service Pack number 3.

5.4 Device Interaction

The Z-Tool software, besides its initialization process, features a few options to test functionalities of common Z-Wave devices, for example: switching on and off a switch or a dimmer and dim the load up to a desired level. It also features the possibility of getting the name and location of Z-Wave devices in a network and setting new names for them. Tests were made in order to observe the network traffic when tasks are per- formed on devices in the network.

5.4.1 Basic Switch On a first test using the Qees Wall switch, Figure 5.1, here with ID=2, it was attempted to switch it on while it is not powered.

37 Figure 5.1: Qees Power

Intercepted Z-Wave frames in a communication are: >01 0A 00 13 02 03 20 01 FF 05 03 3F <01 04 01 13 01 E8 <01 05 00 13 03 01 EB

5.4.1.1 Turn On A first message is sent to turn the Qees Wall switch on using the Z-Tool software although it can also be turned on by means of a physical button. The second and third messages, underlined below, are at the moment unknown. Every time a request is made the first underlined message appears either directed to a spe- cific device or several. This message has been the same every time a message has been successfully delivered to the network. A confirmation could not be obtained, however so far this seems to be its meaning. Since the switch is not turned on, the controller should reply with some type of error saying it cannot find the node. To better understand how this process takes place, it is necessary to compare this message with a different one sent when the switch is powered, to turn it on. >01 0A 00 13 02 03 20 01 FF 05 03 3F <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

This results in the device being switched on. By comparing both scenarios were the switch was turned on, with and without the device being powered, it can be seen that apparently the controller tries to send the same message twice to the device when it does not acknowledge that a message was received the first time. Another important thing is that the byte marked in bold changed according to the device being powered or not. In the previous subsection 5.4.1, this byte had value 0x01, after being powered its value changed to 0x00. As such this indicates that value 0x01 is a Node Not Found and value 0x00 is a Node Found information.

5.4.1.2 Turn Off To actually see which command is sent to turn the switch on and off, it is neces- sary to turn the switch off using Z-Tool and compare the messages.

38 >01 0A 00 13 02 03 20 01 00 05 03 C0 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

The underlined byte 0x00 is different from the byte in the same position sent in previous message. When the device is turned on this byte has the value 0xFF. It is fair to deduce that this byte is the one that indicates the state that the switch shall be, either ON or OFF.

5.4.1.3 Get Status

To inquire the switch state it is necessary to use the command class BASIC and performe a GET command to the switch. The GET command is 0x02 as under- lined below. Also, as shown before in picture 4.4, following the command class code there is a command. The Node ID remains the same, 0x02. When the switch is OFF and a request for its status is made, the following messages are observed. >01 08 00 13 02 02 20 02 05 C3 <01 04 01 13 01 E8 <01 09 00 04 00 02 03 20 03 00 D0

Repeating the query when the device is turned on, makes evident the byte that contains the sate. In the last message from the total of the transmission, the underlined byte is the status of the switch. As observed and stated before, 0x00 means that the switch is turned OFF and 0xFF signals the ON state. >01 08 00 13 02 02 20 02 05 C3 <01 04 01 13 01 E8 <01 09 00 04 00 02 03 20 03 FF 2F

5.4.2 Dimmer Switch The ZDM230 multilevel switch, Figure 5.2, is also tested using Z-Tool. The soft- ware has a multilevel control that enables the user to dimm a load to a selected level. Besides a multilevel control, the ON and OFF buttons are also present and control the multilevel switch as if it were a binary switch.

5.4.2.1 Turn On

The multilevel switch has ID=7. When the multilevel switch is turned sent a Turn On command, the messages sequences is the following: >01 0A 00 13 07 03 20 01FF 05 03 3A <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

39 Besides the difference of the device ID, the message sent to the device is exactly the same as the one sent to turn on the Qees Power binary switch. It makes use of the same command class and the same method, GET, here represented with 0x20 and 0x01 respectively.

Figure 5.2: ZDM230 Dimmer Switch

5.4.2.2 Turn Off As stated in Section 4.2.1, everything leads to the belief that the multilevel switch is a specialization of the binary switch, and as such the commands used to oper- ate the binary switch are the same used for the multilevel switch. The other way around is not be true. To turn the multilevel switch off it is only necessary to send the same command as before with the value 0x00, as it can be seen below. >01 0A 00 13 07 03 20 01 00 05 03 C5 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

5.4.2.3 Get Status Since the multilevel switch is a specialization of switch, the procedure to get the current status of the former is similar to the one used for the latter, changing only the Node ID (in this case 7). With the dimmer regulated to about 20% of the load, the result of the enquiry was the following. >01 09 00 13 07 02 20 02 05 16 D1 <01 04 01 13 01 E8 <01 05 00 13 16 00 FF <01 09 00 04 00 07 03 20 03 19 CC

The third message in the previous response is similar to other messages already received but due to the different value of one of its bytes, 0x16 might have a dif- ferent meaning. When messages with a format like the one below are received, the byte shown as XX is always equal to the byte before the checksum in the original request, in this case, 0x16. <01 05 00 13 XX 00 CHK

40 Since there is a link between the request and one of the messages of the re- sponse, this might be used as a message tracking mechanism so that the controller knows from which device the response comes from. In every situation so far, there are only two situations present: either the two bytes before the checksum in the request do not exist and the response does not contemplate the message with the format above, or those two bytes exist and the response has the message with its XX byte with value equal to the one that the byte before the checksum has in the original request. Further studies of this situation would be required to confirm this information. The underlined byte in the fourth message is the returned state data, in this case 0x19 in decimal notation is 25. As in the previous case, this value is in percentage. At this point a new response stands out. To confirm that this is in fact the value of the multilevel switch being read, the next step was to regulate it to two known points: no load and full load. With no load, the value read is 0x00, at full load status the value is 0x64 or 100% as for the Qees Power Switch, in a few intercepted messages this is the result. No Load: <01 09 00 04 00 07 03 20 03 00 D5 Full Load: <01 09 00 04 00 07 03 20 03 63 B6

5.4.2.4 Dimm the Load

After being successful at turning the multilevel switch on and off, the next step is to dimm the multilevel switch to a desired level. For this to happen, it makes sense that there is one dedicated command class for this type of device, i.e. multilevel switches, and one command class for basic switches. However, it also makes sense to expect that the basic switch command class is supported by multilevel switches, since these can also react to ON/OFF commands accordingly. Using the Z-Tool multilevel control and regulating it to 97% results in receiving the following messages: >01 0A 00 13 07 03 20 01 61 05 03 A4 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

Once again the only difference is the value sent to the device, the type of re- quest sent is exactly the same. Value 0x61 written in decimal notation corresponds to 97, i.e. 97% of the possible dimm level. In conclusion, it can be said that the value sent to the multilevel switch can be either 0x00 or 0xFF to act as a binary switch, or from 0x01 (1%) to 0x64 (100%) if the desired behaviour is the one of a multilevel switch.

41 5.4.3 Power Meter 5.4.3.1 Instant Energy Consumption To read the instant energy consumption value measured by the power meter in- cluded with the Qees Power Switch, it is necessary to send a request to the device, read the value and interpret it. It is also necessary to have a load turned on by the switch. A 11 Watt lamp was used. As [12] states, ”The Module will report its instant or accumulated energy con- sumption to Z-Wave Controller.” and ”When receiving Meter Get Command, it will report Meter Report Command to the node of Grouping 1.” This document also specifies that the structure of both commands is:

Table 5.5: Meter Get Command Structure

Meter Get Command Class Meter Meter Get Scale

Table 5.6: Meter Report Command Structure

Meter Report Command Class Meter Meter Report Rate Type + Meter Type Precision + Scale + Size Meter Value 1 Meter Value 2

And how to calculate the final value from the message’s meter values fields. Meter (W) = Meter Value 1 * 256 + Meter Value 2 = result As it is already known, the structure of a Z-Wave frame includes a command class byte, after the byte that indicates the number of command bytes sent and before the command class command byte. Comparing with the command class list in [13] the command class found is 0x31, named SENSOR MULTILEVEL. In the message sequence immediately below and as referred in [12], after the command class code, comes the command class GET (0x04) and the Scale (0x02). The final byte is the checksum. >01 0A 00 13 02 03 31 04 02 05 2A FF <01 04 01 13 01 E8 <01 05 00 13 2A 00 C3 <01 0C 00 04 00 02 06 31 05 04 22 00 69 88

42 Therefore, according to [12] the following values for the various fields are obtained: Command Class Meter (0x31), Meter Report (0x05), Rate Type + Meter Type (0x04), Precision + Scale + Size (0x22), Meter Value 1 (0x00) and Meter Value 2 (0x69), 105 in decimal notation. According to the formula to calculate the instant energy consumption, the result is: Meter (W) = 0 * 256 + 105 = 105 Watts This is not coherent with the load attached to the binary switch, (11 Watt), but if the value read from the power meter is interpreted as 10,5 Watt, then it would be ok. Several loads were tested to evaluate this hypothesis, and they proved it to be true.

5.4.3.2 Accumulated Energy Consumption The power meter is capable of registering the total energy consumption of every load ever used by the device. Using the instantaneous values measured throughout the device life of operation, the device calculates the energy consumption. This counter can be reset if necessary. The request made to the device is structured like stated in [12] and similar to the structure of the previous request. The request uses the following commands: - 0x32 - Command Class Meter;

- 0x01 - Command Class Get;

- 0x01 - Scale;

- 0xD6 - Checksum.

The request is: >01 08 00 13 02 02 32 01 01 D6 <01 04 01 13 01 E8 <01 0E 00 04 00 02 08 32 02 01 A4 00 00 3F DD 88

The response to the previous request is interpreted as: - 0x32 - Command Class Meter;

- 0x02 - Command Class Report;

- 0x01 - Rate Type + Meter Type;

- 0xA4 - Precision + Scale + Size;

- 0x00 - Meter Value 1;

- 0x00 - Meter Value 2;

- 0x3F - Meter Value 3;

- 0xDD - Meter Value 4.

43 The total energy consumption calculation is detailed by the equation in [12]:

Accumulated Energy Consumption = Meter Value 1 * 232 + MeterV alue2 ∗ 216 +MeterV alue3∗28 +MeterV alue4∗20 = 0+232 +0+216 +63∗28 +221∗20 = 16128 + 221 = 16349

According to [14], the value read can be up to 5 decimals precision and is given in KW.h, hence the value should be read as 16349 KW.h. In section 1.3 it is stated that ”Measurements are accurate to 0.1 watt or 1% depending on the load size.”. Also according to the same document the calculated value has a given scale and precision. This leads to the conclusion that the value is in fact not 16349 but a decimal variation of it such as: 1,6349 or 16,349 for instance. Listing 5.1 is an excerpt of code taken from a project called Open-zwave. This project is meant to be a Z-Wave API with support for every Z-Wave de- vice. This specific code is taken from a file named Meter.cpp from [15], which is, as it is written at the beginning of the file, ”Implementation of the Z-Wave Command Class Meter”. Paying attention to a specific function in this file that is listed in 5.2, several details can be dissected. The first condition to be met is if data[0] variable is equal to the value of a variable declared at the beginning of the file, MeterCmd Report. In the response obtained earlier, the value of the MeterCmd Report was 0x02, hence this condi- tion is met, so the program execution flow enters the condition. This variable is depicted in Listing 5.2.

Listing 5.1: Excerpt of code from open-zwave Project

{ enum MeterCmd { MeterCmd Get = 0x01 , MeterCmd Report =0x02, MeterCmd GetSupported =0x03, //Version2Only MeterCmd ReportSupported =0x04, //Version2Only MeterCmd Reset =0x05 //Version2Only } ; } After entering into the part of the program that concerns the meter readings, it is necessary to decode the next few bytes. The first byte to be processed is the scale, here shown as data[2], which is used as an argument to function ExtractValueAsString. The second byte is used to determine, within a switch case cycle from which type of meter is the reading from. 0x01 for electricity meter, 0x02 for a gas meter and 0x03 for a water meter. Within the switch case cycle, the units are set for this type of reading with the value->SetUnits( c electricityUnits[scale] ); expression. This expression reads the position given by scale, in this case, the value returned by the ExtractVal- ueAsString function, which should be the first of the following depicted at the beginning of the Meter.cpp file, that is, the one with value 0 and shown in listing 5.3. Since what it is being discussed here are accumulated power consumptions it only makes sense that these are shown relative to time and as shown in section 4 of [12], the scale parameter can either be 0x00 for KWh or 0x02 for W, which is consistent with the variable disposition in the c electricityUnits[] array, position

44 0 for KWh and position 2 for W (Watt).

Listing 5.2: Excerpt of code from open-zwave Project

{ if (MeterCmd Report == (MeterCmd) d a t a [ 0 ] ) { string valueStr = ExtractValueAsString( & data[2], &scale );

if ( ValueDecimal ∗ v a l u e = m value. GetInstance( i n s t a n c e ) ) { i f ( value−>GetLabel() == ”Unknown” ) { s w i t c h ( d a t a [ 1 ] ) { c a s e 0 x01 : { // Electricity Meter value−>SetLabel( ”Electricity” ); value−>S e t U n i t s ( c electricityUnits[scale] ); break ; } c a s e 0 x02 : { // Gas Meter } c a s e 0 x03 : { // Water Meter } } } } } }

Listing 5.3: Excerpt of code from open-zwave Project

{ static char const ∗ c electricityUnits [] = { ”kWh” , ”kVAh” , ”W” , ”” } ; }

5.4.4 Sensor The HomeSeer HSM100 is a 3 in 1 device. It features an embedded motion detec- tor, temperature sensor and a luminance sensor. Moreover, it allows the controller to monitor its battery level. It is shown in Figure 5.3.

Figure 5.3: HSM100 3 in 1 Sensor

45 This device has one blue button, which is used to perform the inclusion/exclu- sion/awake processes. When awaken, the device will report back to the controller the data collected by each of its sensors upon request. At this point, because of the lack of interaction of the Z-Tool software with sensor devices it was necessary to use another tool named HomeSeer Pro. This tool is used in a personal computer with the Aeon Labs USB Z-Stick. After adding the device to the network, using the HomeSeer software, several informations about the sensor device were obtained. The HSM100 device manufacturer is: HomeSeer Tech, with ID=30=0x1E. The type is 2 and the ID is 1, although the meaning of this last mentioned id is still unknown at the moment. The supported command classes for this device are:

- 0x60 - Command Class Multi Instance

- 0x31 - Command Class Sensor Multilevel

- 0x70 - Command Class Configuration V2

- 0x84 - Command Class Wake Up

- 0x85 - Command Class Association V2

- 0x80 - Command Class Battery

- 0x72 - Command Class Manufacturer

- 0x77 - Command Class Node Naming

- 0x86 - Command Class Version

- 0xEF - Command Class Mark

- 0x20 - Command Class Basic

Pressing the blue button results in the device sending information to the net- work, specifically, the readout of each of its sensors. The ones that are relevant for this study are presented in the next subsections.

5.4.4.1 Temperature Using HomeSeer one can read all the sensor values. One of the informations sent to the network controller is the temperature of the sensor within the HSM100. By searching, within the messages exchanged with the node, for the command class SENSOR MULTILEVEL value 0x31 the following extract of messages is found: >01 0C 00 13 0B 05 60 06 03 31 04 05 03 B8 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA <01 0F 00 04 00 0B 09 60 06 03 31 05 01 2A 02 ED 63

In this case the node ID has value 0x0B. Both classes MULTI INSTANCE and SENSOR MULTILEVEL are present in this small excerpt of communication. For

46 the time being, the use of the MULTI INSTANCE command class is still unknown. The command class SENSOR MULTILEVEL is used to report the value of the temperature, in this case, since the value of the temperature is 74.9, according to the HomeSeer, this value must be represented in this excerpt of communication. Temperatures are not uncommon to vary between 30 and 105 Fahrenheit or -1 and 45 Celsius, therefore the values are expected to be found between the two sets of more commonly used temperature units. Due to the fact that values can possibly have four significant digits, it is likely that they are represented in two bytes. It is far more likely, that due to the fact that values can easily go up to four digits, they are represented as two different bytes. One byte can go up to 3 digits (255), but it is not enough to represent decimal values. There are two easy options to represent a number with four digits and a decimal parcel. Either using two bytes, one for each 2 digits, or using two bytes that can represent a number up to 65536. Either way, for representing the number 749 for example, using the first method the result is: 7 = 0x07 and 49 = 0x31. Using the second method, it is: 749 = 0x02ED. In the last frame of the responses from the device above just before the checksum byte, the two bytes match the latter result. To confirm this fact, a few more tests with different temperature values were performed. In the previous request, the byte just after the class SENSOR MULTILEVEL byte, 0x04, appears to be an indicator that a request for a new value is being made, a Sensor Get. In the response, the byte in the same position as the previous, just after the command class byte, appears to indicate that a response is being given, byte 0x05 Sensor Report.

5.4.4.2 Light Measurement

Similarly to the temperature reading, the luminance reading is displayed by the HomeSeer software. The luminance value ranges from 0% to 100% and one of the values read is 75%. Using a simple conversion of decimal to hexadecimal notation of the percentage value, results the number 0x4B, which is found in the following extract of traffic between the controller and the device. >01 0C 00 13 0B 05 60 06 02 31 04 05 03 B9 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA <01 0E 00 04 00 0B 08 60 06 02 31 05 03 01 4B EF

After several tests with different temperature values, it is confirmed that the byte before checksum is the luminance level. Much like in the temperature read- ing, there are indicators that a command class command Get is being sent, byte 0x04, and a response, command class command Report is being given, 0x05. Fur- thermore, both the request and the response encapsulate the MULTI INSTANCE command class as in the temperature reading. Figure 5.4 resumes what was stated previously.

47 Figure 5.4: Summary of Z-Wave Frame Structure for Luminance Responses

5.4.4.3 Multi Instance In subsections 5.4.4.2 and 5.4.4.1 two different values are read from the same device and one new Z-Wave feature was revealed, the MULTI INSTANCE command class. Every time a request is made using this command class, the bytes related to it in the request are exactly the same as the ones present in the response, i.e. for the luminance reading. Figure 5.5 shows this.

Figure 5.5: Multi Instance Command Class Structure

When the luminance request is compared to the temperature request read- ing some conclusions can be drawn. When reading the temperature, the third MULTI INSTANCE byte is the same both in the request and the response with value 0x03, when reading the luminance that same byte has value 0x02 as seen below in Figure 5.6.

Figure 5.6: Multi Instance Command Class Structure Comparison

48 One possible explanation for this fact is that the reading is made by the same component but uses different channels. Much like a multi channel Analog to Digital Converter, a channel has to specified so that a reading can be obtained as the diagram in Figure 5.7 details.

Figure 5.7: Multi Instance Data Selection Possible Diagram

5.4.4.4 Battery Level

The battery level displayed by HomeSeer is 14%. The battery level must be present in this excerpt of the transmission, as all the other readings from the sensors do. >01 09 00 13 0B 02 80 02 05 03 68 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA <01 09 00 04 00 0B 03 80 03 0E 77

The battery level is obtained by making a request for information using the BATTERY command class, value 0x80 similar to the previous requests made using the SENSOR MULTILEVEL command class. There is, however a difference between these two command classes. The byte value used to request information in the SENSOR MULTILEVEL command class is 0x04 and in the BATTERY command class that same request uses value 0x02. The same happens with the byte used to report information, command class SENSOR MULTILEVEL uses value 0x05 and the BATTERY command class uses 0x03. The value of the battery level can be obtained by converting 14 to hexadecimal, that is 0x0E, value found in underlined byte before the checksum in the last message of the transmission excerpt.

5.4.4.5 Motion Sensor

The HSM100 is a motion sensor that can respond to motion in front of it. However, this is only possible if the device is associated with another one. The motion sensor is meant to trigger some kind of action, therefore an association to a device that performs that kind of action is required.

49 5.4.5 Device Association Z-Wave devices are capable of association between each other. Groups of devices can be triggered by a state from a single device. These actions happen without the knowledge of the Z-Wave controller, in fact they are interactions between the devices and only between those devices. To illustrate this feature an association was made between the Qees Power Switch and the ZDM230 Dimmer. The association request involves the following data:

- Node ID

- Command Class Association

- Command Class Association Set

- Group ID

- Target Node ID

The first two fields to know are the ID’s of the nodes involved, 0x02 for the Qees Power and 0x07 for the ZDM230 dimmer. The command class association is represented with 0x85 as it is described in [13] and the command class association command is expected to be represented with 0x01. Furthermore, in any Z-Wave request, just before the checksum, at least one byte is used for some sort of control mechanism for the messages. In this example a tentative value of 0x01 was used. The request to perform an association between the two devices is included in the following sequence: >01 0A 00 13 07 04 85 01 01 02 01 63 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

The two latest responses are the acknowledgement that the association process went well. After this process, if the button on the ZDM230 dimmer is pressed once, it turns on the Qees Power Switch and pressed once again turns it off, hence an association exists between two devices. After the association process takes place, the interaction between both devices occurs without the main network controller, this is why this topic was not further explored.

5.4.6 Configuration Parameters There are six known configuration parameters for the HSM100 device, as described in [16]:

- Off Delay;

- Led Enable;

- Sensitivity;

- Wakeup Interval;

50 - Device Activation State;

- Sleep State.

These parameters can also be configured in HomeSeer. The Wake Up Interval parameter is configured by using the WAKE UP command class. The remaining 5 parameters are configured using the CONFIGURATION command class. Each parameter is configured separately. There is one request to change a parameter and a subsequent response to confirm that change. Each parameter has a code, included in table 5.7.

Table 5.7: Codes of Configuration Parameter for the HSM100 device

Off Delay 0x02 Sensitivity 0x01 Led Blink 0x03 Sleep State 0x05 Device Activation State 0x06

The following excerpt of Z-Wave communication is obtained when using Home- Seer to configure the Wake Up Interval parameter with a new value of 10 minutes. >01 00 13 0B 06 84 04 00 02 58 01 05 03 31 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

Before any further analysis it is necessary to find out how are the 10 minutes value encoded in the frame. The values can range from minutes up until hours. And the time value written in the message can also have a unit of seconds or hours. 10 minutes are 600 seconds and 0,1666 in hours. 600 seconds written in hexadecimal are 0x258, which can be found in the message in the underlined bytes 0x02 and 0x58. Since up until a day can be encoded and it is 86400 seconds, in hexadecimal it results in 0x15180. Reversing the process, value 0x15180 would be encoded into 3 bytes, 0x01, 0x51 and 0x80, which means all underlined bytes in the message correspond to that parameter’s value. The byte with value 0x04 indicates that this is a Set value command which is preceded by the command class WAKE UP byte with value 0x84. To inquire the device regarding its configuration of the Wake Up Interval pa- rameter, it is necessary to make the request that is shown in the following sequence of messages: >01 09 00 13 0B 02 84 05 05 03 6B <01 04 01 13 01 E8 <01 05 00 13 03 00 EA <01 0C 00 04 00 0B 06 84 06 00 01 68 01 10

51 In this case, the request uses a Wake Up Interval GET command with value 0x05 to inquire the device about the value of the parameter. Later, in the last message the device answers. Byte with value 0x06, which comes after byte with value 0x84 indicates that the message is a Report with the value of the parameter in the bytes with value 0x0168, or 360 in decimal, that is a total of 6 minutes. The default Sensitivity value was changed from 200 (0xC8) to 255 (0xFF). To set the Sensitivity to 255: >01 0C 00 13 0B 05 70 04 01 01 FF 05 03 63 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

As it can be noted above 0xFF represents the Sensitivity value. That value is configured using the CONFIGURATION command class, byte 0x70, a parameter with value 0x04 followed by the parameter number, 0x01 for the sensitivity and another byte with value 0x01 which function is unknown. The next value is the Sensitivity value. To ensure that this value was correctly sent, the device sensitivity is then read using the HomeSeer Web Interface. Among other communications the result is: >01 0A 00 13 0B 03 70 05 01 05 03 9C <01 04 01 13 01 E8 <01 05 00 13 03 00 EA <01 0B 00 04 00 0B 05 70 06 01 01 FF 77

Apparently, the Sensitivity is read by sending a request using the CONFIG- URATION command class, 0x70, with the GET parameter 0x05, to the configu- ration item 0x01 also known as Sensitivity. The response is very straightforward. As expected the response is 0xFF (255), as setted before. After the CONFIGURATION command class byte 0x70, comes the byte that indicates a response 0x06 followed by the parameter code, in this case 0x01 for Sensitivity, and another byte 0x01 with meaning unknown just before the actual value. Another test was conducted to ensure that this interpretation is valid. Set the Sensitivity to 200: >01 0C 00 13 0B 05 70 04 01 01 C8 05 03 54 <01 04 01 13 01 E8 <01 05 00 13 03 00 EA

Get the current value of Sensitivity: >01 0A 00 13 0B 03 70 05 01 05 03 9C <01 04 01 13 01 E8 <01 05 00 13 03 00 EA <01 0B 00 04 00 0B 05 70 06 01 01 C8 40

The rest of the parameters are configured as the Sensitivity, but the byte code to be used is different and consequently the message will suffer some changes.

52 All the parameters were tested exactly the same way as the Sensitivity was, and all of them worked.

5.4.6.1 Dimmer Switch Configuration Parameters The ZDM230 multilevel switch features two blue LED in the front of the device. Those LED’s are used among other things to acknowledge the current device state (ON or OFF ). Several other features are available to the user. One of the most important configuration parameters allows the user to configure one of the LED to be used as a night light. It features two options: LED on when the switch is ON or LED off when the switch is ON. To configure the Night Light parameter it is necessary to use the CONFIGU- RATION command class and the parameter number and value to be sent. In this case, each parameter number and range of allowed values is described in [18] as well as [17]. It is possible to configure the device using this information and generating a frame that includes a SET command to the CONFIGURATION command class with a given value (in this case either 0 or 1). The excerpts of communication between the Z-Wave controller and the device below demonstrate how to configure the Night Light parameter. To test the parameter setting feature the HomeSeer software was used. The essential information to set a parameter on a Z-Wave device is:

- Name: Night Light;

- Parameter Number: 3;

- Range of Values: 0-1.

To turn the Night Light parameter OFF when the switch is ON and use it as a night light the following message is sent: >01 0C 00 13 07 05 70 04 03 01 01 05 22 B2 <01 04 01 13 01 E8 <01 05 00 13 22 00 CB

On the request, the first underlined byte represents the parameter number to be configured and the second underlined byte represents the value of that param- eter. Below is the message necessary to turn the Night Light parameter ON when the switch is ON. To turn the LED ON when the switch is ON as it can be seen, this request confirms what was stated before for the previous excerpt. >01 0C 00 13 07 05 70 04 03 01 00 05 22 B3 <01 04 01 13 01 E8 <01 05 00 13 22 00 CB

53 Besides the Night Light parameter, there are many others that can be config- ured for this particular device. Below is a list of all the ZDM230 multilevel switch parameters:

- Set Ignore Start Level Bit When Transmitting Dim Commands;

- Suspend Group 4;

- Disable Group 4 During a Dim Command;

- Night Light;

- Invert Switch;

- Ignore Start Level When Receiving Dim Commands;

- Do not Send Level Command After Transmitting Dim Commands;

- Adjusting Dim Rate;

- Enable Shade Control Group 2;

- Enable Shade Control Group 3;

- LED Transmission Indication;

- Poll Group 2 Interval (minutes).

The parameter number does not follow the order of the list taken from [18]. All configuration parameters will be reset to their default value when the ZDM230 device is erased from the Z-Wave network, that is, when the network controller is reset to its default configuration. This is just an example of how configuration parameters can be configured. This should be similar for other devices, with the exception of parameter numbers and values which are device specific.

5.4.7 Dimmer Switch Supported Features By pressing the button Get Names and Locations in the Z-tool GUI, the ZDM230 Dimmer responds and the next message is an excerpt of that communication. >01 04 00 60 07 9C <01 04 01 60 01 9B <01 14 00 49 84 07 0E 04 11 01 26 27 85 73 70 86 72 EF 20 26 50 01 F1

When any of the buttons on the multilevel switch is pressed, the message received is the same. The first underlined byte is the node ID of the device, followed by the size of the payload; byte with value 0x0E or 14 in decimal and the next three underlined bytes are the same received during the Z-Tool initialization routine. The last group of underlined bytes are all part of the list of command classes in [19]. This

54 document provides valuable information about the list of command classes and the byte values that identify them. So far this information has proved to be reliable. Below, is a list of command classes that correspond to the bytes underlined above:

- 0x26 - Command Class Switch Multilevel

- 0x27 - Command Class Switch All

- 0x85 - Command Class Association

- 0x73 - Command Class Powerlevel

- 0x70 - Command Class Configuration

- 0x86 - Command Class Version

- 0x72 - Command Class Manufacturer Specific

- 0xEF - Command Class Mark

- 0x20 - Command Class Basic

- 0x26 - Command Class Switch Multilevel

- 0x50 - Command Class Basic Window Covering

5.4.8 Manufacturer Information & Device Type The same document provides information to find more details such as: ZDM230 type of device is 0x11, the manufacturer ID (01D), which corresponds to the ACT manufacturer, type 44 4D, ID (33 30), and Z-Wave device version (Lib 1.99 and App 1.10). Although [19] provides some insight about the meaning of these ZDM230 features, most of its meaning is still unknown. For instance, type of device byte 11H, can be a switch, controller, dimmer, transmitter, thermostat, shutter and other (the type of hardware) or a controller, static controller, slave or routing slave (the type of device within the network). By cross-referencing the information in [19] and [13], a confirmation can be obtained regarding the meaning of each of the command classes. The ID Manufacturer list is also mostly unknown as well as the device type, but through a comparison with additional information present in [19], two lists shown in tables 5.8 and 5.9 below. Further investigation upon devices of different manufacturers and types would be required to complete these tables.

5.4.9 Node Version Information One of the command classes supported by all three devices in this study is the VERSION command class, with byte value 0x86. As the name already implies, this command class provides the user with version information regarding a device.

- Product Type ID: 0x444D

55 - Product ID: 0x3330

- Library Type: 0x00

- Protocol Version: 0x01

- Protocol Sub Version: 0x63

- Application Version: 0x01

- Application Sub Version: 0x0A

To request the version information from the device, the request that starts the following message sequence was sent by HomeSeer. >01 07 00 13 07 02 86 11 79 <01 04 01 13 01 E8 <01 0D 00 04 00 07 07 86 12 06 01 63 01 0A 0D

Based on previous successful attempts of interaction with Z-Wave devices, the values to request the version information were found to be low, such as 0x02, 0x03 or 0x04. The remaining bytes in the frame follow the general Z-Wave frame format. In contrast, the analysis of this request reveals that the value of Get Version command byte is 0x11. The version information for ZDM230 can be found in [18].

ID Device Type 0x01 CONTROLLER 0x10 APPLIANCE 0x11 DIMMER 0x20 SENSOR 0x12 TRANSMITTER 0x08 THERMOSTAT 0x09 WALL ROLLER SHUTTER

Table 5.8: Device Type List

ID Manufacturer 0x01 ACT 0x02 DANFOSS 0x12 HOUSEKEEPER 0x60 EVERSPRING 0x59 HORSTMANN 0x77 INNOVUS 0x7A MERTEN

Table 5.9: Manufacturer ID List

56 By comparing this information with the received response, it is noticeable that there are common byte values, underlined in the excerpt above, and some parameters that do not have the same value.

- Product Type ID: 0x444D

- Product ID: 0x3330

- Library Type: 0x00

To obtain the Version Information of the Qees Power Switch is similar. The only difference is the device’s Node ID in the request. >01 07 00 13 02 02 86 11 7C <01 04 01 13 01 E8 <01 0D 00 04 00 02 07 86 12 06 02 33 01 0B 5A

In this device, the following software versions are available:

- Protocol Version: 0x02

- Protocol Sub Version: 0x33

- Application Version: 0x01

- Application Sub Version: 0x0B Comparing this request with the previous one, some similarities are found between the responses. The first underlined bytes, 0x12 and 0x06 are the same independently of the device being inquired. At least for byte with value 0x12 just after command class byte 0x86 it can be assumed that it signals that the message is a report from the VERSION command class. Consequently, byte with value 0x11 in the initial message can be interpreted as a Get command.

57 58 Chapter 6

Graphical User Interface

To control all the Z-Wave devices added to the network using the console, a graphical user interface (GUI) was developed. This GUI represents the iHotel concept. Since this system is only a concept, the Z-Wave functions here are the ones studied in this project. For demonstration purposes, the GUI has a full menu with other function the concept should feature. Among these functions are:

- VoIP Phone

- Hotel Services

- Distributed Audio Control

- Digital Frame

- Hotel Statistics

The GUI was developed using C++ and designed using the Qt graphic inter- face libraries. The decision to use the Qt libraries was supported by the extensive documentation readily available and by the fact that cross-compiling the libraries for this embedded system is fairly simple and also well documented. Although the core part of this project is the interactivity with Z-Wave devices, the GUI contains not only the Z-Wave devices menu but also options for all other iHotel functions. Functions that are not directly related to the device interaction are not active, therefore they cannot be used. Further down, the implemented function will be explored. The GUI is part of a larger system constituted by:

- Graphical User Interface

- Socket2Serial software

- Hardware Interface with the Z-Wave Controller

A diagram showing the connections between the software and hardware of the system is shown in figure 6.1 below.

59 Figure 6.1: System Connections Overview

As the picture shows the GUI interfaces with the Socket2Serial software through a socket connection which in turn interfaces with the Z-Wave controller by mean of a UART device driver.

6.1 Main Screen

Although a text based interface could be more than enough, a graphical design was preferred to give a modern style to the GUI and augment its attractiveness and intuitiveness. Figure 6.2 displays the GUI main screen. Each of the buttons features a iHotel system function. The main screen of the application features different types of Qt objects, dialogs, buttons and other items. Each of these objects uses a specific Qt class that allows the object to have its properties altered through a set of available methods and even extended by creating new methods to those classes. The base class for this application is MainWindow and inherits from Qt’s class QMainWindow. In Figure 3.3 a diagram of how the GUI’s objects classes are related between themselves is shown. This diagram is valid for all of the different screens that

60 feature system functionalities. The exception is that some screens use additional objects and therefore also use additional classes, that have as base class QWid- get; some of these classes are: QAbstractSlider, QDial, QSlider, QProgressBar, QSplashScreen, QLineEdit and QMainWindow.

Figure 6.2: Graphical User Interface Main Screen

6.2 Socket2Serial - Graphical User Interface

As already stated, the Socket2Serial program, described in detail in chapter7, interacts with the GUI through a network socket. Qt features a library, QTcp- Socket, that enables socket communication of data streams through a TCP socket. The main reason for using this Qt library is the fact that is written in C++ so integration with the rest of the GUI is easier and cleaner. An alternative is the BSD sockets API written in C, but since the QTcpSocket library is based on it, it would not make sense to use an old API in C within a C++ application. A class named Client is defined to represent the system as a client of the Socket2Serial component, thus making it the system server. To use this class, a pointer to an object of its type is declared within the MainWindow class. Besides that, using a Qt library has a big advantage, the Qt Signals and Slots mechanism. This Qt abstraction is used to link GUI controls and/or functions through their behaviour by means of events that are sent and received. For example, when a GUI control is activated or controlled, a Signal is sent to a Slot that has previously been linked with. That slot, in turn executes a specific function. The GUI acts as a ”client” of the Socket2Serial component, this is shown in Figure 6.3 below. Hence it has a Client object that, as a result of interfacing with the Z-Wave controller and a TCP socket, makes use of two classes: ZWave and QTcpSocket.

61 Figure 6.3: Main Window Classes Relationship

Using the QTcpSocket library, a connection is established every time a message is sent and/or received by the Z-Wave network. Additionally, a class named ZWave was created to aggregate all the details regarding the Z-Wave protocol, frame building, checksum calculation, functions to send and receive data and other. Both classes are used by the Client class, a pointer to QTcpSocket is declared and a ZWave object is instantiated as seen in Figure 6.4.

Figure 6.4: Client Object Relationship

62 When the GUI initiates, a verification is made to ensure that the Socket2Serial software is ready to communicate. Listing 6.1 below shows the constructor of the main window. In the main window constructor a connection is made to see if new data is available using the signal readyRead(), if an error occurs, a connection is made to enquire regarding the error type. The error is returned through the QAbstractSocket::SocketError variable and displayed in the command line.

Listing 6.1: Main Window Constructor

Client :: Client(QWidget ∗ p a r e n t ) : QDialog(parent) { // Create a socket and configure it. tcpSocket = new QTcpSocket(this );

t h i s −>ZW IP Adress = ”localhost”; t h i s −>ZW Port Adress = 12345; // Define when a readSocket() and SocketError() are invoked. connect(tcpSocket , SIGNAL(readyRead()) , this , SLOT(readSocket ())); connect(tcpSocket , SIGNAL(error(QAbstractSocket :: SocketError)) , this , SLOT(displayError(QAbstractSocket :: SocketError ))); } Whenever it is necessary to send a new message to the Socket2Serial compo- nent, a general function is available. For each message the function establishes a new connection with the server and sends a stream of data. Also, a Signal is emit- ted every time the socket has new incoming data and the readSocket() function is invoked to deal with that data. This function is depicted in listing 6.2.

Listing 6.2: General Function to Send Data

void Client::writeSocket(const char message[] , int message s i z e ) { blockSize = 0; tcpSocket −>a b o r t ( ) ; // Establishes a socket connection to the host and sends the message[] data through it. tcpSocket −>connectToHost(ZW IP Adress , ZW Port Adress ) ; tcpSocket −>write(message , message s i z e ) ; } Function 6.3 below is responsible for a first analysis of the incoming data. This consists of checking if a valid Z-Wave message has been received. At this point a valid message has to meet the following requirements:

- Starts with a 0x01 byte.

- Has the correct size.

- Has a valid checksum.

Listing 6.3 shows how these requirements are met. The incoming data is anal- ysed to look for a byte with value 0x01. If that byte is found, the checksum byte is searched for and compared to a calculation of what it is expected to be. Func- tion network.checksum(message received, size) returns the expected checksum. If the comparison result is positive the message is considered valid and the function network.decodeMessage(message received, size) is inked to decode it. If the check- sum calculation is not valid the message is considered invalid and according to the Z-Wave protocol specification a NAK, not acknowledge, is sent to the network.

63 Listing 6.3: Client::readSocket() Function void Client :: readSocket() { ... // Verify if it is a valid Z−Wave frame . if( (message received[0] == ”0x01”) ) { int checksum result = network.checksum(message received , size); // Perform a checksum validation of the incoming frame. if (checksum read == checksum r e s u l t ) { ... // Pass the frame data on to be decoded. network . decodeMessage(message received , size); } e l s e { qDebug ( ) << ”CHECKSUM FAILED ! ” ; } } e l s e { // If the data is not a valid Z−Wave frame, report error. const char message2[1] = {0 x18 } ; i n t s i z e message2 = sizeof(message2); Client :: writeSocket(message2 , size m e s s a g e 2 ) ; }

if (tcpSocket −>bytesAvailable () < b l o c k S i z e ) r e t u r n ; }

6.3 Z-Wave Devices

6.3.1 Switch The Qees Power Switch control window enables the user to turn the device either ON or OFF. Furthermore, the consumption values can be read, see picture 6.2.

Figure 6.5: Switch Graphical User Interface

Decoding a Z-Wave message implies that the program must be prepared to receive any type of these messages. In this case, there are two major command classes that have to be supported: Basic and Meter. For the time being only the Meter command class is supported. It was decided not to implement the Basic command class since it added no immediate value because of its simple

64 usage to this study. Other command classes are more interesting and therefore priority will be given to those. Also, when a request to set a given status is sent, a response with the current status is not sent back, only the confirmation that the status has been set, this is a characteristic of the Z-Wave protocol and can be observed in subsection 5.4.1.2. The only thing that is replied to a Z-Wave message is an acknowledge, not acknowledge or not available. In fact, the only way to be absolutely sure about the switch status is to ask the device for its status. Listing 6.4 shows the function used to ask the device for its status. Listing 6.4: Switch On Function

void MainWindow:: on d e v i c e 0 1 p u s h B u t t o n O n c l i c k e d ( ) { const char message[11] = {0x01, 0x09, 0x00, 0x13, 0x02, 0x03, 0x20, 0x01, 0xFF, 0x01, 0x3B } ; int size = sizeof(message); t h i s −>c l i e n t −>writeSocket(message , size ); } The Meter command class is responsible for receiving details related to the power consumption of the load to which the switch is connected to. The details to be received are:

- value - power consumption in kWh;

- precision - value precision;

- scale - value scale;

- size - number of bytes of value.

An example of a request and subsequent response is shown in subsection 5.4.3. Listing 6.5 shows the part of the decodeMessage() function responsible for decoding the response to the consumption values request. The Command Class Meter section of the ZWave::decodeMessage() function is responsible for extracting the value of the meter, but not only that. Also, the values of Scale, Mask and Precision are extracted here. These are used to calculate the value and present it correctly to the user. Details about how these are interpreted are still not completely known at this point. These details are discussed in subsection 5.4.3. Listing 6.5: Meter Command Class Function

...

c a s e COMMAND CLASS METER: // If it is a meter report then extract scale, precision and size data. if (frame[8] == METER REPORT) { scale = ( (unsigned char)frame[10] & METER REPORT SCALE MASK ) >> METER REPORT SCALE SHIFT ; precision = ( (unsigned char)frame[10] & METER REPORT PRECISION MASK ) >> METER REPORT PRECISION SHIFT ; size = (unsigned char)frame[10] & METER REPORT SIZE MASK ; short tmpval; // Extract the meter report value. switch(size) { c a s e 1 : value = (signed char)frame[11]; break ; c a s e 2 : tmpval = ( (unsigned char)frame[11] << 8) + (unsigned char)frame[12]; value = (signed short)tmpval; break ; d e f a u l t :

65 value = ( (unsigned char)frame[11] << 24 ) + ( (unsigned char)frame[12] << 16 ) + ( (unsigned char)frame[13] << 8 ) + (unsigned char)frame[14]; value = (signed int)value; break ; }

switch(frame[9]) // Meter Type + Rate Type { ...

if (scale == 0) { ... }

...

6.3.2 Dimmer

Figure 6.6: Dimmer Graphical User Interface

Using the controls shown in picture 6.6 it is possible to switch the load connected to the dimmer and to regulate it to a desired power level. As previously done with the switch, the Z-Wave messages sent to the device to turn it both ON and OFF are hard coded into the GUI component, not using any specific command class. Listings 6.6 and 6.7 show the functions used to turn the dimmer on and off, respectively. These functions prepare the Z-Wave messages to be sent to the Socket2Serial program and from there to the Z-Wave controller. Before data is sent to the Socket2Serial component, its checksum is calculated and a message is built according to the Z-Wave protocol. After this the message is ready to be sent to the Z-Wave controller. Listing 6.6: Dimmer On Command Class Function

void MainWindow:: on ZDM230 on pushButton clicked ( ) { const char ZDM230 on [ 1 3 ] = {0x01, 0x0B, 0x00, 0x14, 0x01, 0x04, 0x03, 0x20, 0x01, 0xFF, 0x05, 0x0A, 0x37 } ; i n t ZDM230 on size = sizeof(ZDM230 on ) ; t h i s −>c l i e n t −>writeSocket (ZDM230 on , ZDM230 on size ) ; // Set the value of the GUI controls to the same one sent to the device. ui−>d i a l −>setValue(100); ui−>Z D M 2 3 0 horizontalSlider −>setValue(100); ui−>ZDM230 progressBar−>setValue(100); }

66 Listing 6.7: Dimmer Off Command Class Function void MainWindow:: on Z D M 2 3 0 o f f p u s h B u t t o n c l i c k e d ( ) { const char ZDM230 off [ 1 3 ] = {0x01, 0x0B, 0x00, 0x14, 0x01, 0x04, 0x03, 0x20, 0x01, 0x00, 0x05, 0x0B, 0xC9 } ; i n t Z D M 2 3 0 o f f size = sizeof(ZDM230 off ) ; t h i s −>c l i e n t −>writeSocket(ZDM230 off , Z D M 2 3 0 o f f s i z e ) ; // Set the value of the GUI controls to the same one sent to the device. ui−>d i a l −>setValue (0); ui−>Z D M 2 3 0 horizontalSlider −>setValue (0); ui−>ZDM230 progressBar−>setValue (0); } If the value is changed on the dial then Qt executes the on dial valueChanged() function: the value returned from the dial is converted to a valid number to be sent as part of the message and a new checksum value is generated and substituted in the pre-defined message. The resultant message is then sent to the network and the dimmer is actuated accordingly. Listing 6.8 shows how this process takes place and further information about setting a dimmer value can be seen in subsection 5.4.2.4.

Listing 6.8: Dimmer Change Value Function void MainWindow:: on d i a l valueChanged(int value) { // If the dial is rotated, the value changes and has to be sent to the device. i n t i = 0 ; int result = 0; char ZDM230 dimmer value [ 1 1 ] = {0x01, 0x09, 0x00, 0x13, 0x04, 0x03, 0x20, 0x01, 0x00, 0x05, 0xFF } ;

ZDM230 dimmer value[8] = value; // Recalculate the checksum to be incorporated in the frame to be sent. result = 0xFF ˆ ZDM230 dimmer value[1]; // first value f o r ( i =2; i < 1 0 ; i ++) { result ˆ= ZDM230 dimmer value [ i ] ; } // Encapsulate the dimmer value onto the frame. ZDM230 dimmer value[10] = result; // Send the new frame. i n t ZDM230 dimmer value size = sizeof(ZDM230 dimmer value ) ; t h i s −>c l i e n t −>writeSocket(ZDM230 dimmer value, ZDM230 dimmer value size ) ; }

6.3.3 Sensor

Figure 6.7: Sensor Graphical User Interface

67 To display values sent from the 3 in 1 sensor, HSM100, the GUI features a screen shown here in picture 6.7. The GUI features information about temperature, light level and battery level upon device request. These requests are shown below in listings 6.9, 6.10 and 6.11 and are already ready to be sent to the Socket2Serial program.

Listing 6.9: Get Temperature Request void MainWindow:: on HSM100 pushButton GetTemperature clicked ( ) { const char temperature[14] = {0x01, 0x0C, 0x00, 0x13, 0x03, 0x05, 0x60, 0x06, 0x03, 0x31, 0x04, 0x05, 0x03, 0xB0 } ; int temperature size = sizeof(temperature); t h i s −>c l i e n t −>writeSocket(temperature , temperature s i z e ) ; }

Listing 6.10: Get Light Level Request void MainWindow:: on H S M 1 0 0 p u s h B u t t o n GetLightLevel c l i c k e d ( ) { const char light l e v e l [ 1 4 ] = {0x01, 0x0C, 0x00, 0x13, 0x03, 0x05, 0x60, 0x06, 0x02, 0x31, 0x04, 0x05, 0x03, 0xB1 } ; i n t l i g h t l e v e l size = sizeof(light l e v e l ) ; t h i s −>c l i e n t −>writeSocket(light level , light l e v e l s i z e ) ; }

Listing 6.11: Get Battery Level Request void MainWindow:: on H S M 1 0 0 p u s h B u t t o n GetBatteryLevel c l i c k e d ( ) { const char battery l e v e l [ 1 4 ] = {0x01, 0x09, 0x00, 0x13, 0x03, 0x02, 0x80, 0x02, 0x05, 0x03 , 0 x60 } ; i n t b a t t e r y l e v e l size = sizeof(battery l e v e l ) ; t h i s −>c l i e n t −>writeSocket(battery level , battery l e v e l s i z e ) ; } For the time being, battery information is not available since it belongs to a different command class, Battery. At this point, only the Sensor Multilevel command class was implemented. In subsubsection 5.4.4.4, it is demonstrated how the battery level readings should be interpreted. Listing 6.12 shows part of the decodeMessage() function responsible for interpreting luminance and temperature reports.

Listing 6.12: Sensor Multilevel Command Class Function c a s e COMMAND CLASS SENSOR MULTILEVEL: // If a data report has been received from the sensor. i f ( frame [ 8 ] == SENSOR MULTILEVEL REPORT) { // Extract scale , precision and size data. int scale = ( (unsigned char)(unsigned int)frame[10] & SENSOR MULTILEVEL REPORT SCALE MASK ) >> SENSOR MULTILEVEL REPORT SCALE SHIFT ; int precision = ( (unsigned char)(unsigned int)frame[10] & SENSOR MULTILEVEL REPORT PRECISION MASK ) >> SENSOR MULTILEVEL REPORT PRECISION SHIFT ; int size = (unsigned char)(unsigned int)frame[10] & SENSOR MULTILEVEL REPORT SIZE MASK ; i n t v a l u e ; short tmpval; // Extract the value depending on its size. switch(size) { c a s e 1 : value = (signed char)(unsigned int)frame[11]; break ; c a s e 2 : tmpval = ((unsigned char)(unsigned int)frame[11] << 8) + (unsigned char (unsigned int)frame[12]; value = (signed short)tmpval; break ; d e f a u l t : value = ( (unsigned char)(unsigned int)frame[11] << 24 ) + ( (unsigned char) (unsigned int)frame[12] << 16 ) + ( (unsigned char)(unsigned int)frame[13] << 8 ) + (unsigned char)(unsigned int)frame[14];

68 value = (signed int)value; break ; } if (precision > 0) { value = value / pow(10 , precision) ; } // Print the values according to their nature. switch((unsigned int)frame[9]) { c a s e SENSOR MULTILEVEL REPORT LUMINANCE: if (scale == 0) { qDebug(”Luminance measurement received : %d”,value ); } e l s e { qDebug(”Luminance measurement received : %d Lux”,value ); } break ; c a s e SENSOR MULTILEVEL REPORT TEMPERATURE: if (scale == 0) { qDebug(”Temperature level measurement received : %d C”,value); } e l s e { qDebug(”Temperature level measurement received: %d F”,value); qDebug ( ) << ”Convert to Farenheit!”; } break ; default: // Exception qDebug(”Sensor type 0x%x not handled”,(unsigned char)(unsigned int)frame[9]); break ; }

6.4 Configurations

Figure 6.8: Configurations Graphical User Interface

As described previously the GUI connects with the Socket2Serial component through a socket connection, and in order to do so, it needs an address and an available port. These two parameters are configured at this configurations screen. Furthermore, the system provides a place to configure another socket connection, but with the main hotel server. For both connections, it is necessary to configure the IP address and the port. In this project, when the Socket2Serial component is initiated, two parameters are passed onto it: IP and port. These two parameters are defined by the developer and are fixed and must also be configured in the GUI configuration screen so that the GUI can connect with the Socket2Serial. Further development would be necessary regarding the hotel server configura- tions, since these are meant to be used when a hotel features a network of iHotel

69 systems connected to a central server. At this point, an option to configure the system time is provided for debug purposes.

70 Chapter 7

Socket2Serial Interface Software

This software is essentially a message router, from the TCP socket to the serial port, where the Aeon Labs USB Z-Stick is connected. The interface between the Z-Wave network and the embedded system or a standard personal computer is established by means of a USB device. By examining this device, the Z-Wave network controller, up close it was possible to determine that it consists of no more than a Z-Wave radio transceiver embedded in a microcontroller connected through a standard UART to USB signal converter named Silicon Labs CP2102. The microcontroller is already pre-programmed with the Z-Wave Application Pro- gramming Interface (API) application software. This API interprets commands and the application software acts upon the network and/or its devices accordingly and manages all the network activity. This software, designated Socket2Serial handles the communication between the user interface and the Z-Wave Controller device: it receives commands through a TCP socket connection and sends them to the Z-Wave device to be interpreted by the Z-Wave API, and receive commands from the Z-Wave device, sending them through the same TCP socket connection. To better illustrate the data flow, it is represented below in picture 7.1. The Socket2Serial component talks with the Z-Wave controller through a serial port connection. Since data can be received or sent at any time it is necessary to handle that data whenever necessary. For that reason, when designing a program, several I/O techniques can be applied such as asynchronous I/O data receiving, blocking or non-blocking program flow according to the desired purpose.

Figure 7.1: Flow of data through Socket2Serial

71 7.1 Unix Signals

Handling asynchronous events such as incoming data from devices or processes can be done using a Unix resource named Unix Signals. The operating system responds to several different signals in different ways and for a range of different events. Signals come from Kernel space and can be initiated by processes or the Kernel itself. For this specific purpose the Socket2Serial should be notified that data has arrived either on the serial port or on the specific socket connection active at the time. Furthermore, to allow the user to have some control upon the software several other signals were registered. The list of signals registered for this software were: - SIGIO;

- SIGTERM;

- SIGINT;

- SIGHUP. The SIGIO/SIGPOLL is a signal sent to a process when an asynchronous Input/Output event occurs. This might be the data coming through the serial port or the network socket. SIGTERM is useful to allow a process to be killed by the user or other process, this signal can be blocked, handled and ignored. It is considered a polite way to terminate processes. During the development process it was useful to kill the process abruptly by using the ”Ctrl-C” key combination for that reason the SIGINT signal was registered. Finally, the SIGHUP signal was also registered since it allows to detect that a terminal connection, typically an RS-232 terminal, was lost or hangup. To configure the way the iHotel should behave when receiving data and/or signals each signal must be configured in a specific structure, the sigaction struc- ture (defined in the C header file sys/signal.h), the sigaction structure. In listing 7.1 it can be seen how this is done by the configuration routine which is invoked when the program starts.

Listing 7.1: Configuration of the signals for Socket2Serial

void configure SIGNAL(struct sigaction saio) { /∗ install the signal handler before making the device asynchronous ∗/ s a i o . s a handler = signal h a n d l e r ;

/∗ initialize the struct member ∗/ sigemptyset(&saio .sa mask ) ; s a i o . s a f l a g s = 0 ; s a i o . s a restorer = NULL;

/∗ when signal driven I/O is enabled for a socket ∗/ sigaction(SIGIO, &saio , NULL); /∗ CTRL−C ∗/ signal(SIGINT, signal h a n d l e r ) ; /∗ PROCESS TERMINATED ∗/ signal (SIGTERM, signal h a n d l e r ) ; /∗ DISCONNECTED TERMINAL ∗/ signal(SIGHUP, signal h a n d l e r ) ;

p r i n t f (”\ n∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗\n ” ) ; printf (”SIGNALS configured ! \ n ” ) ; }

72 The sigaction() function allows the process to examine or change the action to be taken when, in this case, a SIGIO signal is issued. The second parameter, saio, points to a structure that describes the action to be taken on receipt of the signal, in this case, a function acknowledging that a signal has been received and that terminates the application correctly. The function configure signal() also shows the setup of the handler for each of the other signals that are able to interrupt the program, respectively SIGINT, SIGTERM and SIGHUP, by the signal() function.

7.2 Serial Port Input/Output

To perform terminal I/O functions, such as interfacing with a serial port, an application programming interface called termios was used. This UNIX API allows the programmer to interface not only with a serial port but with any kind of terminal. To develop a software program using this API, the program shall behave ac- cording to the following sequence of actions showed in picture 7.2:

Figure 7.2: Socket2Serial Diagram of Operation

73 For this particular application there is a set of pre-requisites that have to be followed by the program: - Receive a line of characters or a set of characters.

- Write and read data.

- Not block if the device is unable to be opened.

7.2.1 Opening a Serial Device To open a serial device respecting the requirements specified above, one has to select options, such as: the path to the device, a set of flags that control the opening method, access permissions, etc. The path to the device (/dev/ttyUSB0) is mandatory, and it is stored in MODEMDEVICE. The control flags used are: - O RDWR opens the port for reading and writing;

- O NOCTTY to prevent the terminal device from controlling the application (and, for example, kill it if a CTRL+C is received;

- O NONBLOCK to prevent the opening process from blocking. The process of opening the serial device is done as it can be observed in listing 7.2. The function open UART() will return a value that indicates if the opening process was successful or not.

Listing 7.2: Open UART function

i n t open UART() { /∗ open the device to be non−blocking (read will return immediately) ∗/ i n t c o n f i g = open (MODEMDEVICE, O RDWR | O NOCTTY | O NONBLOCK) ;

i f ( c o n f i g < 0) { p e r r o r (MODEMDEVICE) ; e x i t ( −1); } printf (”UART open! \ n ” ) ; return config; }

7.2.2 Configuring the Serial Device The configuration of the serial device is done using a data structure named struct termios shown in listing 7.3. This data structure is defined in the header file and contains five fields that have to be filled to configure the device accordingly to what is desired.

Listing 7.3: Struct termios

{ struct termios { t c f l a g t c i f l a g ; /∗ i n p u t modes ∗/ t c f l a g t c o f l a g ; /∗ output modes ∗/ t c f l a g t c c f l a g ; /∗ control modes ∗/ t c f l a g t c l f l a g ; /∗ l o c a l modes ∗/ c c t c c c [NCCS ] ; /∗ control chars ∗/ } ; }

74 One of the important decisions to make is how data is meant to be received. The possible modes of operation are: - Canonical mode to provide data line-by-line, useful to deal with real termi- nals. - Non-canonical mode to receive individual characters. - Raw mode to prevent the input from being received line-by-line and to disable the processing of special characters (e.g., delete). The configuration of the serial port will be the same as the one defined by the manufacturer for the Aeon Labs Z-Wave Stick, 115200bps, 8 data bits, no parity bits and 1 stop bit. Furthermore, the graphical user interface returns individual characters and it does not process special characters hence the Non-Canonical mode is used. Listing 7.4 displays the configure UART function that is responsible for configuring every option related to the serial port. Listing 7.4: Configure UART function

void configure UART ( i n t fd UART, struct termios oldtio , struct termios newtio) { /∗ save current port settings ∗/ tcgetattr(fd UART ,&oldtio );

/∗ speed, 8 data bits, ... ∗/ newtio . c c f l a g = BAUDRATE | CS8 | CLOCAL | CREAD;

/∗ NO PARITY BITS ∗/ newtio . c c f l a g &= ˜PARENB;

/∗ RAW i n p u t ∗/ newtio . c i f l a g = IGNPAR | INLCR ;

/∗ Raw output ∗/ newtio . c o f l a g = 0 ;

/∗ disable canonical input ∗/ newtio . c l f l a g = (˜ICANON) ;

/∗ number of bytes to receive before the signal is activated ∗/ newtio . c cc[VMIN] = 1;

// newtio . c c c [VTIME] = 0 ;

t c f l u s h ( fd UART , TCIFLUSH ) ;

/∗ APPLY SETTINGS ∗/ tcsetattr(fd UART , TCSANOW,& newtio ) ; printf(”UART configured ! \ n ” ) ; }

7.2.3 Writing to and Reading from the Serial Interface To read from and write to the device the system calls read() and write() are used, as shown in listing 7.5. Each of the used the file descriptor obtained by open(), specifies the buffer where the data is located or is to be stored and the size of that same buffer. Listing 7.5: Reading and Writing data to the Serial Device

/∗ \ t e x t i t {Read from the Serial Device } ∗/ ... char number 01 = read ( fd UART, Socket buffer , size S o c k e t b u f f e r ) ; ...

/∗ \ t e x t i t { Write to the Serial Device } ∗/ ... char number = write(fd UART, message, message s i z e ) ; ...

75 7.2.4 Close Serial Interface The final step taken when interacting with the serial port in closing it using the standard Unix close() system call. Besides closing the device, the UART is also flushed, i.e., every remaining data on the buffer is actually written. Listing 7.6 shows how this is done. Listing 7.6: Flush UART function v o i d flush UART ( i n t fd UART, struct termios oldtio) { t c f l u s h ( fd UART , TCSAFLUSH ) ; tcsetattr(fd UART , TCSANOW, &o l d t i o ) ; p r i n t f (”UART FLUSHED! \ n ” ) ; c l o s e ( fd UART); }

7.3 Network Sockets

The graphical user interface connects with the Socket2Serial server by means of socket connections. The data that is received from the serial port is rerouted through a socket connection to the GUI. That network socket allows the GUI to receive and send information to the Z-Wave controller. The basic behaviour of a socket server and respective client software is illus- trated in figure 7.3. This structure is replicated in the Socket2Serial software and the graphical user interface (GUI). The implementation of a network socket implies the use of the functions listed below.

- socket(), creates a socket connection.

- bind(), associates the socket to the specific port present in the socket address structure.

- listen(), puts the socket in listening mode.

- connect(), requests a connection to an existing socket.

- accept(), accepts an received incoming connection.

- send(), recv(), write() or read(), sends and/or receive data.

- close(), terminates the connection.

7.3.1 Establishing a Socket Connection - Server Side 7.3.1.1 Creating a Server First the server creates a socket connection, it fills all the fields in the sockaddr in structure with the necessary data to specify either a local or remote endpoint to which to connect a socket as: the address family, the IP port and the IP address.

76 Structure sockaddr in is a data structure containing an internet address that is used to specify either a local or remote endpoint where to connect a given socket. This structure has the definition given in listing 7.7:

Figure 7.3: Server and Client Socket Flow Diagram

Listing 7.7: sockaddr in Data Structure

struct sockaddr i n { s h o r t s i n f a m i l y ; /∗ must be AF INET ∗/ u s h o r t s i n p o r t ; s t r u c t i n a d d r s i n a d d r ; char s i n z e r o [ 8 ] ; } ;

7.3.1.2 Configuring a Socket The socket configuration is done by the function configure SOCKET() in listing 7.8. The setsockopt() function is used to set the options associated with a socket,

77 in this case, the options are the following:

- SOL SOCKET is the specified protocol level for which the options are being set. Other levels, such as TCP, can be used by indicating the respective protocol number, which can be found using the getprotobyname() function.

-SO REUSEADDR defines whether local addresses are able to be reused. This is useful during the development process to avoid ”Address already in use.” messages when the server restarts after a crash. Typically, when an abnormal termination of the server or client happens, the connection enters in a state called TIME WAIT which is the state that ties up the port for several minutes after the process has completed. To avoid this, the SO REUSEADDR options is used to explicitly allow a process to bind to a port which remains in the TIME WAIT state.

Listing 7.8: Configure Socket function

int configure SOCKET ( i n t fd SOCKET) { ... e r r o r f l a g = s e t s o c k o p t (fd SOCKET , SOL SOCKET, SO REUSEADDR, ( char ∗)& f l a g , sizeof(flag ));

...

e r r o r f l a g = i o c t l (fd SOCKET , FIONBIO , ( char ∗)& f l a g ) ;

... } The other important option to set is FIONBIO. The ioctl system call is used to control the operating characteristics of a socket and therefore to set this option on. Turning it on allows the socket not to block whether it is for input or output data. By default, TCP sockets are blocking, that is, when a connect() call is made it blocks until a response is issued or an error occurs. This would be impractical since the desired behaviour of the program is that it never hangs at any connection. It simply puts one connection on hold, attends a new one, and later returns to complete the first. For this reason, a non-blocking socket is used. Even if the connection would return no data, the socket would not block.

7.3.1.3 Bind Socket The bind process associates the socket identified by the socket descriptor pre- viously obtained by socket() with a local address. Before that, the sockaddr in structure previously declared has to be filled with all the details regarding the socket connection. Listing 7.9 shows the complete process.

Listing 7.9: Bind Socket function

v o i d bind SOCKET ( i n t fd SOCKET , i n t s e r v e r port , struct sockaddr i n addr ) { ...

addr . s i n f a m i l y = AF INET ; addr . s i n a d d r . s addr = htonl(INADDR ANY ) ; addr . s i n port =htons(server p o r t ) ; e r r o r f l a g = bind (fd SOCKET , ( s t r u c t sockaddr ∗)&addr, sizeof(addr));

78 ...

printf(”Socket binded! \ n ” ) ; }

7.3.1.4 Accept Connection Whenever an application is listening for connections and is notified of a new one, in this case by using the select() function, it starts the connection by calling the accept() method, hence a new socket is created for each connection. The accept() method returns the new socket descriptor for the accepted connection.

7.3.1.5 Sending and Receiving Data While receiving data is done asynchronously using the select() mechanism, sending data can be done at any time during the program’s flow of execution simply be- cause the send() function can be invoked at any time. the function send MESSAGE(), in listing 7.10, is responsible for sending data through a network socket. Basically it uses the send() system call for that purpose.

Listing 7.10: Send Message function

i n t send MESSAGE(unsigned char message[] , int size , int close conn , int socket number ) { ...

e r r o r flag = send(socket number, message, size , 0);

... }

7.3.1.6 Closing a Socket Connection Finally, to close a socket connection, which its file descriptor is registered in the select() structure, detailed in section 7.5, all that is necessary to do is, making sure it is in fact registered and after that just invoke the close() system call on it. Listing 7.13 shows how this takes place.

Listing 7.11: Closing Socket Connection function

void cleanup SOCKET(int max sd , f d s e t m a s t e r s e t ) { int iterator 0 0 1 = 0 ;

for (iterator 001 = 0; iterator 0 0 1 <= max sd; ++iterator 0 0 1 ) { i f ( FD ISSET( iterator 001 , &master s e t ) ) close(iterator 0 0 1 ) ; } }

7.3.2 Establishing a Socket Connection - Client Side On the client side, GUI, a socket connection is established with the Socket2Serial system component as shown previously in 6.2. The GUI, developed in Qt, makes use of the QtNetwork module which makes use of QTcpSocket class to establish TCP reliable connections to transfer streams of data.

79 The client application is always running in the foreground and with the server also running in the background a connection between both is maintained. The connection is never closed as a result of the client. In fact, the client is never closed. The objective of the system is to be on all the time, so the possibility of shutting down the whole system was not part of the design, the system would simply restart as soon as it was turned on. On a formal point of view, this possibility should be considered but since it was not absolutely necessary, the option was made to leave it out.

7.4 Data Exchange

Functions read Buffer() in listing 7.12 and process socket() in listing 7.13 receive and process respectively incoming data from the serial port and the network socket.

Listing 7.12: Read Buffer function v o i d read BUFFER(unsigned char Socket buffer[], int size S o c k e t buffer , int socket number , i n t fd UART) { ...

char number 01 = read ( fd UART, Socket buffer , size S o c k e t b u f f e r ) ;

...

i f ( c l i e n t connected == 1) { char number 02 = send(socket number , Socket b u f f e r , s i z e S o c k e t b u f f e r , 0 ) ; } e l s e p r i n t f (”NO CLIENT CONNECTED! \ n ” ) ;

... }

Listing 7.13: Process Socket function void process socket(int fd UART, int close conn , int socket number, unsigned char buffer[] , i n t s i z e b u f f e r ) { ...

chars received SOCKET = recv(socket number, buffer , size b u f f e r , 0 ) ;

...

chars written UART = write(fd UART, buffer , chars received SOCKET);

... }

7.5 Select() Application Programming Interface

The select() API is used to monitor the input or output of data through a set of file descriptors. This allows multiplexing of several I/O channels or file descrip- tors. This API can be configured to monitor the following events: read, write and exception. The select() function is sleeping and awakes when one of those events takes place in one or several of the file descriptors monitored, if previously configured for that purpose. The file descriptor sets are specified as fd set ob- jects. When a file descriptor is activated, a bit is set on the file descriptor set.

80 This is actually a bit array. To manipulate a file descriptor set, four functions are available:

- FD CLR() clears the bit for the file descriptor fd in the file descriptor set, fd set.

- FD ISSET() returns a non-zero value if the bit for the file descriptor fd is set in the file descriptor set pointed to by fd set, and 0 otherwise.

- FD SET() sets the bit for the file descriptor fd in the file descriptor set, fd set.

- FD ZERO() initializes the file descriptor set fd set to have zero bits for all file descriptors.

7.5.1 Communication Management In Socket2Serial, the function FD ISSET is used to monitor any change in both serial port and network socket file descriptors. Once one of these file descriptors changes the data is received and immediately sent through the other one. That is, if received trough the serial port, is sent through the socket connection or if received from a socket connection is sent through the serial port. This behaviour can be observed in listing 7.14 by respectively calling functions read Buffer() and process Socket() described in section 7.4.

Listing 7.14: Wait Connections function

... do { ...

i f ( FD ISSET ( fd UART, working s e t ) ) { read BUFFER( Socket buffer , size S o c k e t buffer , socket number , fd UART); print BUFFER( Socket b u f f e r ) ; } i f ( FD ISSET (fd SOCKET , w o r k i n g s e t ) ) { socket number = a c c e p t (fd SOCKET , NULL, NULL ) ;

...

p r o c e s s s o c k e t ( fd UART , c l o s e conn , socket number, buffer , size b u f f e r ) ; }

} w h i l e ( 1 ) ; ...

7.5.2 Registering the Socket File Descriptor The function initialize FDSET() in listing 7.15 is used to manipulate an fd set structure to register each one of the file descriptors (FD) to be used. Along with the serial port FD fd SOCKET, the fd set structure was also used to register the socket FD fd UART. Registering implies setting a bit to 1 in the declared structure. That is accomplished with the FD SET() function.

Listing 7.15: Initialize FDSET Socket function

int initialize FDSET(int fd UART , i n t fd SOCKET , f d s e t m a s t e r s e t ) {

81 ...

FD ZERO(& m a s t e r s e t ) ; max sd = fd SOCKET + fd UART + 1 ; /∗ Number of descriptors ∗/ FD SET(fd SOCKET , &m a s t e r s e t ) ; /∗ set testing for sockets ∗/ FD SET( fd UART, &master s e t ) ; /∗ set testing for serial port ∗/

... }

7.6 Running the Application

The Socket2Serial component is started by the following command: $ socket2serial [-p netport] device To start the software a few things have to be specified. In which port the service is meant to be running, that is parameter netport. The device to use is specified in the device parameter. This is where the Aeon Labs USB Z-Stick is connected, for example: /dev/ttyUSB0. Once Socket2Serial is running, it is possible for any other program or web service to use the a socket connection to send and receive commands to the Z- Wave network. This enables a whole new range of possibilities, like a server being able to remotely control a Z-Wave network.

82 Chapter 8

Conclusion

8.1 Future Work

Besides all that has been done to unravel the Z-Wave protocol and build a concept around it, much could be added and/or improved in the iHotel. Either software or hardware modifications would be able to improve the iHotel in several ways.

8.1.1 Processing Power Although no quantitative study has been conducted regarding the platform’s per- formance in terms of video playback (which at the time is not available), load speed of the application, boot time, speed of change between menus and several other, some delays and lags are noticeable to the user. These lags or delays that may influence user interaction with the system can easily be overcome by using a more powerful platform, with a faster and more capable processor, more RAM memory or even a dedicated graphics processor.

8.1.2 Complete Z-Wave Application Programming Inter- face The Z-Wave protocol details discovered throughout this project are far from being complete. A complete application programming interface to the Z-Wave protocol would enable the iHotel system to interact with every Z-Wave compatible device independently of its vendor. This would take a large amount of time and money to try many other devices, or only a lot of money to buy the protocol license.

8.1.3 Larger Display Depending on the specific final use of the system, a different LCD size or touch screen technology could be used. Modifications to the Linux kernel are needed in order to use a bigger or smaller display. Considerations regarding the processor power have to be made if a higher resolution and color depth display is to be used since considerably more processing power is required to drive such LCD.

83 8.1.4 iHotel Web Control A powerful advantage to any home control system is to be able to control it remotely. Either by the hotel room client or by the hotel staff, remote control over the system enables a great deal of comfort and liberty as well as resource management for increased functionalities and costs reduction.

8.2 Conclusions

The iHotel concept demonstrates how a home automation protocol that is not open can be studied thoroughly and used to support an idea. As a conclusion, it can be said that the protocol had its basic features explored. Reading the status of switches, actuating upon them, read sensor values and gather basic network information were the basic topics explored during this work. Although some features were revealed, many other remain to be explored and tested. The graphical interface developed is basic and relies mostly on hard-coded Z-Wave frames to operate. This allowed flexibility and less time consumed with details that added no relevant information regarding the protocol, which is the object of study depicted here. Taking into consideration the information obtained during the investigation process of this work, it can be said that the protocol is much more extensive than this work can possibly demonstrate. One of the limitation for this work was precisely the limited access to Z-Wave devices. Having access to different types of devices, from different brands and launched into the market at different times would allow for more information to analyse and a better comparison term that surely would enable more results. The objectives of this work were achieved since basic control of a Z-Wave network and its devices was obtained.

84 Bibliography

[1] Cristensen, Carlos Mlia; Patent Number: 6,980,080; RF Home Automation system With Replicable Controllers, 27 of December of 2005.3, 28, 32, 34, 35

[2] Franck, Jargen; INS10244 - Instruction: Z-Wave Node Type Overview and Network Installation Guide 23

[3] Johansen, Niels Tybo; Patent Number: 7,680,041; Application Number: 11/684,430; Node Repair in a Mesh Network, 16 of March of 2010. 24, 26, 28

[4] T. Galeev, Mikhail; Catch the Z-Wave, October of 2006. 25, 26, 27

[5] Johansen, Niels Tybo; SDS10243 - Software Design Specification: Z-Wave Protocol Overview 26

[6] Johansen, Niels Tybo; ZM3102 Z-Wave Module Datasheet 28

[7] Qees ApS; Qees Power - Model 0300002 Datasheet 31

[8] Jorgensen, Thomas; T. Johansen, Niels; Z-Wave as Home Control RF Platform 33

[9] Shorty, Peter; Patent Number: 6,879,806; Application Number: 09/870,497; System and a Method for Building Routing Tables and for Routing Signals in an Automation System, 12 of April of 2005. 33, 35

[10] Website: http: // en. wikipedia. org/ wiki/ List_ of_ checksum_ algorithms , List of Checksum Algorithms 35

[11] Website: http: // wiki. micasaverde. com/ index. php/ ZWave_ Dongle 37

[12] Datasheet: http: // downloads. ezhome. nl/ en/ EVR/ EVR_ AN1582_ in_ en. pdf , AN158 Wall Switch 42, 43, 44

[13] Website: http: // wiki. micasaverde. com/ index. php/ ZWave_ Command_ Classes 42, 50, 55

[14] Datasheet: http: // us. bosscom. com/ files/ pdf/ BossDim-RS. pdf , BossDimm RS - Technical Document 44

85 [15] Openzwave Project Website: code. google. com/ p/ open-zwave/ 44

[16] HomeSeer Website: http: // www. homeseer. com/ wiki/ index. php/ HomeSeer_ HSM100 50

[17] Datasheet: ACT ZDM230 Z-Wave Controlled Dimmer Receiver, Dual Switch. Act Solutions, 2007. 53

[18] Website: http: // www. pepper1. net/ zwavedb/ device/ 4 53, 54, 56

[19] Website: http: // www. smarthus. info/ support/ download/ zwave/ Z-WaveConfigurationInformation. pdf 54, 55

86