\documentclass[12pt,twoside]{article}
\usepackage[utf8]{inputenc} % apparemment utf8x est mieux qu’utf8 mais c'est incompatible avec biblatex...
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{textcomp}
% \usepackage[style=numeric,backend=biber]{biblatex}
\usepackage{csquotes}
\usepackage[english]{babel}
\usepackage[pdftex]{hyperref}
\usepackage{verbatim}
\usepackage{alltt}
\usepackage{hhline}
\usepackage{lmodern}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage[a4paper,margin=2cm]{geometry}
% \usepackage[letterpaper,margin=2cm]{geometry}
% \usepackage[hmarginratio=1:1]{geometry}
\usepackage{listings}
\usepackage{float}
\usepackage{url}
\usepackage{tabularx}
\usepackage{calc}
\usepackage{color}
\usepackage{wasysym}
\usepackage{enumitem}

% \bibliography{labo}


\begin{document}

\title{A brief introduction to xAAL v0.7-draft}

\author{Christophe Lohr \and Jérôme Kerdreux}

\maketitle

\begin{abstract}
This document summary information which specifies xAAL such as defined by
the IHSEV/HAAL team of IMT-Atlantique.

% This release proposes to use CBOR in place of JSON for
% xAAL messages, and CDDL in schemas in place of Json Schema.
\end{abstract}


\section{Introduction}
The xAAL system is a solution for home automation interoperability.
Simply speaking, it allows a device from vendor A (e.g. a switch) to talk
to a device from vendor B (e.g. a lamp).

The xAAL specification defines: (i) a functional distributed architecture;
(ii) a means to describe and to discover the interface and the expected
behavior of participating nodes by the means of so-called schemas; and (iii)
a secure communications layer via an IP (multicast) bus.

These points are detailed in the specification document of xAAL version
0.5-r2.\footnote{\url{http://recherche.imt-atlantique.eu/xaal/documentation/}},
which is considered as the latest stable release.  xAAL version 0.6 is a
first attempt to introduce CBOR, but with some points to improve.  xAAL
version 0.7 aims to address them.


\begin{itemize} 
\item xAAL architecture remain almost the same as in version 0.5-r2
  except that Schema Repositories are withdrawn.

\item xAAL schemas are still written in JSON, except that now data
  types are specified with the Concise Data Definition Language (CDDL,
  RFC 8610)\footnote{\url{https://tools.ietf.org/html/rfc8610}} and no more
  with the JSON Schema\footnote{\url{http://json-schema.org/}} dialect. 
  Moreover, data type definitions are gathered in a \emph{data model}
  section of xAAL schema documents.

\item xAAL version 0.7 proposes to use the Concise Binary Object
  Representation (CBOR,
  RFC 7049)\footnote{\url{https://tools.ietf.org/html/rfc7049}} in place of
  JavaScript Object Notation (JSON,
  RFC 7159)\footnote{\url{https://tools.ietf.org/html/rfc7159}} for messages.

\end{itemize}


\paragraph{The philosophy.}
xAAL is a distributed system based on ``the best effort'' principle.  Each one does its
best according to its capacity for things to go well.  There is no
warranty.  There is no quality requirement to expect/provide from/to
others.  

\paragraph{} Following papers discuss main points of xAAL:
\begin{enumerate}
\item C. Lohr, P. Tanguy, J. Kerdreux, ``xAAL: A Distributed Infrastructure for Heterogeneous Ambient Devices'', Journal of Intelligent Systems. Volume 24, Issue 3, Pages 321–331, ISSN (Online) 2191-026X, ISSN (Print) 0334-1860, DOI: 10.1515/jisys-2014-0144, March 2015.
\item C. Lohr, P. Tanguy, J. Kerdreux, ``Choosing security elements for the xAAL home automation system'', IEEE Proceedings of ATC 2016, pp.534 - 541, Jul 2016, Toulouse, France.
\end{enumerate}


%                                      *
%                                     * *

\section{The xAAL Architecture}
A home automation facility is usually made of physical devices (sensors,
actuators).  The basic way for users to interact with a home automation
facility is by pressing buttons or switches, that is to say activating
dedicated physical sensor devices.  Modern home automation solutions provide
user interfaces such as mobile applications for smartphones tablets PC or
voice interfaces.  It is also common to provide some functionalities for
scripting sequences of actions to be triggered automatically at a given time
or to react to some expected event.  There may also be some logging
functionalities for monitoring parameters along the time, such as
temperature in rooms, consumption of energy or water, so that users may
reduce their consumption.

The xAAL system aims to address the typical uses and needs towards home
automation systems.

\paragraph{Objectives:}
\begin{itemize}
\item The system should be robust: the failure of a component should not
  prevent others from doing their job.

\item The system should be lightweight, even in terms of communication.  It
  should use existing communication networks available at home, without
  consuming too much bandwidth.

\item The system should be flexible: adding or removing a component should
  not require long or complex configuration processes to make it work nor
  disturb the other components.

\item The system should address security considerations, regarding users'
  privacy, or third party's threat to get control.

\item Last, but not least, the system should handle interoperability issues,
  allowing a device from vendor A (e.g.  a switch) to talk to a device from
  vendor B (e.g.  a lamp), allowing consumers to buy devices they need
  without being enclosed into the market or the technology of the vendor of
  devices they already have bought.
\end{itemize}


\subsection{Overview of the xAAL Architecture} 
The xAAL system is made of functional entities communicating to each other
via a messages bus over IP.  Each entity may have multiple instances or
zero, may be shared between several boxes, and may be physically located on
any box.

Figure \ref{archi} shows the general functional architecture of the xAAL
system in a typical home automation facility.

\begin{figure}
\centering
\includegraphics[width=0.8\linewidth]{bus-xaal}
\caption{Functional Architecture of xAAL.\label{archi}}
\end{figure}


\paragraph{Native Equipment.}
  Some home automation devices (sensors, actuators) can communicate natively
  using the xAAL protocol.

\paragraph{Gateways.}
  In general, devices for home automation only support their own proprietary
  communication protocol. 
  Therefore, elementary \emph{gateways} have the responsibility to translate
  messages between the manufacturer protocols and the xAAL protocol.

  Within an installation, each manufacturer protocol may be served by a
  dedicated gateway.

  According to the technologies and the manufacturer protocols, each gateway
  will handle the following issues: pairing between the gateway and physical
  devices, addresses of devices, configuration, and the persistence of the
  configuration.

  Gateways can be queried about the list of devices they manage.

\paragraph{Database of Metadatas.}
  Each automation device within a facility is likely to be associated with a
  piece of user-defined information: for instance some location information
  (e.g.  declare that the equipment typed as a lamp and having address X is
  located in the ``kitchen'' or in the ``bedroom of Bob''), possibly a
  friendly name to be displayed to the end user (e.g.  device having address
  X is called ``lamp\#1''), or any useful piece of information for users
  regarding devices on its facility (e.g.  pronunciation of the nickname of
  the device for a voice interface, or whatever).

  All this information is grouped in a \emph{database of metadata}.
  This database contains somehow the configuration of home automation
  devices, from the end-user point of view.

  The database of metadata is present on the xAAL bus.  Other xAAL devices
  can query it via this bus to obtain information associated with the
  identifier of a device, or conversely a list of devices associated with a
  given piece of information.

  There should be at least one database of metadata on the bus.  There could
  be several.
  
  Such pieces of information are structured as key-value pairs.  Keys and
  values are UTF8 strings.  The xAAL specification does not define a
  normative list of pre-defined or well-known key entries.  As a
  consequence, the meaning of a key makes sense only for the entity that
  write it in the database and for the entities which read it.  This is the
  responsibility of those entities to agree on a common semantics to
  interpret information.

\paragraph{Cache.}
  Unidirectional sensors are quite common: one cannot question them, they
  send their information sporadically.  (e.g.  A thermometer which sends the
  temperature only if it changes.)

  So, there should be at least one cache on the xAAL bus that stores this
  information so that other entities can query it whenever necessary.  Note
  that even if such caching feature is implemented by the gateway software
  itself, the cache is seen as a dedicated xAAL device.

  Such a cache should store at least the values of attributes carried by
  notifications sent by the devices.  It can also stay informed by
  monitoring request/reply messages between devices about values of
  attributes.

  As with any caching mechanism, it is necessary to associate a timestamp to
  cached information.  When another entity on the xAAL bus asks the cache
  for information, it also gets the age of the cached information, and
  decides itself if it is good enough or not.  This is not the
  responsibility of the cache to manage the relevance of data according to
  their age.  This is the responsibility of the client that makes the
  request.  Moreover, the clock used by caches to set such timestamps may
  not be accurate or synchronized well.  This is the responsibility of
  clients to deal with that.

  Again, inconsistencies may arise if two caches return information that has
  the same timestamp but divergent values.  This phenomenon is a priori very
  rare.  However, the xAAL specification does not enforce any rule to solve
  inconsistencies.

\paragraph{Automata of Scenarios.} 
  Scenarios are advanced home automation services like, for example start a
  whole sequence of actions from a click of the user, or at scheduled times,
  or monitor sequences of events and then react, etc.

  To do this, xAAL proposes to support it by one or more entities of the
  type \emph{automata of scenarios}.

  These automata of scenarios are also the right place to implement virtual
  devices. For example, consider a scenario to check for the presence of
  users in a room: it could aggregate and correlate a variety of
  events from real devices, and then synthesizes information such as
  ``presence'' and notify it on the bus, in order to be used by other
  entities.  By proceeding in this way, this scenario should appear by
  itself as a device on the bus, with its address and its schema.  This
  scenario is a kind of virtual device.

\paragraph{User Interfaces.}
  One or many  user interfaces are provided by specific entities connected
  to the xAAL bus.  This can be a real hardware device with a screen and
  buttons; or a microphone which performs voice recognition; or a software
  component that generates Web pages (for instance) to be used by a browser
  on a PC, a connected TV, or whatever; or software that provides a REST API
  for mobile applications (tablets, smartphones), to an external server on
  the cloud for advanced services, to an MQTT server, or to offer features
  for services composition, etc.

  Within a home automation system, there may be one or many user interfaces.


\subsection{Typical Work Flow}
Such a functional architecture allows managing the dynamic aspects of the
infrastructure (modularity, scalability, adaptation, etc.).  Thus, advanced
functions such as HMI or automata of scenarios can adapt themselves
automatically to the infrastructure and to its modifications (if equipment
enters / leave, if one fails or is replaced, etc.).

The typical work flow of an HMI could be
\begin{enumerate}
\item Query the xAAL bus to be aware of the present devices;
\item Query devices about their description (model, manufacturer, URL,
  etc.);
\item Optionally, download non-standard schemas from the URL of the
  description of those non-standard devices, or else use standard schemas;
\item Query the database of metadata about devices to get the configuration
  of the installation (a friendly name to display, location and other
  key values associated with each device);
\item Query the cache for the latest known states of devices;
\item Dynamically build display screens and control interfaces for these
  devices.
\end{enumerate}


\subsection{Change in the xAAL Architecture}
Compares to former versions, xAAL 0.7 has no more \emph{Schemas Repository}. 
This xAAL device was used to provide xAAL schemas via the xAAL bus. 
Schemas are still there with xAAL 0.7 but are distributed by other means. 
Experiments on the long term have convinced us that there is not a real use
of such a functionality (having schemas via the home automation bus itself
instead of downloading from the Web).

Indeed, xAAL schemas are not of such a dynamic nature.  They are downloaded
and configured once.  Standards schemas can be preconfigured, and
non-standard schemas can be downloaded from the URL provided by non-standard
devices in their description.

The last reason for this change is that, finally, schema files are not so
used as-it by xAAL devices.  Schemas are really important for developers to
know formally what a device does.  This is important for developers of the
device described in the schema, and also for developers of other devices
which interact with it.  Schemas may also be used to generate code
skeletons.  As a consequence, the knowledge provided by schemas takes the
form of software code within devices.  One of the few cases where schema
files are used as-is, this is by the generic user interface which is able to
dynamically and automatically build interfaces on the basis of the xAAL
schema files.  To be honest, even if this generic user interface is
completely functional, it is not so elegant neither ergonomic.  It is
probably not likely be used in real facilities, only for developers.  To do
the job, this generic user interface is able to download schemas files from
the Web, it does not really need to get it from the xAAL bus.

Those discussions have led us to simplify the xAAL architecture and to
withdraw the Schema Repository.


\subsection{Communication Channel} 
The xAAL architecture is based on the many-to-many communication principles,
concretely a communication bus.  Any component can post messages (e.g. 
sensor data) to another, several, or all components without preliminary
connection setup.  This has many advantages over usual client-server
communication principle.  Point-to-point communications are avoided, which
saves device memory resources.  Indeed, a home automation component is
usually linked to many others for things to work.  Maintaining many
permanent connections in parallel may be extremely heavy for constrained
devices.  A bus also brings some functional benefits.  This allows the
discovery: when a new component appears in the installation, it announces
itself.  All other entities can then take it into account.  Similarly, when
a new component enters, it can query the bus to discover the other
components already present.  This greatly facilitates the configuration,
allows dynamicity as well as the evolution capacities of the system.

For these reasons, the xAAL system has been designed on an IP
\emph{multicast bus} (IPv4 or IPv6).


\subsubsection{WiFi and Multicast}
WiFi weaknesses are out of the scope of the home automation study.  However,
this may have an impact on the xAAL architecture.  This is why a discussion
is welcome.

WiFi (IEEE 802.11) is a common use wireless technology for IP networks, also
at home.  It is widely used to provide Internet access to mobile devices
(smartphones, tablets, laptops, etc.).  It is also used for non-mobile
devices (connected TV, video game consoles, IP CCTV cameras, etc.) when
users are refractory to the installation of Ethernet cables.

Unfortunately, IEEE 802.11 protocols do suffer from design choices regarding
the management of broadcast and multicast packets.  Simply speaking, it has
been chosen not to acknowledge broadcast and multicast packets at the radio
level, contrary to unicast packets.  Indeed, avoiding managing a list of
nodes having not acknowledged packets greatly simplify the protocol
implementation.  Broadcast and multicast packets are sent only once, and at
a lower rate to get a better chance to be received without error.

This point has been studied by research in wireless networks since the very
first years of WiFi.  Several proposals have been made, by modifying the
radio MAC layer, by introducing a central coordinator, by replacing
multicast by unicast either at the MAC layer or at the application layer,
etc. 
\footnote{\url{https://drakkar.imag.fr/IMG/pdf/perfAnomaly-infocom.pdf}}
\footnote{\url{https://pdfs.semanticscholar.org/b348/624662cedc637b50eea6e28206d7e16dc71a.pdf}}
\footnote{\url{https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/dircast.pdf}}
\footnote{\url{https://hal.inria.fr/inria-00084130v2/document}}
\footnote{\url{https://link.springer.com/article/10.1023\%2FA\%3A1016631911947}}%

Over the years, the WiFi Alliance has enhanced WiFi protocols, but with the
objective to increase bandwidth, and for unicast.  One may notice that the
IEEE 802.11e standard proposes the Wireless Multimedia Extensions (WME).  It
provides basic Quality of service (QoS) features on which the first two
classes of service among the four ones are dedicated to voice and video
content.  Classification is often performed on the basis of the TOS field of
the IP header.  WME is sometimes presented as a solution for
multicast-over-WiFi issues, despite the mechanisms act at different layers
and has concretely no impact.  The confusion comes from the idea that
multicast is dedicated to multimedia (e.g.  TV diffusion over IP, which is
actually one of the multicast uses cases among others), and enhancing
multimedia do enhance multicast.  This is not the case.

For twenty years, the Mboned IETF working group aims to facilitate
deployment of multicast technologies for the Internet at large.  This
working group also consider the issues of deploying multicast on WiFi
networks.\footnote{\url{https://tools.ietf.org/id/draft-ietf-mboned-ieee802-mcast-problems-09.html}}
Several nowadays mitigation solutions are listed.  None is perfect.  The
conclusion of this study is that ``IEEE 802.1, 802.11, and 802.15 should be
encouraged to revisit L2 multicast issues.''

Indeed, this situation contributes to the ``Ossification of the Internet'':
due to (technical and administrative) limitation of several infrastructure
equipment, innovations tend to restrict themselves to a small subset of
Internet services.  To get a chance to get clients, one only uses TCP and Web
communication technologies to implement innovations.  On the other hand,
equipment manufacturers take time to enhance their product to fully support
Internet principles with the argument there is a few consumer request.

Note that the situation is probably similar when diffusing multicast packets
over HomePlug-AV PowerLine Adapters.
\footnote{\url{http://www.plc.uma.es/articulos/Analysis_and_improvement_of_multicast_communications_in_HomePlug\%20AVbased_in_home_networks_2014.pdf}}%
\footnote{\url{http://repositorio.upct.es/bitstream/handle/10317/4179/pjpe.pdf}}%


\paragraph{Is this severe?} Well, this greatly depends on the quality of the
WiFi Access Point in use.  Let's consider a managed mode 802.11 network:
several WiFi Stations (STA) connected to a WiFi Access Point (AP).  If
multicast packets are transmitted from an STA to the AP, packets are well
received almost as good as unicast packets.  However, if packets are
transmitted from the AP to STAs, there are risks packets are lost, depending
on the quality of the AP and the global situation.  According to our
informal and humble tests in lab with a small set of different AP, nowadays
AP are not perfect but of a rather good quality.  Moreover, probably thanks
to the small size and their sporadic emission, xAAL messages are not really
affected.  However, there is no formal warranty at all.

\paragraph{Workaround: a multicast-unicast reflector.} If network equipment
of a home facility has severe issues regarding multicast, the xAAL
infrastructure can be slightly modified.  In such a situation, one may use a
\emph{Unicast-Multicast Reflector}.  This application forwards messages from
a multicast channel (e.g.  the xAAL bus) towards connected UDP unicast
clients, and vice versa.

This is the same approach as solutions developed in the middle of 90s for
the MBone project
\footnote{\url{https://www.researchgate.net/publication/2855653_Multicast-Unicast_Reflector}}
except that our reflector does not intent to manage RTP RTSP RTCP protocols. 
It works at the UDP layer.

To use it: first, put as many as possible xAAL devices on the wired side of
your AP.  On plain old Ethernet wires, multicast works well.  Put also the
reflector on the wired side.  All those components can communicate with each
other via the xAAL multicast bus, as usual.  Then, xAAL devices that have
to go on the wireless side of your AP should be configured to use the
unicast IP of the reflector instead of the multicast IP of the xAAL bus (the
xAAL network stacks accept a unicast peer).  This increase delays and
bandwidth consumption, but this works.

Note that such a reflector is not a xAAL component.  One recommends not to
use it, if possible.  As an alternative, select a better quality WiFi AP, or
use Ethernet.




%                                      *
%                                     * *

\section{The xAAL Devices Behavior and xAAL Schemas}\label{schemas}
xAAL devices are described by so-called schemas.  Schemas are documents
specifying attributes, notifications and methods API.

\bigskip 

Note that the idea of specifying home automation devices by schemas is
inspired by the UPnP
approach.\footnote{\url{http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf},
Chapter 2.}.  Thanks to that, UPnP entities could discover new entering
devices, ways to interact with them, and possibly dynamically build user
interfaces (well, for this latter point UPnP schemas usually pointed to some
Microsoft DLL installers or Internet Explorer plugins to be installed on the
user's PC, which is not very secure).

The other advantage of a formal specification of home automation devices is
for software production.  Having a clear API specification may help to
automatically build skeleton of code.  That was the case with the XDR
(External Data Representation) for Sun's RPC (Remote Procedure Call) since
the middle of 90s.  Now there is a renewal with OpenAPI and other RESTful
API description languages: during the first age of Web technologies,
communications were rarely clearly specified since developers were used to
manage both sides (the server code, plus the client in the shape of
JavaScript code).  Nowadays, with REST architecture principles, the web
client is not necessarily the end-user web browser but sometimes a
third-party application.  Within the Web community, this revives needs
towards clear API specifications.

The home automation community does have the same needs.


\paragraph{Objectives:}
\begin{itemize}

\item xAAL devices should be specified in a clear way for others to know how
  to interact with them, what to provide, what to expect.

\item Those specifications should describe devices in a generic and in an
  abstract way (e.g.  all thermometers should have the same behavior, even
  if a manufacturer adds blinking nice LEDs on it or whatever)

\item Those specifications should allow extensions to describe devices more
  sophisticated than the basic ones of the same family, without breaking the
  basic behavior one may expect for devices in this family, in a backward
  compatibility way.

\item Those specifications should follow a strict syntax to be parsed by
  software for automatic treatments.  (e.g.  Building skeleton of software,
  or automatic discovering of peers API).

\item The specification document should be readable by a human (well, with
  some software programming skills).
\end{itemize}


\subsection{Definition of a device}\label{def_device}
A \emph{device} has a \texttt{dev\_type} and an \texttt{address}.

\paragraph{dev\_type:} This references the \emph{schema} and defines the 
  type of the device.  It is hard-coded into the device.
  
  \begin{itemize}
  \item This schema identifier is a string consisting of a pair of words
    separated by a dot: \texttt{dev\_type:\emph{class}.\emph{variant}}
    \begin{itemize}[label=]
    \item The first word refers to a class of device type (e.g. lamp,
    switch, thermometer, power plug).
    \item The second word refers to a variant of a given class (e.g.  within
      the lighting class one may have an on-off lamp, a lamp with dimmer, an
      RGB lamp, etc.).  The second word may also refer to a schema extension
      by a manufacturer (cf.  \ref{heritage_schemas}).
    \end{itemize}

  \item The keyword \texttt{``any''} is reserved and acts as a wildcard
    for requests.  So that the identifier \texttt{``any.any''} is reserved and
    refers to all variants of all classes within request messages.  This is a
    \emph{virtual} type.  It is not allowed to defines a schema named
    \texttt{``any.any''}.  No one can claim to be of the type
    \texttt{``any.any''}.  Devices having no dedicated attribute, method or
    notification may use the \emph{concrete} type \texttt{``basic.basic''}.

  \item For example, the pair \texttt{``lamp.any''} means all variants of the
    class \texttt{``lamp''}.  This is also an abstract type.  
    Remember that the concrete type \texttt{``lamp.basic''} is provided to 
    describe basic features common to all lamps.

  \item We reserve a special name: \texttt{``experimental''}, for the
    class, as well as for variants.  This designates concrete types. 
    Associated schema, if written, should not be distributed outside the
    testing platform.  (e.g.  When someone makes a device but has not got a
    standard name for its type.)
  \end{itemize}

\paragraph{Address:} The device ID, unique on the bus.

  \begin{itemize}
  \item This device identifier is a UUID (RFC 4122), a 128-bit random number.
  \item Addresses are self-assigned. There is no naming service anywhere. A
    device does not request any entity to get an address.\\
    Concretely, addresses may be assigned:
    \begin{itemize}[label=]
    \item Either this is hard-coded in the factory.
    \item Auto-generated (random)  at the time of installation.  However, it
      is recommended that this address remain persistent. (i.e.  Please save
      it, if possible, during power breaks.)
    \item There is in principle very high probability of having no collision
      of UUIDs.  However, it is technically possible to verify that a UUID
      is not already used on the bus by a kind of ``Gratuitous ARP'', i.e. 
      by \texttt{is\_alive} requests to ensure that no one else already uses
      this address.
    \item But certainly not assigned by a bus supervisor/coordinator or
      something like that.
    \end{itemize}
  \end{itemize}


\subsection{Definition of a schema, the type of device}\label{ref_schema}
Each device is typed, i.e. described by a schema. 

A xAAL schema is a JSON object with a specific form that must validate given
CDDL rules (\emph{Concise Data Definition Language}, RFC 8610).  See
Appendix \ref{schema.cddl}.

The schema provides a bit of semantics for a device and describes its
capabilities: a list of attributes that describe the operation of the device
in real time (the device announces change of values on the bus), a list of
possible methods on this device (mechanism of request replies), a list of
notifications that it emits spontaneously.

\begin{itemize}
\item A list of \emph{attributes}.  If the value changes, this spontaneously
  generates a notification to the bus.

  Each attribute is defined by:
  \begin{itemize}[topsep=-1ex,parsep=0pt,partopsep=0pt,itemsep=0pt]
  \item A unique name which identifies it within the schema;
  \item A type name relating to the data model section.
  \end{itemize}

\item A list of \emph{methods}. Each method is described by:
  \begin{itemize}[topsep=-1ex,parsep=0pt,partopsep=0pt,itemsep=0pt]
  \item A unique name which identifies it within the schema;
  \item A textual description;
  \item A list of \texttt{``in''} arguments to be filled by peers when
    invoking this method;
  \item A list of \texttt{``out''} arguments returned by the device to
    peers;

    Each argument is defined by:
    \begin{itemize}[label=,topsep=-1ex,parsep=0pt,partopsep=0pt,itemsep=0pt]
    \item A unique name which identifies it within this method definition in
      the schema;
    \item A type name relating to the data model section.
    \end{itemize}

  \item A list of related attributes that may be affected by the method
      (e.g. to be refreshed in an HMI after the method call)
  \end{itemize}

\item A list of \emph{notifications}. Each notification is described by:
  \begin{itemize}[topsep=-1ex,parsep=0pt,partopsep=0pt,itemsep=0pt]
  \item A unique name which identifies it within the schema;
  \item A textual description;
  \item A list of \texttt{``out''} arguments included in the notification;
    Each argument is defined by:
    \begin{itemize}[label=,topsep=-1ex,parsep=0pt,partopsep=0pt,itemsep=0pt]
    \item A unique name which identifies it within this notification definition in the schema;
    \item A type name relating to the data model section.
    \end{itemize}
  \end{itemize}

\item A \emph{data model} section, that is to say a list of \emph{data types}
  definitions. For each type name:
  \begin{itemize}[topsep=-1ex,parsep=0pt,partopsep=0pt,itemsep=0pt]
  \item A textual description;
  \item The unit, if any.  This unit should be one of the IANA Sensor
    Measurement Lists (SenML)
    registry.\footnote{\url{https://www.iana.org/assignments/senml/senml.xhtml}}
    \footnote{Note that, contrary to SenML, within the xAAL context, the
    percent symbol \texttt{``\%''} is used for values between 0 and 100, and
    not for values between 0 and 1.} If none is relevant, use a unit of the
    International Bureau of Weights and Measures.  A standard unit allows
    automatic processing, data computation, or at least a consistent way for
    rendering by HMIs;
  \item A type definition in the form of CDDL rules, for extra processing
    (to dynamically build software skeleton, a generic HMI, etc.).
  \end{itemize}

\end{itemize}

\subsection{Inheritance of schemas} \label{heritage_schemas}
There is a notion of inheritance between schemas.  A schema can extend an
existing schema.  xAAL defines the first three levels of this genealogy:

\begin{enumerate} 

\item A basic generic schema, named \texttt{basic.basic}, common to all
  existing devices in the world, that everyone has to implement.  (See
  \ref{basic_schema}.)

\item A basic schema for every class (e.g.  \emph{lamp.basic},
  \emph{thermometer.basic}, \emph{switch.basic}, etc.).  Such basic schemas
  inherit from the generic schema, and extend it by defining basic
  functionalities shared by all device variants of the corresponding class. 
  (e.g.  lamps basically can do on/off)

\item Advanced schemas for more complex devices, by extending the
  basic schema of the corresponding class, and by defining
  new functionalities.  (e.g.  lamps basically do on/off, but some more
  sophisticated lamps are dimmable, others offer RGB control, etc.). All
  variants of a class must inherit the basic schema of the class. E.g.
  \texttt{lamp.dimmer} extends \texttt{lamp.basic} which extends
  \texttt{basic.basic}

\item Thereafter, manufacturers of home automation equipment will naturally
  define their own schemas among their products range.  However,
  manufacturers must not define their own schemas as level 1 schemas (the
  generic schema is the only one), nor as level 2 schemas (basic class
  schemas).  Schemas from manufacturers are necessarily extensions of
  schemas from level 2 or higher.

  While naming such schemas, manufacturers may use the second word (the
  variant name) of the pointed pair as their own discretion.  This is their
  responsibility to choose a name that may not conflict with existing ones. 
  However, the schema name should refer above all of the functionality of
  the device and means to interact with it; the name should also give an
  idea of the nature of the device.
\end{enumerate}


\paragraph{Definition of the extension process:} Let's consider a first
schema which is extended by a second schema.  The later express differences
with the former.  The extension process produces a new schema.  Extending a
schema has the following meaning:
\begin{itemize}
\item The latter schema may introduce new \emph{attributes}, \emph{methods},
  \emph{notifications}, and associated \emph{data types}.  The result of
  the \emph{extend} operator is a new schema that contains all
  \emph{attributes}, \emph{methods}, \emph{notifications}, \emph{data types}
  of former schema, plus the new ones introduced by the latter schema.

\item The latter schema may overload the definition of some existing objects,
  that is to say \emph{attributes}, \emph{methods}, \emph{notifications},
  and \emph{data types}.  An overloading means that such an object has the
  same name but a different definition.  There is no attempt to merge the
  old and the new object definition.  The resulting schema contains all new
  objects (\emph{attributes}, \emph{methods}, \emph{notifications},
  \emph{data types}) plus old ones that have not been overloaded.
\end{itemize}


\section{The Basic Schema}\label{basic_schema}
This is the basement of every schema.  This is normative.  All other schemas
must inherit from it somehow.  It is named \texttt{basic.basic}.

\paragraph{Attributes}
  \begin{itemize}
    \item \emph{Attributes involved in the protocol}
    \begin{itemize}[label=]
    \item \texttt{dev\_type}: string, the name of the schema to which the
      device obeys;
    \item \texttt{address}: byte string of 16 bytes, a UUID (the address of
      the device);
    \end{itemize}

  \item \emph{Attributes describing the device}
    \begin{itemize}[label=]
    \item \texttt{vendor\_id}: string, the name or identifier of the vendor;
    \item \texttt{product\_id}: string, an identifier of the product
      assigned by the vendor;
    \item \texttt{version}: string, version or revision of the product
      assigned by the vendor;
    \item \texttt{hw\_id}: any type, some hardware identifier of the device
      (e.g.  low-level addresses of the underlying protocol, a pairing code,
      a serial number, or any piece of information that may help to retrieve
      a device within a facility for maintenance);
    \item \texttt{group\_id}: bytestring[16], a UUID shared by all devices
     belonging to the same physical equipment (e.g.  each plug of a
     multi-plug outlet, each thermometer and hydrometer of a weather
     station, etc.);
    \item \texttt{url}: string, the URL of a website with extra 
      information
    \item \texttt{schema}: string, the URL to download the schema file in
      case if the device is of a non-standard \texttt{dev\_type};
    \item \texttt{info}: string, any additional information, if any, about this
      device that should make sense for the end user; (e.g.  on the
      thermometer of a weather station this may indicate that this is the
      \emph{indoor thermometer} or the \emph{outdoor thermometer}, or on a
      plug belonging to multi-plug outlets this may indicate the position of
      the plug.)
    \item \texttt{unsupported\_attributes}: array of strings (hopefully
      empty), with names of attributes of the schema that are actually not
      supported by the device for some (bad) reason.
    \item \texttt{unsupported\_methods}: array of strings (hopefully
      empty), with names of methods of the schema that are actually not
      supported by the device for some (bad) reason.
    \item \texttt{unsupported\_notifications}: array of strings (hopefully
      empty), with names of notifications of the schema that are actually
      not supported by the device for some (bad) reason.
    \end{itemize}
 \end{itemize}

  The attributes of the \texttt{basic.basic} schema are mostly considered as
  \emph{internal}, or dedicated to the description of the
  device, and are not likely to change along the life of the device.  Unlike
  attributes of extending schemas, they must not be involved in the
  \texttt{attributes\_change} notification nor in the \texttt{get\_attributes}
  method described below, but via the \texttt{get\_description} method.

\paragraph{Notifications}
  \begin{itemize}
  \item \texttt{alive}: emitted when starting the device and then
    periodically emitted at a rate left to the discretion of the device. 
    The notification message may contain a \texttt{timeout} parameter
    indicating to others when the next \texttt{alive} should arise.

  \item \texttt{attributes\_change}: emitted at every change of one of the
    attributes (except those belonging to \texttt{basic.basic}).  The body
    of the message contains only attributes which changed.

    A schema gives the list of all possible attributes that may appear
    within this notification message.  So, in a given message, some of those
    attributes may be present, some other may not be.  This is normal.

    However, the generic schema defines this method with no attributes,
    since the default attributes defined above are relating to the
    description of the device, and do not characterize the real-time
    operation of a specific feature.  Schemas extending \texttt{basic.basic}
    may overload the \texttt{attributes\_change} notification according to the
    extra attributes introduced by the extending schema.

  \item \texttt{error}: issued when the device detects a major error or a
    failure.\\
    The notification may contain a \texttt{description} (a textual
    description of the error), and a \texttt{code} (the numeric code of error).

    Remember that xAAL is of the best-effort philosophy.  Therefore, a wrong
    method invocation does not issue \texttt{error} notifications.  (The
    called device does its best with what it received, and possibly change its
    attributes accordingly, but there is no one-to-one dialogue to explain
    mistakes to the caller.) Errors are issued only on major failure of the
    device.

    This is intended to be overridden in the definitions of extending
    schemas.

  \end{itemize}

\noindent
Note: notification messages should be addressed to all.

\paragraph{Methods}
  \begin{itemize}
  \item \texttt{is\_alive}
    \begin{itemize}[label=]
    \item \texttt{dev\_types} (in): array of \emph{dev\_type} strings, 
      giving names of the schema of devices that should wake up.

    \item One may have:
      \begin{itemize}[label=]
      \item an empty array or \texttt{["any.any"]} to wake up everybody, or
      \item an abstract type, e.g.,\texttt{["lamp.any" ]} to wake up all
        lamps, or
      \item a specific type, e.g.  \texttt{["lamp.basic", "lamp.dimmer"]} to
        wake up just those types of lamp, or
      \item an array of above-mentioned items, e.g.  \texttt{["lamp.dimmer",
        "shutter.basic"]} if we are interested in that, etc.
      \end{itemize}

    \item The target field of a \texttt{is\_alive} request is often
      empty, i.e.  broadcasted, but not necessary.

    \item A \texttt{is\_alive} request must not cause any response message. 
      Instead, recipients(s) of the request must respond as much as possible
      by an \texttt{alive} notification (addressed to all).

    \item This method must not be overloaded by extending schemas.
    \end{itemize}

  \item \texttt{get\_description}
    \begin{itemize}[label=]
    \item \texttt{vendor\_id}, \texttt{product\_id}, \texttt{version},
      \texttt{hw\_id}, \texttt{group\_id}, \texttt{url}, \texttt{info},
      \texttt{unsupported\_attributes},
      \texttt{unsupported\_methods},
      \texttt{unsupported\_notifications}
      (out): see the meaning of the above list of attributes.

    \item This method should not be overloaded with extending schemas.  In
      case if this method is overloaded, the above-listed arguments must
      remain.
    \end{itemize}

  \item \texttt{get\_attributes}
    \begin{itemize}[label=]
    \item \texttt{attributes} (in): array of string, the name of wanted
      attributes.  If the array is empty or if this parameter is absent
      within the request, all attributes should be returned.
  
   \item \texttt{<key values of attributes>} (out): Attributes actually
      returned.  The schema \texttt{basic.basic} defines this method with no
      attributes.  However, this method may be overridden in the definition
      of extending schemas.

    \item It is not mandatory to return all requested attributes.  Peers
      should not make any assumption on this.

    \item Reminder: devices do not return the attributes defined by the
      \texttt{basic.basic} schema, only attributes introduced by extending
      schemas.

    \end{itemize}
  \end{itemize}



\subsection{Composite devices} 
This section discusses the case of equipment that is composed of a set of
several elementary devices.  Those cases arise in different circumstances
for which the xAAL solutions differ.  Here are some best-practice
guidelines.


\subsubsection{Gateways}
A gateway is a piece of software and hardware which make the bridge between
the xAAL bus and a proprietary home automation protocol used by some devices
deployed in a facility (e.g.  X10, Zigbee, X2D, Z-Wave, HomeEasy, KeeLoq,
etc.).

The gateway presents one xAAL device on the xAAL bus for each proprietary
home automation device it manages; each one with its own xAAL address and
its own \texttt{dev\_type}.  They are called \emph{embedded devices}.

Moreover, the gateway should present itself as an additional xAAL device,
with its own address and a \texttt{dev\_type:"gateway.basic"}, or any
relevant extended type of gateway.  The gateway maintains the list of its
embedded devices and can be questioned about it.  Some advanced gateways may
also provide information about the status of managed devices (e.g.  if the
gateway know that certain devices are defective or dead).

Even if it is not recommended, a gateway can also choose to be not visible
on the xAAL bus, does not announce itself, nor indicates that it has
embedded devices.


\subsubsection{Group of devices}
A physical equipment may consist of several devices.  For instance, consider
the case of a ``smart control multi-plug socket'', or a small weather
station with several sensors that measures indoor/outdoor temperature,
humidity, etc.

In such a case, the equipment is seen as a set of different xAAL devices,
each one with its own functionalities, attributes, etc.  From a logical
point of view (the xAAL point of view), this equipment is divided into
several xAAl devices.  However, those devices that belong to
the same physical equipment are grouped.  Within their description they
have the same \texttt{group\_id} value (a UUID in fact).  They are called
\emph{grouped devices}.

A group just says that some xAAL devices are physically together, and only
this.  (Which is, however, a highly valuable information for maintenance.)
This does bring no indication about the fact that some of those xAAL devices
could be in relationship from a logical or functional point of view or to
provide some service.  (This is handled within the definition of the schema
of the devices, if needed.)

\subsubsection{Devices Using Others}
A device may provide services on top of other devices.  For instance,
consider the case of the ``smart control multi-plug socket''.  Each of the
plug may be smart because it provides two services.  First of all, this is a
basic plug with a remote-controlled on/off.  This service is implemented by
the xAAL device \texttt{powerrelay.basic}.  Moreover, those smart plug may
embed power consumption monitoring services.  Such a service is implemented
by the xAAL device \texttt{powermeter.basic}.

By design, the xAAL device \texttt{powermeter.basic} provides its service
on top of other devices.  It measures the power of something: possibly only
one plug in the case of the previously mentioned ``smart plug'', or
possibly a large set of several devices, a part of the power supplying
network of the facility (e.g. all equipment of the kitchen, or of a given
floor, etc.). The definition of the \texttt{powermeter.basic} device
includes an attribute to list measured devices (called \texttt{power} in
the current version of the schema definition). This has no relation to the
\texttt{group\_id} introduced in the previous section. 

There is the same consideration with the xAAL device
\texttt{weatherforcast.basic}.  Its schema definition includes an attribute
listing other devices actually used to compute its forecasts (thermometers,
hydrometers, etc.).  This has no relation to the \texttt{group\_id} usage,
which only means that those thermometers, hygrometers and forecast
algorithms may belong (or not) to the same physical box (the weather
station).



\subsection{Changes in xAAL Schemas}
Schemas are written in JSON for now.  This is still the case with xAAL
version 0.7.  The new version proposes to replace JSON by CBOR for messages,
not for schemas.  There are several reasons for this:

\begin{itemize}
\item First, JSON cover the need.  As indicated, a schema tells the list of
  attributes, notifications and methods of the device, plus some extra
  information to describe the device (vendor, model, etc.). The
  expressiveness of JSON is enough for this.

\item Then, a schema should be a document readable by a human (and possibly
  editable), since this brings some semantics that should make sense to
  users and developers.  A binary document, such as CBOR, is only
  understandable by software.  This is not desirable in the context of xAAL
  schemas.
\end{itemize}

Unfortunately, mixing JSON and CBOR may lead to uncomfortable situations
that are investigated bellow.


\subsubsection{Specifying types of attributes and parameters}
Schemas specify the types of the attributes and parameters of devices.

To do this, for each attribute or parameter description, the former format
of xAAL schemas included fragments of Json-Schema.
\footnote{\url{http://json-schema.org/latest/json-schema-core.html}}
\footnote{\url{http://json-schema.org/latest/json-schema-validation.html}}. 
A Json-Schema is a kind of grammar that specifies the form that a JSON data
must fit.  Compares to alternatives (e.g. Json Content Rules
(JCR)\footnote{\url{https://tools.ietf.org/html/draft-newton-json-content-rules-08}},
JSON Constrained Notation
(JSCN)\footnote{\url{https://tools.ietf.org/html/draft-miller-json-constrained-notation-00}},
etc.), Json-Schema uses a pure JSON syntax.  A Json-Schema specification is
written in JSON.  Thanks to this, the type of xAAL attributes and parameters
(in Json-Schema) could be directly included in the xAAL schema.

The key point is that this describes a data presentation for data presented
in JSON.  But xAAL version 0.7 introduces messages in CBOR.  Values of
attributes and parameters are carried by xAAL messages, therefore encoded in
CBOR.  Json-Schema is inappropriate for describing a CBOR data model.  The
dedicate data-model language for CBOR is CDDL (\emph{Concise Data Definition
Language}, RFC 8610).

As a consequence, xAAL schema version 0.7 now describes the types of the
attributes and parameters of devices by the means of CDDL rules.


\subsubsection{Gathering Types Definitions in a Data Model Section}
With the former versions of xAAL schemas, types of data used by attributes
methods and notifications were specified `in-line'.  That is to say, the
schema describes the first attribute by giving its name followed its type
definition, then do the same for the next attribute.  Then it describes a
first method by giving its name and its list of parameters; and for each of
these parameters it gives its name and its type definition.

As a consequence a schema may include several copy paste of data type
definition.  Typically, attributes definitions were duplicated into the
standard \texttt{get\_attributes()} method and into the
\texttt{attributes\_change()} notification.  Those copy pastes made the
schemas hard to read for a human.

Therefore, now xAAL schemas give a type name to each attribute and
parameter, and gather type definition into a dedicated section called
\texttt{data model}.  This data model section is subject to extension
mechanisms as for attributes, methods, and notifications.


\subsubsection{On the Use of CBOR Tags}
In CBOR, a data item can be enclosed by a tag to give it additional
semantics.  Such a tag gives an indication of how data should be
interpreted.  For instance, tag 0 says that a text string has to be
interpreted as a date, tag 1 is for dates since POSIX Epoch (1970-01-01),
tag 32 says that a text string is an URI, tag 37 says that a binary string
is a UUID, etc.  A small set of tags is part of the standard (RFC 7049);
additional tags are defined by a dedicated IANA
registry\footnote{\url{https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml}}.

There are pro and cons on using CBOR tags.  Tags values are carried with
data, this consumes space.  On the other hand, receiver gets in-line
semantic indication to interpret data without having to check any side
specification documents.  This is particularly useful when CBOR is used for
general (de)serialization in a programming environment: many CBOR libraries
widely use tags to provide automatic casting of data into dedicated specific
programming object types.  Conversely, tags are somehow redundant with
information provided within xAAL schemas.

Well, on the basis of these considerations, it has been settled that tags
were not used for low-layers of the xAAL communication protocol (that is to
say the Security Layer and the Application Layer as defined below).  Indeed,
these layers are of a small and rigid shape, without any room for choice or
interpretation of data.  These data items are relating to the xAAL
communication protocol itself.

However, data items relating to attributes, methods and notifications of
xAAL devices are of more complex shapes.  Therefore, xAAL schemas may use
CBOR tags in their data type definitions; for instance, UUID, date, URI. 
Note that, if tags are specified in a xAAL schema, then they are mandatory
into the \emph{body} part of the Application Layer for corresponding
actions.  Tags management may lead to optional behaviors by decoders, but
they are not optional in data items written in messages once they have been
specified by a CDDL rule (as in xAAL schemas).


\subsubsection{Guidelines for Writing Schemas}

\paragraph{Writing Convention.}
Former versions of xAAL used the \emph{Calmel
Case}\footnote{\url{https://en.wikipedia.org/wiki/Camel_case}} writing
convention for naming the elements of xAAL schemas.  This choice was
consistent with habits of JSON (and JavaScript) communities.

The new version of xAAL move from JSON to CBOR, leaving JSON communities. 
Main developers are closer to Python and C communities.  One therefore
decided to move to the
\emph{snake\_case}\footnote{\url{https://en.wikipedia.org/wiki/Snake_case}}
writing convention.


\paragraph{Action Verbs for Methods.}
A key to get an engaging API is to select a wording for elements which carry
an intuitive and well-known meaning.  This makes the talent of the designer. 
There is no universal rule.  However, this sounds reasonable selecting
action verbs to name methods, e.g.  \texttt{turn\_on()} and not just
\texttt{on()}.

Similarly, programmers usually like \emph{accessors} to \emph{attributes},
i.e. \texttt{set\_XXX()} \texttt{get\_XXX()}. (Note that the latter may be
redundant with the generic \texttt{get\_attributes()} method of the
\texttt{basic.basic} schema.)


\paragraph{Describes Functionalities from the Other Point of view.}
Amazon
Alexa\footnote{\url{https://developer.amazon.com/fr/docs/smarthome/get-started-with-device-templates.html}}
and Google
Home\footnote{\url{https://developers.google.com/assistant/smarthome/guides/}}
propose means to design its own device by composing elementary so-called
\emph{capabilities} (Alexa) or \emph{traits} (Google Home).  E.g.  for a
color-changing lamp this means \emph{power on-off} \emph{brightness} \emph{HSV
color} etc.

Such APIs are oriented towards the description of products.  For instance, an
innovative startup may sell an all-in-one connected fan with an oscillating
feature, a colored dimmable lamp, a camera and a thermometer.  The API of such a
device can be written by composing corresponding capabilities or traits.
This is the responsibility of the client application to seek devices and to
turn on the lamp of this fan if the user wants light.

Moreover, this may require sub-addressing.  For instance, a weather station
may provide both temperature and humidity measures, and be exposed with
corresponding capabilities.  However, if this weather station has two
thermometers, the temperature capability has to be instantiated twice, with
a sub-addressing to retrieve each of the two thermometers into the device. 
From the client application point of view, these two thermometers are not
retrieved like other thermometers of the house.

As contrary, xAAL proposes schemas oriented towards the description of
functionalities from the client point of view.  Concretely, a
mult-features product such as a weather station is split into several
devices (thermometers, hygrometers, etc.). Each feature is implemented by a
dedicated xAAL device. Such xAAL devices may then be grouped thanks to a
\emph{group identifier}. Client application may retrieve all thermometers in
the same way whatever they are single thermometer or embedded into an
all-in-one product.



%                                      *
%                                     * *


\section{The xAAL Communication Protocol}
xAAL is a distributed system.  Participating entities need to communicate
with each other.  The xAAL communicating protocol has been designed with
following objectives in mind.

\paragraph{Objectives:}
\begin{itemize}
\item The communicating channel should allow automatic discovering,
  allowing a new entity to join the group without much job to do, and
  allowing other entities to know that a new entity arrives.

\item The communication stack should be simple and lightweight to implement
  in constrained devices, in a stateless manner, without having to maintain
  alive several communication channels in parallel.

\item The communication should be lightweight in terms of messages size and
  number, close to the background noise of a usual home network.

\item The communication should address security considerations, regarding
  users' privacy, or threat to get control.

\item The communication should be simple to configure for the end user.
\end{itemize}

xAAL messages are carried by UDP multicast packets.  xAAL messages are made
of two layers: (i) a Security Layer with some clear fields mandatory for
transport to receivers, followed by a ciphered payload; and (ii) an
Application Layer which consists of the decrypted payload and containing all
information for participating applications.


\subsection{The Security Layer}
The data of the Security Layer is the payload of the UDP multicast messages 
of the xAAL bus. This is a CBOR array of 5 fields:
\begin{itemize}
\item {[0]}:\emph{version} - Unsigned int, of the value \texttt{7}.
  The version of the protocol.
  Other values should be rejected, the message is ignored.
\item {[1]}:\emph{seconds} - Unsigned int.  First half of the timestamp. 
  The number of seconds since the Epoch (1970-01-01 00:00:00 +0000 UTC).
\item {[2]}:\emph{microseconds} - Unsigned int.  Second half of the
  timestamp.  The number of microseconds since the beginning of above
  second.
\item {[3]}:\emph{targets} - A definite byte string build as the CBOR
  serialization of the array of destination addresses for the message.  Note
  that xAAL device addresses are UUID (see Sec.\ref{schemas}), here encoded
  as definite bytestring[16] without tags.  A xAAL device receiving a
  message should accept it if its own xAAL address is present in the array
  of targets.  An empty target array means a broadcast message.  A target
  field containing an empty byte string is not allowed (the message should
  be ignored).
\item {[4]}:\emph{payload} - A definite byte string which is the ciphered
  \emph{Application Layer} according to version 0.5-r2 principles
  (Poly1305/Chacha20, a symmetric key, a binary nonce build on the timestamp
  of messages, an acceptance window for the timestamp of messages, the
  target field covered by the cryptographic signature).
\end{itemize}

If a message includes other fields in addition to the above mandatory ones,
the message may be accepted, but the extra fields must be ignored.

The above-described CBOR items must have no CBOR tags.

\begin{figure}
\centering
\begin{verbatim}
security_layer = [
  version : 7,
  timestamp_sec: uint,
  timestamp_usec: uint,
  targets : bytes .cbor ([ * (bstr .size 16) ]),
  payload : bstr
]
\end{verbatim}
\caption{CDDL specification of the xAAL Security Layer\label{SecurityLayer}}
\end{figure}

Figure \ref{SecurityLayer} gives the CDDL specification of the xAAL Security
Layer.



\subsection{The Application Layer}
The Application Layer is a CBOR array of size 4 or 5, depending if
there is a \emph{body} field or not:
\begin{itemize}
\item {[0]}:\emph{source} - A definite bytestring[16]; the xAAL address
  (UUID) of the sender of the message.
\item {[1]}:\emph{dev\_type} - A definite string; the schema name of the
  sender (The pair \emph{classe.variant}.)
\item {[2]}:\emph{msg\_type} - An usigned int of value: \texttt{0}:notify,
  \texttt{1}:request, \texttt{2}:reply.
  Other values must be rejected, the message is ignored.
\item {[3]}:\emph{action} - A definite string; the name of the 
  action brought by the message from the list of \emph{methods} and 
  \emph{notifications} described in the considered schema. The considered 
  schema is the one of the sender.
\item {[5]}:\emph{body} - An optional field.  If present, it must be a map. 
  Keys of this map are definite strings, the names of parameters associated
  with the corresponding action according to the schema and their value. 
  Depending on data model specified in the schema, values may have CBOR
  tags.  Note that the body may be absent if the schema does not specify
  parameters for the corresponding action. Multiple identical keys are not
  allowed, the message should be ignored.
\end{itemize}

The above-described CBOR items must have no CBOR tags.
However, value items within the \emph{body} may be tagged, according to the
corresponding schema.


\begin{figure}
\centering
\begin{verbatim}
application_layer = [
  source : bstr .size 16,
  dev_type : tstr .regexp "[a-zA-Z][a-zA-Z0-9_-]*\\.[a-zA-Z][a-zA-Z0-9_-]*",
  msg_type : 0..2,
  action : tstr
  ? body : { * ( tstr => any ) }
]
\end{verbatim}
\caption{CDDL specification of the xAAL Application Layer\label{ApplicationLayer}}
\end{figure}

Figure \ref{ApplicationLayer} gives the CDDL specification of the xAAL
Application Layer.


\subsection{The Ciphering Method}
The security of the xAAL bus is ensured by:
\begin{itemize}
\item A symmetric key, pre-shared into all participating devices;
\item Poly1305/Chacha20 as the only cryptographic algorithm, and used
  according to RFC 7905 recommendations (i.e.  with a 96 bits nonce and a
  256 bits key);
\item A binary nonce build as a timestamp since the Epoch
  ( seconds (64 bits) + microseconds (32 bits) );
\item An acceptance window for the timestamp of messages;
\item The list of targets in clear, but covered by the signature;
\item A Security Layer in CBOR, as described above;
\item An Application Layer in CBOR, as described above;
\item The Application Layer is CBOR serialized to produce binary data,
  ciphered into a binary buffer which is placed into the Security Layer as a
  CBOR definite byte string.
\end{itemize}


\paragraph{Notes:}
\begin{itemize}
\item The target field of the Security Layer is a CBOR definite
  byte string.  This is not an array of UUIDs, this is the CBOR
  serialization of an array of UUIDs.  This byte string may be seen as a
  buffer of bytes and can directly be used as the \emph{public additional
  data} for the Poly1305/Chacha20 algorithm, to be covered by the
  cryptographic signature.
\item The binary nonce (96 bits) to be used with Poly1305/Chacha20 is
  composed of the seconds and microseconds (in this order): first a 64 bits
  big-endian unsigned integer (seconds), followed by a 32 bits big-endian
  unsigned integer (microseconds).
\end{itemize}

\paragraph{Recommendations:}
\begin{itemize}
\item To build the cryptographic key from a passphrase:\\ The
  Poly1305/Chacha20 algorithm uses a binary key on 256 bits.  A fine way to
  select a good key is to build it from a passphrase using a cryptographic
  hashing algorithm.

  It is proposed to use the dedicated function provided for this purpose in
  the reference Chacha20 library (the \emph{sodium} library), and derived
  libraries:
  \begin{itemize}
  \item function: \texttt{crypto\_pwhash\_scryptsalsa208sha256()}
  \item for the salt: a buffer of zeros
  \item for the \emph{opslimit}: \texttt{crypto\_pwhash\_scryptsalsa208sha256\_OPSLIMIT\_INTERACTIVE}
          (512k~cycles)
  \item for the \emph{memlimit}: \texttt{crypto\_pwhash\_scryptsalsa208sha256\_MEMLIMIT\_INTERACTIVE}
          (16~Mbytes)
  \end{itemize}

\item To choose a window of acceptance for the timestamp:\\
  An acceptance window of two minutes should be fine.

\item To have several keys on the same bus:\\
  If several key or xAAL versions are needed in a facility, it is
  recommended to use different xAAL buses (UDP ports).

\end{itemize}


\paragraph{Example.} 
Figure \ref{xaalmsgs_sec} gives an example of a xAAL message (the Security
Layer): a message to the target
\texttt{8BCC7ED2-A6AC-4D83-A723-6ED3B168C51F}, with a ciphered payload.

Figure \ref{xaalmsgs_app} shows the decoded payload (the Application Layer):
the sender is the device\\
\texttt{1ADFFD0D-67A6-415D-BC11-74C9CCB32EE9},
of type \texttt{thermometer.basic}, which replies about its attribute
\texttt{temperature:18.0}.

The examples use the textual CBOR Diagnostic Notation.

\begin{figure}[H]
\begin{verbatim}
[ 7,
  1572609657,
  519551,
  h'9F508BCC7ED2A6AC4D83A7236ED3B168C51FFF',
  h'BE67602B9DFC0EDA2CD59FA875109954190D11159C6D67B24CA50201EB09
    84FE782F8BCB4259CD38701027184C5959F080DAD013C7A584F44F7EAE52
    BAA212086AC467C6461AC866F5ECC13C2C5EFA4CD71BDE7987CE68D1E8F0' ]
\end{verbatim}
\caption{Example of a xAAL message (\emph{Security Layer})\label{xaalmsgs_sec}}
\end{figure}

\begin{figure}[H]
\begin{verbatim}
[ h'1ADFFD0D67A6415DBC1174C9CCB32EE9', 
  "thermometer.basic",
  2,
  "get_attributes",
  {"temperature": 18.0} ]
\end{verbatim}
\caption{The decrypted payload of a xAAL message (\emph{Application Layer})\label{xaalmsgs_app}}
\end{figure}


\subsection{Changes in the xAAL Communication Protocol}
As in version 0.5-r2, the xAAL messages in version 0.7 are carried on an IP
multicast bus (IPv4 or IPv6).  Messages are still made of two layers: a
\emph{Security Layer} which encapsulates an \emph{Application Layer}.  Data
fields, the associated semantic and behaviors are the same.

The novelty is that data are now serialized in CBOR (RFC
7049\footnote{\url{https://tools.ietf.org/html/rfc7049}}, and revision draft
7049bis
\footnote{\url{https://tools.ietf.org/html/draft-ietf-cbor-7049bis-07}}). 
For instance, instead of JSON objects, one may use CBOR map.  Also, instead
of using the textual representation of UUID (RFC 4122), one now uses its
binary representation as a CBOR definite byte string of 16 bytes.

JSON was a fine message format for prototyping xAAL.  As a textual format,
this greatly has helped developers to diagnostic issues.  Now xAAL has grown
in maturity.  Moreover, since xAAL version 0.5 have brought ciphering of
messages, keeping a textual format have no more interest.  CBOR brings
compactness (xAAL messages are now about three times smaller), but its main
advantage since xAAL has ciphered data is that CBOR can manage byte string
properly (i.e.  without base64 encoding onto a textual string, as JSON
does).

CBOR has many other concurrent binary coding formats.  Appendix E of RFC
7049 provides a brief comparison.  Not surprisingly, this technical
comparison is positive for CBOR.  Another argument in favor of CBOR is that
CBOR is a published standard.


\paragraph{Maps vs.  Arrays.} JSON is deeply linked to the JavaScript
programming language and inherits of some of its concepts: object-oriented,
dynamic typing, etc.  Within the JSON community, data is frequently
organized into so-called objects data structures (also called maps,
associative arrays, or dictionaries, depending on programming language
vocabulary).  So that, each piece of data is associated with a name, which,
if well chosen, may make sense in the head of other developers of the
community, bringing a kind of intuitive semantic.  This is one of the
reasons why JSON is said a \emph{self-describing} format.  (The other reason
is about the serialization/serialization point of view: thanks to
punctuation marks and syntactic salt, the format of strings carries enough
information to decode bytes into data types of usual programming languages
without any other specification document.)

Within the CBOR community, habits slightly differ.  Maybe due to its binary
basement, developers prefer array structures, used as \emph{struct} in C
programming language.  However, associative maps are also available: it is
still useful to associate well-chosen names to data items.  Moreover, CBOR
provides another means to give semantic to data in a more formal way: data
items may be tagged with a number which refers either a standardized
tag\footnote{\url{https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml}}
or an application-specific tag.  (Note that CBOR is also said a
\emph{self-describing} format from the serialization/serialization point of
view: the format carries enough information to decode bytes into data types
of usual programming languages without any other specification document.)

In conclusion, xAAL version 0.7 chose to use array structures for its
Security Layer and its Application Layer.  There is no more keywords
associated with data items for these two layers.  Data items are provided in
a strict order, in a strict way.  Messages are even shorter, and this brings
simplicity for receivers, without so much complexity for senders.  Moreover,
there is no CBOR Tags in these two low-level layers.  xAAL nodes already
must know those layers format, there is no need to carry tags for the
meaning of fields.


\paragraph{Definite vs.  Indefinite Data Structures.} CBOR data containers
(maps, array, strings, byte strings) are proposed in two variants: definite
(with a predefined size), and indefinite (the container is open at the
beginning, items follow in sequence, the container is closed on reception of
a special end mark).

Both variants have pros and cons, with a balance between the complexity of
the sender versus the complexity of the receiver.  Indefinite data
containers are fine for streaming data on the fly.  This may also ease the
job of the sender if it can't easily predetermine the size of data to send,
without making two passes.  On the other hand, indefinite data containers
may bring more complexity for the job of the receiver which may manage this
either by implementing streaming mechanisms (e.g.  with specific call-back
functions), or by allocating extra buffers.  The situation is even more
uncomfortable with indefinite strings and byte strings for which chunks may
split data at any position.

So, to simplify the job of xAAL receiver, indefinite strings and byte
strings are prohibited within the Security Layer and the Application Layer. 
A priory this choice does not increase so much the complexity in the sender
for building messages since this two layer are of a well-known format.


\subsection{Measures on the Protocol}
xAAL is deployed in our
laboratory\footnote{\url{https://www.imt-atlantique.fr/fr/recherche-et-innovation/plateformes-de-recherche/experiment-haal}}.

\begin{itemize}
\item There are 121 xAAL devices.
\item An average of 4.82 messages per second, that is to say about one
  message every 25 seconds for a device.
\item An average of 378 bytes pear message with xAAL 0.5, and an average of
  128 bytes with xAAL 0.7, in other words: an average bandwidth of 5 bytes
  per seconds for a device.
\end{itemize}

Note that moving from xAAL 0.5 to xAAL 0.7 just changes message size, there
is no impact on the global behavior nor on the number of messages.

Also note that the number of messages is impacted by timeout value for
\emph{alive} notifications and for \emph{get\_description} requests (usually
performed by HMI applications).  However, thanks to bus communication
principles, a reply message to an application is used by other applications. 
Having multiple applications on the bus does not increase so much the number
of messages.


\subsection{Security Considerations}
\subsubsection{Local Communications}
By design, home automation protocols over IP do benefit of the security
offered by the home network, which is made of physical wires or of WiFi
networks with WPA security.  It is therefore at least as hard to get the
control of a home automation from outside as to be able to join the home
network.  A protocol with messages in clear could have been fine.

However, main threats may probably not come from outside.  Nowadays, end
users (happy eye balls, RFC 8305) are used to bring many smart devices at
home, to install many promising applications, embedding times-to-times
suspicious code.  If the home automation protocol does not have any security
code, a malicious application could take control of it (e.g.  deactivate the
alarm, unlock the door for thieves).  More probably, such a third part
application could spy the home automation activity, monitor users' habits
and preferences to feed ads and recommendation systems for consumers.

Such a situation is not desirable, or else, at least, with a clear and
informed opinion of the end user and its agreement...  This is why a certain
level of security should be added to home automation systems.  Messages
should not be in clear, nor ciphered with a hard-coded static key; secret
keys must differ from one home to another; secret keys must not be
preconfigured by companies, but chosen by the end user.

In xAAL version 0.5 and Later, messages are ciphered using
Poly1305/Chacha20 algorithm.  According to experts, it is at least as much
stronger than others (e.g.  AES).  It is now in the cipher suites for TLS
(RFC 7905).\footnote{\url{http://www.rfc-editor.org/rfc/rfc7905.txt}} Due to
its communicating bus principle, xAAL devices can't negotiate cryptographic
parameters prior to sending useful data as with client-server communication
principles (selecting a cipher algorithm, a nonce, Diffie-Hellman keys,
etc.).  xAAL messages must be self-content, also regarding security
parameters.  xAAL uses a pre-shared symmetric key.  This is the only
parameter that the end user has to configure.  The nonce is a timestamp with
a small acceptance window to allow clock drifts.

The security proposed by xAAL is a compromise.  Of course, this can be
criticized.  But a higher security level will break simplicity and
efficiency of xAAL.  The security proposed by xAAL is high enough to protect
data carried by home automation communications, and fits requirements to
address threats model one considers.

\subsubsection{Cloud Communication}
Within the home automation context, users are at home, and services are
rendered at home by the home.  One may wonder where to locate and execute
service: at home or in the clouds.  xAAL, and many others, propose to locate
home automation services at home.  This is a first step to address security
and privacy issues.  However, nowadays, consumers accept cloud solutions. 
This implies to trust involved companies, to give them control of our home,
to give them a view of our activities at home, to believe in their ethic for
today and for the future.  Accepting this is a cost for the consumer.  The
counterpart is the promise to get a simple-to-use service.


\paragraph{Mobile Clients to Cloud Servers.} The first promise is
simplicity.  Generally, `smart devices' wording has to be read as `devices
having Internet access and connected to servers of the company in the
clouds'.  The consumer buy and install home automation devices (smart plugs,
smart outlets, smart lamps, etc.).  Those devices may embed a WiFi network
interface, or may be connected via a dedicated radio protocol to a
hub/gateway/box also present at home, which has a WiFi network interface and
sometime an Ethernet one.  There is a persistent connection between devices
at home and external computers of the company: usually devices forward
sensor measures and events in real time, and can be remotely controlled from
those external computers.  From its side, the consumer uses a mobile
application (a dedicated one or a Web page) which is also connected to those
external computers of the company.  By this means, the user is informed of
events at home and can send commands to its devices.  Companies usually
propose such services for free, or free for the first years.  This process
conforms to nowadays usual design of mobile applications: user applications
are \emph{clients} of \emph{cloud servers}, servers that are retrieved
thanks to a well-known DNS name (Domain Name System, the means to translate
names into Internet addresses).  This process is transparent to the user. 
In addition, the user has the same level of service whatever he or she is at
home near devices, or outside.  Controlling the house from outside by any
member of the family is often presented as an advantage despite there is no
clear demands from consumers.

Mobile applications are rarely designed to reach local servers.  Indeed, few
end-user services assume that there are servers of anything at home;
everything is supposed to be in the clouds.  One of the exceptions is for
\emph{multimedia drives} which allows users to store at home photos videos
and music.  Note that such services are now also competed by cloud services. 
These multimedia drives are based on protocols such as DLNA that offers
discovering features: user applications can retrieve these drives on the
local network and play the contents.  xAAL also has a discovering feature by
itself, which may be used by a xAAL mobile application.  Or else, if the
xAAL user interface / control point is a Web service in a box on the home
network, it can register its well-known name to the local mDNS server thanks
to the Home Networking Control Protocol (HNCP, RFC
7788\footnote{\url{http://www.rfc-editor.org/rfc/rfc7788.txt}} by the
Homenet IETF working group).  This provides a generic discovering mechanism
for local services.  The well-known name of such a xAAL box can then be
retrieved locally by mobile applications, as usual, but at home.


\paragraph{Interoperability in the Clouds.} Another promise is the
interoperability in the clouds.  Indeed, many home automation vendors
propose to interconnect their solution with popular voice assistants (Google
Home, Amazon Alexa, Apple Siri).  These devices called `voice assistants',
`smart speakers', `connected speakers', but rarely `connected microphones',
are cloud services by themselves: the speech recognition (more or less
automatic\footnote{\url{https://www.bbc.com/news/technology-49502292}}) is
mostly performed by external computers, not at home by the device itself. 
Thanks to programming API, but also to commercial agreements between
companies, cloud computers of voice assistants are connected with cloud
computers of home automation vendors.  Such connected microphone records
sounds at home all the time; when a sound matches a given keyword, the sound
stream (or chunks) is pushed to computers of the company of the connected
microphone; the sentence is analyzed by a speech-to-text process; if
keywords associated with home automation are recognized then the text is
pushed to computers of the home automation company; if some home automation
commands are recognized then these computers send commands to devices at
home to which they are permanently connected.  As a result, the end user may
tell requests to its house and see it in action, very impressive.  This kind
of universal interface is somehow a kind of interoperability in the case
there are several home automation technologies at home.  In fact, there is
no real inter-operation between them, just a single user interface.  For
now, this is performed in the cloud, this is why such solutions are called
`interoperability in the cloud'.  In fact, this could also be performed
locally at home.  Speech-to-text is a complex process, and is a precious
added value for companies which manage it.  On-line (cloud) solutions seems
to be of better quality than off-line (local) solutions.  But, depending on
the user’s real needs and feeling, local solutions are good enough for
simple interaction (recognize keywords), as for home automation services. 
Moreover, there is no convincing evidence that speech-to-text algorithms
executed nowadays by cloud computers could not be performed by local
devices.  Companies promise continuous improvements of their secret
algorithms by collecting in the clouds voice and sentences of their
consumers, probably by unsupervised learning algorithms, without
ground-proof and labeled data.


\paragraph{} To sum up, performing home automation `in the clouds' raise
many safety, security, and ethical issues.  There is no real technical
obstacles to perform this completely locally, at home, without any leak of
information in the clouds or to third parties.  xAAL has been designed with
this idea in mind.



\subsection{Alternative Home Automation Protocols over IP}
The xAAL communication protocol was inspired by UPnP, xAP, xPL and others. 

\subsubsection{UPnP}
Universal Plug and Play (UPnP) brings advanced concepts and designs for
device-to device communications on, for instance, home networks.  Functions
are well defined, devices are formally described by schemas, the system
allows discovering, etc.  The main criticism is about its heaviness: it is
based on HTTP, SSD, XML, SOAP, ZeroConf.  Participating nodes often need all
of these layers, each action requires several TCP connections.  Nowadays,
UPnP remain in use for smart TVs to display videos from home media servers,
via the UPnP DLNA sub-profile (Digital Living Network
Alliance)\footnote{\url{https://www.dlna.org/}}.  The home automation UPnP
profile has never really been used in products, except for proof of concept
demos.

\subsubsection{xAP and xPL} 
The eXtensible Automation Protocol
(xAP)\footnote{\url{https://www.xapautomation.org/}} is a pragmatic ad hoc
simple textual home-automation protocol which uses IPv4 broadcast for
message passing between senders and receivers.  xAP has also the notion of
schemas, which defines messages format classes, and somehow device types. 
Main criticism is about its ad hoc nature: schemas are not so formal, and it
is concretely rather difficult to interoperate with a device that one has
not coded by oneself.  The other difficulty is about its addressing
principles by `logical name', `device id', `instance id', `sub-addressing
endpoints', which are commonly replaced by the wildcard mark \texttt{`*'}. 
The last surprising point is about the architectures: hosts are
communicating with each other by IPv4 broadcast, but software on the same
host are locally connected via a UDP unicast socket to a `hub' component in
this host which is in charge to forward those UDP packets to other hosts by
broadcast.

The xPL protocol\footnote{\url{http://xplproject.org.uk/}} is a fork of the
xAP protocol.  It defines itself as a `glue' to tie together home automation
technologies.  It tried to do things in a more formal way: the UDP port in
use was claimed and officially registered by IANA, schemas were written in
XML, unfortunately without clarifying behavior of devices.  Finally, it
suffers from the same criticisms as xAP.

xAP and xPL are ten year old protocols and are now closed projects. 
However, they have participated founding basements of home automation
protocols over IP in terms of need expression and in terms of solutions
basis for interoperability: distributed systems, device-to-device
communications, schemas for devices' definition, lightweight communication
stack...


\subsubsection{MQTT-like Protocols}
There are still recent proposals in the open-source community for simple ad
hoc home automation protocols using the home IP network, such as
MQTT-UDP\footnote{\url{https://mqtt-udp.readthedocs.io/}}.

The Message Queuing Telemetry Transport
(MQTT\footnote{\url{http://mqtt.org/}}) is publish/subscribe messaging
transport protocol designed for machine-to-machine (M2M) communication:
sending commands to a set of devices, collecting data from sensors (e.g. 
measuring particulates and dust of town), etc.  MQTT is a one-to-many
communication system, based on a \emph{star} architecture: a central node
(called broker) is in charge of forwarding published messages towards
subscribers.  Messages are organized by topics, topics are somehow the
addressing system.

The idea of MQTT-UDP is to reuse MQTT principles in a lightweight manner by
replacing the broker by UDP IPv4 broadcast.  The result is an ad hoc
pragmatic transport protocol for smart home applications.  The functional
definition of implied components and specifications of their API is out of
the scope of MQTT-UDP.



\subsubsection{Aqara}
Aqara is home automation company of Lumi United
Technology.\footnote{\url{https://www.aqara.com/en/home.html}} Aqara
products are generally sold by Xiaomi.  Some product variants may be
purchased directly to Aqara, with almost same shape and functionalities.

Technically, Aqara devices are connected to an Aqara Hub at home via the
Zigbee radio
protocol.\footnote{\url{https://www.aqara.com/eu/smart_home_hub.html}}. 
This hub is a small home automation gateway with a WiFi interface for
Internet connection, and which is in charge of forwarding home devices
messages to and from Aqara cloud servers via a non-published but verbose UDP
protocol.  Cloud services allow consumers to get control of their home
devices via a mobile application, retrieve monitored activities, and to set
up automation scripting.  Some automation (e.g.  alarms) are executed
locally by the hub, other more complex are executed by cloud services. 
Aqara cloud platform provides a documented REST API for third-party
applications (e.g.  for compatibility with Google Home, Alexa, and others),
or for open-source
applications.\footnote{\url{http://docs.opencloud.aqara.com/en/development/cloud-development/}}

Some models of Aqara Hubs may be configured to activate a home network
interface in addition to the cloud
connection.\footnote{\url{http://docs.opencloud.aqara.com/en/development/gateway-LAN-communication/}}
This allows user applications controlling home devices directly, without
using cloud services.  This local communication uses two UDP sockets:
multicast and unicast.  The multicast channel is used: (i) for discovering
(for applications to discover hubs present on the home network), (ii) for
heartbeat messages (the hubs and their sub-devices regularly announce that
they are alive, plus a battery level, plus a changing security token), and
(iii) to sends report messages (i.e.  notifications of events and sensors
changes, from the hubs to users' applications).  The UDP unicast channel is
for command control from users' applications to the hubs.  These messages
indicates: (i) the sub-device id (which seems to be stable and in relation
to some Zigbee address of the physical device), (ii) the \emph{model} name
of the sub-device (this model name is specific to the Aqara or to the Xiaomi
products), and (ii) a set of \emph{parameters} relating to the indicated
model name.  These parameters are documented on Web pages of Aqara.

Aqara messages are in JSON format, in clear text.  Note that command
messages include a security key which is computed by concatenating the
gateway key with the device token and then ciphering this with the AES-CBC
128 algorithm, initialized with a predefined vector.  The gateway key is
randomly generated by the Aqara cloud service for the first time the gateway
is installed by the consumer.  This key is stable and is supposed to be
secret.  Mobile applications get it from the cloud after user login. 
Devices tokens are publicly available in heartbeat messages and change every
10 seconds.  Aqara messages are not ciphered nor signed, this security key
just brings a certain level of confidence in the fact that command messages
are sent by a regular application.

To sum up, the Aqara local protocol has some pro and cons.  Having two
sockets makes the communication protocol more cumbersome.  On the other
hand, providing some functionalities on unicast is a pragmatic workaround
for weakness of WiFi regarding multicast.  Devices are described by a model
name, with an effort to document it.  Unfortunately, there is no attempt to
organize those devices' descriptions in terms of family of devices with
shared functions or so.  For now, there are about twenty device models.  One
may wonder about the evolution of the products list.  The security of the
local communication protocol is rather poor, but at least it exists, which
is a rather rare in this domain.  But the main criticism is about the
privacy concerns caused the cloud services.


\subsubsection{Tuya}
Tuya is a business-to-business IoT
company\footnote{\url{https://en.tuya.com/}}.  It does not sell home
automation by itself (or very few), but provides services for other
companies to propose their own devices to consumers.  Tuya has about 75
major companies, and about 93 000 small or medium companies as clients, over
200 countries, for about 90 000 compatible products. 
\footnote{\url{https://docs.tuya.com/en/iot/introduction-of-tuya/introduction-of-tuya}}
\footnote{\url{https://www.journaldunet.com/ebusiness/internet-mobile/1440892-tuya-smart-le-geant-derriere-100-millions-d-objets-connectes/}}
Tuya is one of the preferred technical solutions for low-cost IoT devices. 
An extremely large number of home automation and IoT products use the Tuya
proprietary technology as backend.  Everything is `Tuya-compatible'.  Tuya
therefore present itself as an interoperability solution.  Well, a dominance
industrial position can hardly be seen as a real interoperability solution.

The service provided by Tuya is in three parts.  The heart of its service is
a cloud platform: compatible devices can connect to it, send data to it, and
receive commands from it.  The second part is a generic mobile application
for consumers to get control of their device via the Tuya platform (the
\emph{Tuya Smart Life App}), as well as REST API for companies to develop
their specific mobile application on top the Tuya platform.  The third part
of Tuya services is to provide a code for developers of companies, to be
embedded in their devices.  For this, developers are invited to enroll the
Tuya program, to describe their device (functions, data type, commands,
etc.).  In return, Tuya provides keys to access the platform and piece of
programming code to be embedded in a dedicated Tuya electronic chips with
has integrated WiFi module.  Companies develop their product around the chip
and the code provided by Tuya.  The code opens a TCP socket from the device
at home towards the Tuya cloud platform.  Users data goes on the Tuya cloud
platform.  The Tuya cloud platform control Tuya devices at home, send
commands, update firmware remotely, etc.

Tuya is a very popular solution with many devices sold.  As a consequence,
it has been widely studied, via reverse-engineering processes due to the
lack of open documentation, either for checking its
security\footnote{\url{https://www.heise.de/newsticker/meldung/Smart-Home-Hack-Tuya-veroeffentlicht-Sicherheitsupdate-4292028.html}}\footnote{\url{https://techsecurity.news/tag/tuya/}},
either to develop alternative compatible
applications\footnote{\url{https://github.com/codetheweb/tuyapi}}.

Tuya devices communicate with their servers via HTTP (or HTTPS, depending on
the Tuya version) for configuration and key exchange.  Then command control
of devices is performed with MQTT, whose messages may be encrypted using
AES-128 (depending on the Tuya version).  Security is performed by a
symmetrical key which is configured by the Tuya company and pushed to users'
devices and application.  In parallel to cloud communications, Tuya devices
accept local communications with a similar shape of protocol, allowing
mobile applications of the user to control devices locally without a
go-and-back in the clouds.  Messages are in JSON format.  Parameters are
passed as a map of registers named \texttt{"1"} \texttt{"2"}, etc.  whose
meaning is not specified and corresponds somehow to what the developer has
set up the device functions.  There is no formal specification of devices. 
Tuya is widely deployed, but suffer from safety, security and privacy
issues.



\subsubsection{CoAP} 
The Constrained Application Protocol
(CoAP\footnote{\url{http://coap.technology/}}, RFC
7252\footnote{\url{https://tools.ietf.org/html/rfc7252}}) is a popular
machine-to-machine protocol.  It is based on the
REST\footnote{\url{https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm}}
model, adapted for small devices.  It is a client-server architecture (i.e. 
many-to-one), and use HTTP-like methods such as GET, PUT, POST, and DELETE. 
It is resource-oriented.  For instance, a thermometer has the temperature
value as a resource.  The server address and the resource name compose the
URI managed by CoAP.  CoAP is much lightweight than the HTTP protocol.  It
is based on UDP.  The payload is in XML, JSON, or CBOR format.  Packets may
be ciphered with DTLS\footnote{\url{https://tools.ietf.org/html/rfc5238}}. 
CoAP support multicast (without ciphering) for one-to-many communications,
for instance to send a command towards several devices.  CoAP was designed
for IoT use cases, to manage devices in large area networks.

CoAP could also have been a good candidate for home automation and for the
xAAL system.  Unfortunately, its client-server approach does not fit the
many-to-many communication needs.  xAAL proposes a full distributed
architecture for home automation.  Well, CoAP could have been diverted to do
the same: if all nodes are both client and server, one gets a multi-server
architecture which is somehow a distributed architecture.  With a bus
communication, a thermometer post one message when its temperature changes. 
With a client-server communication, the thermometer expects request messages
then send reply messages, or posts messages to previously subscribed clients
(that have to be kept in memory).  For home automation, a bus communication
is more efficient than client-server communications even if this could work.

The main obstacle in using CoAP is for the definition of a security
mechanism for many-to-many communications.  CoAP uses DTLS (TLS for
datagrams) which require a preliminary negotiation stage prior to send data:
to agree on a ciphering algorithm, session keys, nonce, etc.  This is
feasible for client-server communication, not for bus communications: each
one post its messages on the bus without any preliminary knowledge of
others.  This is why a dedicated communication protocol has been designed
within the xAAL system.


\subsubsection{OpenHAB} 
The Open Home Automation Bus
(OpenHAB\footnote{\url{https://www.openhab.org/}}), ported by the OpenHab
Fundation\footnote{\url{https://www.openhabfoundation.org/}} is a popular
open-source software solution for home automation.  This is a central
solution (e.g.  to be installed in a home automation `box').  This
centralizes in a single software several home automation functions: user
interface, scripting features for automation, and gateways towards many
physical devices and technologies.  To address interoperability issues, this
software supports multiple vendor specific home automation systems by the
means of add-ons (named \emph{bindings} in the OpenHAB vocabulary).  For
now, add-ons are developed by the open-source community.  Home automation
companies are then invited to provide their add-ons for their devices
(similar than PC drivers for peripherals).  Due to this technical detail,
this is still the OpenHAB name and logo which is displayed on the box, not
the ones of home automation companies.  This can be a real obstacle to the
adoption of this approach.

The software is developed with the Java language, and use a OSGi
architecture (Open Services Gateway initiative, now OSGi
Alliance\footnote{\url{https://www.osgi.org/}}).  Natively, Java VM does not
provide technical means for dynamic libraries loading.  OSGi is an answer to
cover the need.  OSGi proposes a component architecture.  Components, named
\emph{bundles}, can be dynamically loaded to extend the software, and are
communicating with each other via a software bus.  OpenHAB specializes this
bus with \emph{channels}; this bus is the \emph{B} of OpenHAB.  OpenHAB is
not a network protocol.  However, some bundles propose a REST API to
remotely control the box from iOS, Android, or Web applications.


\subsubsection{Confluens} 
The Confluens project\footnote{\url{http://confluens.io/}} aims to address
home automation interoperability.  It is both a software solution and a
company created by home automation companies: CDVI (access control systems),
Delta Dore (heating control devices), Hager, Legrand, Schneider-Electric
(electrical equipment) and Somfy (shutters control automation). 
Technically, this is an inter-box communication system.  The idea is that a
consumer may have several products at home from different companies, each
one managed by the home automation box of the corresponding company.  So,
there may be several home automation boxes at home.  The boxes may share
information and work together.  Communication is based on the MQTT protocol,
inside the home network.  A discovery mechanism allows joining new boxes and
to elect the box which is to play the role of the MQTT broker. 
Communications are securized by TLS (Transport Layer
Security\footnote{\url{https://tools.ietf.org/html/rfc8446}}).  The
Confluens company is the certificate authority, signs the TLS certificates,
and manage their deployment on partners' boxes.

A home automation box is a centralized solution.  Confluens proposes a
multi-box approach.  This is less distributed than the xAAL approach, but
this is a first step.  The MQTT protocol is a machine-to-machine protocol
designed for the global Internet, and may be heavy to be used inside a home
network, a local area network.  The pyramidal signing mechanism of TLS'
certificates can't allow third parties to enter the loop without prior
agreement between companies.  The security is in the hands of companies and
not in end users' ones.  At the opposite, xAAL allows users to manage their
privacy.

Confluens is now an ended project.  No product was sold with this
technology.  According to last news from involved companies, the code is
willing to be distributed to the open-source community.




%                                      *
%                                     * *




\cleardoublepage
\appendix

\section{CDDL Rules for xAAL Schemas}\label{schema.cddl}
{\small\begin{verbatim}
; Definition of Schemas for xAAL version 0.7
; Copyright Christophe Lohr IMT Atlantique 2019
; Copying and distribution of this file, with or without modification, are
; permitted in any medium without royalty provided the copyright notice
; and this notice are preserved.  This file is offered as-is, without any
; warranty.


schema = {
  ; The name of the device schema, i.e. the dev_type
  title: dev_type,

  ; A short description in natural language
  description: tstr,

  ; IETF BCB47 language tag of descriptions
  lang: tstr,

  ; URI (rfc3986) pointing to a more comprehensive documentation
  documentation: tstr,

  ; URI (rfc3986) pointing to the original version of this schema
  ; i.e. before any extention process
  ref: tstr,

  ; License of the the original schema file itself
  ? license: tstr,

  ; The schema name which is extended by this one
  ? extends: dev_type,

  ; List of attributes managed by the device
  ? attributes: { + identifier => type_name },
 
  ; Methods supported by the device
  ? methods: { + identifier => method },

  ; Notifications emitted by the device
  ? notifications: { + identifier => notification },

  ; Specifications of data mentionned in the schema
  ; Typically: attributes, parameters of methods and notifications
  ? datamodel: { + identifier => datadef }
}



; Format of the name of a schema in the form "foo.bar"
dev_type = tstr .regexp "[a-zA-Z][a-zA-Z0-9_-]*\\.[a-zA-Z][a-zA-Z0-9_-]*"


; Format of names for attributes, methods and notification
identifier = tstr .regexp "[a-zA-Z][a-zA-Z0-9_-]*"

type_name = identifier


; Definition of a method
method = {
  ; A short description in natural language
  description: tstr,

  ; List of input parameters
  ? in: { * identifier => type_name },

  ; List of output data
  ? out: { * identifier => type_name },

  ; List of device attributes that may be modified while invoking the method
  ? related_attributes: [ * identifier ]
}


; Definition of a notification
notification = {
  ; A short description in natural language
  description: tstr,

  ; List of output data
  out: { * identifier => type_name }
}


; Definition of a data
; Used by device attributes, methods and notifications parameters
datadef = {
  ; A short description in natural language  
  description: tstr,

  ; Unit, according to the IANA Sensor Measurement Lists (SenML) registry
  ? unit: tstr,

  ; Formal descrtiption in CDDL (rfc8610)
  type: tstr
}
\end{verbatim}}


\end{document}
