sofia2 apissofia2.com/docs/(en) sofia2-sofia2 apis.pdf · sofia2 apis page 8/98 3 communication...

98
SOFIA2 APIS September 2014 Version 7

Upload: ngokhanh

Post on 18-Aug-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIS

September 2014

Version 7

Page 2: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 2/98

1 INDEX

1 INDEX ............................................................................................................................................. 2

2 INTRODUCTION .............................................................................................................................. 7

2.1 REQUIREMENTS ................................................................................................................... 7

2.2 GOALS AND SCOPE OF THE CURRENT DOCUMENT ....................................................................... 7

3 COMMUNICATION PROTOCOLS (KP-SIB) ........................................................................................ 8

3.1 MQTT ............................................................................................................................... 8

3.1.1 Gateway MQTT ........................................................................................................ 8

3.2 RESTFUL ............................................................................................................................ 8

3.2.1 RESTful Gateway ...................................................................................................... 8

3.3 AJAX PUSH (JAVASCRIPT) .................................................................................................... 19

3.3.1 Gateway Ajax Push ................................................................................................. 19

3.4 WEBSOCKET ...................................................................................................................... 20

3.4.1 Gateway Websocket: ............................................................................................. 20

3.5 OTHER PROTOCOLS ............................................................................................................ 20

4 SSAP MESSAGING ......................................................................................................................... 22

4.1 JOIN ............................................................................................................................... 22

4.1.1 Request: ................................................................................................................. 22

4.1.2 Response: ............................................................................................................... 22

4.1.1 23

4.1.2 23

4.1.3 Response to Incorrect Request: ............................................................................. 23

4.2 LEAVE ............................................................................................................................. 25

4.2.1 Request: ................................................................................................................. 25

4.2.2 Response: ............................................................................................................... 25

4.3 QUERY ............................................................................................................................ 26

4.3.1 Native Query .......................................................................................................... 26

Page 3: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 3/98

4.3.2 SQL-Like-type Query ............................................................................................... 28

4.3.3 SIB-DEFINED-type Query ........................................................................................ 31

4.3.4 BDH-type Query ..................................................................................................... 33

4.4 INSERT ........................................................................................................................... 36

4.4.1 Request: ................................................................................................................. 36

4.4.2 Response: ............................................................................................................... 37

4.5 UPDATE .......................................................................................................................... 37

4.5.1 Request: ................................................................................................................. 37

4.5.2 Response: ............................................................................................................... 38

4.6 DELETE ........................................................................................................................... 38

4.6.1 Request: ................................................................................................................. 38

4.6.2 Response: ............................................................................................................... 39

4.7 SUBSCRIBE ..................................................................................................................... 39

4.7.1 Request: ................................................................................................................. 39

4.7.2 Response: ............................................................................................................... 40

4.8 UNSUBSCRIBE ................................................................................................................ 40

4.8.1 Request: ................................................................................................................. 40

4.8.2 Response: ............................................................................................................... 41

4.9 INDICATION ................................................................................................................... 41

4.9.1 Response ................................................................................................................ 41

4.10 CONFIG .......................................................................................................................... 42

4.10.1 Request: ................................................................................................................. 42

4.10.2 Response: ............................................................................................................... 42

4.11 BULK .............................................................................................................................. 43

4.11.1 Request .................................................................................................................. 44

4.11.2 Response ................................................................................................................ 44

5 JAVA API ...................................................................................................................................... 46

Page 4: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 4/98

5.1 INTRODUCTION .................................................................................................................. 46

5.2 MAVEN DEPENDENCY ......................................................................................................... 46

5.3 KP INTERFACE ................................................................................................................... 46

5.4 PROTOCOL CONNECTORS IN THE API ..................................................................................... 47

5.4.1 MQTT ...................................................................................................................... 47

5.4.2 RESTFul ................................................................................................................... 48

5.4.3 Websocket .............................................................................................................. 52

5.4.4 Extension with new protocols ................................................................................ 53

5.5 API UTILITIES .................................................................................................................... 54

5.5.1 Class SSAPMessageGenerator ................................................................................ 54

5.5.2 Binary Support........................................................................................................ 55

5.5.3 SSAPMessage and derived classes ......................................................................... 59

5.5.4 SSAPBulkMessage and derived classes ................................................................. 60

5.6 USE EXAMPLE .................................................................................................................... 61

6 ANDROID API ............................................................................................................................... 62

6.1 INTRODUCTION .................................................................................................................. 62

6.2 DISTRIBUTION ................................................................................................................... 62

6.3 KP INTERFACE ................................................................................................................... 62

6.4 SIMILARITIES WITH JAVA API .............................................................................................. 63

6.5 USE EXAMPLE .................................................................................................................... 63

7 ARDUINO API ............................................................................................................................... 65

7.1 KPMQTT LIBRARY .............................................................................................................. 65

7.2 SUPPORTED PROTOCOLS ...................................................................................................... 66

7.2.1 MQTT ...................................................................................................................... 66

8 JAVASCRIPT API ............................................................................................................................ 68

8.1 KP-CORE.JS LIBRARY ............................................................................................................ 68

8.2 SUPPORTED PROTOCOLS ..................................................................................................... 69

Page 5: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 5/98

8.2.1 Webscoket .............................................................................................................. 69

8.2.2 AJAX/AJAX Push...................................................................................................... 70

9 NODE.JS API ................................................................................................................................. 72

9.1 INTRODUCTION .................................................................................................................. 72

9.2 KPMQTT.JS LIBRARY .......................................................................................................... 72

9.3 SSAP MESSAGE GENERATOR ............................................................................................... 73

9.4 SUPPORTED PROTOCOLS ...................................................................................................... 77

9.4.1 MQTT ...................................................................................................................... 77

9.5 USE EXAMPLE .................................................................................................................... 77

10 C API ............................................................................................................................................. 80

10.1 LIBSSAP-CORE-API-C LIBRARY ................................................................................................ 80

10.2 COMPILING WITH MAKE ...................................................................................................... 80

10.3 SUPPORTED PROTOCOLS ...................................................................................................... 81

10.4 API FEATURES ................................................................................................................... 81

10.5 API FUNCTIONS ................................................................................................................. 81

10.5.1 KP-SIB communication functions ........................................................................... 81

10.5.2 SSAP messages handling functions ........................................................................ 84

10.5.3 Structures used in the API ...................................................................................... 91

10.6 ADDITIONAL UTILITIES ......................................................................................................... 92

10.6.1 cJSON ...................................................................................................................... 92

10.7 API USAGE ........................................................................................................................ 93

10.7.1 Connect to the platform......................................................................................... 93

10.7.2 Disconnect from the platform ................................................................................ 94

10.7.3 Send SSAP messages .............................................................................................. 95

10.7.4 Processs the response with cJSON ......................................................................... 96

10.7.5 Liberar memoria de estructuras utilizadas ............................................................ 97

10.8 COMPILER PARAMETERS TO INCLUDE THE API ......................................................................... 97

Page 6: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 6/98

11 OTHER APIS .................................................................................................................................. 98

Page 7: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 7/98

2 INTRODUCTION

2.1 Requirements

Before you read this guide, we strongly suggest you to read SOFIA2- SOFIA2 Concepts.doc

2.2 Goals and scope of the current document

The current document aims to describe the different APIs provided by the SOFIA Platform to

develop KPs.

Page 8: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 8/98

3 COMMUNICATION PROTOCOLS (KP-SIB)

Within a SOFIA SmartSpace, the SIB acts as a communication gateway with the KPs,

receiving SSAP messages.

The SIB supports several communication protocols out-of-the-box, allowing the KPs to

connect with the SIB.

Those protocols can be enabled or disabled using the settings.

The SIB also offers the plug-in concept to develop new connectors and to enable new

protocols that fit specific needs.

We will now see the protocols offered by the SIB:

3.1 MQTT

MQTT (Message Queue Telemetry Transport) is a connectivity protocol focusing in M2M

(machine-to-machine) and IoT (Internet of Things).

It is a lightweight messaging protocol based on TCP and especially designed for remote devices

with little memory and little processing power. It is based in a publish/subscribe messaging

model that eases one-to-many distribution.

3.1.1 Gateway MQTT

The SOFIA2 Platform deployed in the URL sofia2.com provides an MQTT Gateway through TCP

in ports 1880 and 1884.

This Gateway answers MQTT messages having as a payload a remotely-sent SSAP message.

3.2 RESTful

3.2.1 RESTful Gateway

The deployment of SOFIA2 in sofia2.com provides a RESTful Gateway to invoke operations on

that instance.

This Gateway works around SSAPResource, which represents, along with the Gateway HTTP

verbs, the different SSAP operations.

SSAPResource is described by the following schema:

<xs:sequence>

Page 9: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 9/98

<xs:element minOccurs="0" name="data" type="xs:string"/> <xs:element minOccurs="0" name="instanceKP" type="xs:string"/> <xs:element name="join" type="xs:boolean"/> <xs:element name="leave" type="xs:boolean"/> <xs:element minOccurs="0" name="ontology" type="xs:string"/> <xs:element minOccurs="0" name="sessionKey" type="xs:string"/> <xs:element minOccurs="0" name="token" type="xs:string"/> </xs:sequence>

The properties are:

join: If the resource represents an SSAP JOIN operation, its value will be true.

instanceKP: In case the resource represents an SSAP JOIN operation (join=true), its

value will be the KP instance joining to the SIB. It will be ignored in any other operation.

token: In case the resource represents an SSAP JOIN operation (join=true), its value

will be the authentication token for the KP instance requesting the operation.

leave: If the resource represents an SSAP LEAVE operation, its value will be true.

data: Contains the data of the SSAP request or response for any operation that needs

them.

ontology: Indicates the ontology over which the SSAP operation is requested.

sessionKey: SessionKey of the SSAP logical session for which the operation is

requested.

The RESTful Gateway accepts and returns information in JSON format. Therefore, both

requests to and responses from the Gateway include in their headers the attribute Content-

type: application/json, and the SSAPResource shuold be sent in the request body coded as a

JSON object.

The WADL descriptor for the RESTful Gateway is available in:

http://sofia2.com/sib/services/api_ssap?_wadl

As well, you can find web documentation of the Gateway in

http://sofia2.com/sib/

selecting the API RESTFul SOFIA2 option in the APIS menu, and the SSAPResource option in

the OBJECTS menu:

Page 10: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 10/98

The corresponde between the RESTful Gateway and the SSAP protocol is:

JOIN: Operation with POST HTTP method over /api_ssap/v01/SSAPResource/

sending in the request body an SSAPResource object with the attributes:

o join: true.

o instanceKP: <KP name>:<KP instance>.

o token: Token to identify the KP.

Example:

{

"join": true,

"instanceKP": "KPvisualizacionHT:KPvisualizacionHT01",

"token": "cbb9364c434543a18dc6efa30dc780eb"

}

LEAVE: Operation with POST HTTP method over /api_ssap/v01/SSAPResource/

sending in the request body an SSAPResource object with the attributes:

o leave: true.

o sessionKey: sessionKey of the SSAP session to close.

Example:

Page 11: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 11/98

{

"leave": true,

"sessionKey": "f74babaa-26c5-4b8f-901c-98c3e7254fc"

}

INSERT: It is solved in two ways over RTDB:

o NATIVE: Operation with POST HTTP method over

/api_ssap/v01/SSAPResource/ sending in the request body an SSAPResource

object with the attributes:

data: Instance of the ontology to insert.

ontology: Ontology over which the instance is inserted.

sessionKey: sessionKey of the SSAP session.

Example:

{

"sessionKey":"5d59872f-4e64-4111-a660-5d7d4e415bad",

"ontology":"SensorTemperatura",

"data":"······"

}

o SQL LIKE: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: SQL insert statement.

$queryType: SQLLIKE

Example:

/api_ssap/v01/SSAPResource?$sessionKey=b0e24264-6606-4682-b816-

49831ec1f5ae&$query=insert into SensorTemperatura (identificador, timestamp,

medida,unidad) values ("Nuevo",1357930309163,0, "C");&$queryType=SQLLIKE

BDH inserts are also supported:

o BDH: Operation with GET HTTP method over /api_ssap/v01/SSAPResource/

sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

Page 12: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 12/98

$query: SQL insert statement.

$queryType: BDH

Example:

/api_ssap/v01/SSAPResource?$sessionKey=b0e24264-6606-4682-b816-

49831ec1f5ae&$query=insert into SensorTemperatura (identificador, timestamp,

medida,unidad) values ("Nuevo",1357930309163,0, "C");&$queryType=BDH

UPDATE: It is solved in two ways:

o NATIVE: Operation with PUT HTTP method over

/api_ssap/v01/SSAPResource/ sending in the request body an SSAPResource

object with the attributes:

data: Instance of the ontology to update. Composed of (see example):

ObjectId of the instance in the RTDB (returned by the SIB in the

INSERT operation).

New instance data, in the format described by the ontology

schema.

ontology: Ontology over which the data is updated

sessionKey: sessionKey of the SSAP session

Example:

{

"sessionKey":"ab77b168-6389-4d62-aa79-97984037de1a",

"ontology":"SensorTemperatura",

"data":"

{\"_id\":{\"$oid\": \"527a6352c0af4380e54822e1\"},

\"SensorTemperatura\":

{\"coordenadaGps\":{\"altitud\":10,

\"latitud\":40.508277,\"longitud\":-3.676827},

\"identificador\":\"S_Temperatura_00001\",

\"medida\": 30,

\"timestamp\":1383678276000,

\"unidad\": \"C\"}

}"

Page 13: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 13/98

}

o SQL LIKE: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: SQL update statement.

$queryType: SQLLIKE

Example:

/api_ssap/v01/SSAPResource?$sessionKey=b0e24264-6606-4682-b816-

49831ec1f5ae&$query=update SensorTemperatura set

SensorTemperatura.identificador="ST-TA32312" where

SensorTemperatura.identificador = "ST-TA3231-2";&$queryType=SQLLIKE

DELETE: It is solved in three ways:

o NATIVE: Operation with DELETE HTTP method over

/api_ssap/v01/SSAPResource/ sending in the request body an SSAPResource

object with the attributes:

data: Instance of the ontology to delete. Contains the ObjectId of

the instance in the RTDB (returned by the SIB in the INSERT

operation).

ontology: Ontology over which the data is deleted.

sessionKey: sessionKey of the SSAP session.

o SQL LIKE: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: SQL delete statement.

$queryType: SQLLIKE

Example:

/api_ssap/v01/SSAPResource?$sessionKey=b0e24264-6606-4682-b816-

49831ec1f5ae&$query=delete from SensorTemperatura where

SensorTemperatura.identificador = "ST-TA3231-2";&$queryType=SQLLIKE

o By ID as path param: This is not a RESTFul operation, but it has been

included in the API for simplicity.

Page 14: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 14/98

Operation with DELETE HTTP method over the path /api_ssap/v01/{objectId}

with the following parameters:

{objectId}: Path param with the ObjectId of the instance to delete.

$sessionKey: Query param with the sessionKey of the SSAP session.

$ontology: Query param with the ontology over which the data is

deleted.

Example:

/api_ssap/v01/SSAPResource/527a6346c0af4380e54822db?$sessionKey=fe70c

11e-6ca1-4cad-8cfd-737cdfe0277a&$ontology=SensorTemperatura

QUERY: It is solved in 4 different ways over the RTDB

o NATIVE by criteria: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: Native search criteria (body of find()).

$ontology: Ontology over which the query is performed

$queryType: NATIVE

Example:

/api_ssap/v01/SSAPResource?$sessionKey=fe70c11e-6ca1-4cad-8cfd-

737cdfe0277a&$ontology=SensorTemperatura&$query={"SensorTemperatura.m

edida":{$gt:30}}&$queryType=NATIVE

o NATIVE statement: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: native query statement over the RTDB.

$queryType: NATIVE

Example:

/api_ssap/v01/SSAPResource?$sessionKey=fe70c11e-6ca1-4cad-8cfd-

737cdfe0277a&$query=db.SensorTemperatura.find({"SensorTemperatura.medid

a":{$gt:30}})&$queryType=NATIVE

o SQL LIKE: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

Page 15: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 15/98

$sessionKey: sessionKey of the SSAP session.

$query: SQL select statement.

$queryType: SQLLIKE.

Example:

/api_ssap/v01/SSAPResource?$sessionKey=<session_key>&$query=delete

from SensorTemperatura where SensorTemperatura.identificador = "ST-

TA32311";&$queryType=SQLLIKE

o SIB DEFINED query: Operation with GET HTTP method over

/api_ssap/v01/SSAPResource/ sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: Identifier of the SIB_DEFINED query in the SIB.

$queryType: SIB_DEFINED.

$queryArguments: If the predefined query included parameters, JSON

map with the key-value pairs of the query arguments.

Example:

/api_ssap/v01/SSAPResource?$sessionKey=<session_key>&$query=selectAll

WithParam&$queryArguments={"PARAM1":"\"S_Temperatura_00001\""}&$quer

yType=SIB_DEFINED

BDH queries are also supported:

o BDH: Operation with GET HTTP method over /api_ssap/v01/SSAPResource/

sending the request with the query parameters:

$sessionKey: sessionKey of the SSAP session.

$query: SQL select statement.

$queryType: BDH

Ejemplo:

/api_ssap/v01/SSAPResource?$sessionKey=<session_key>&$query=delete

from SensorTemperatura where identificador = "ST-

TA32311";&$queryType=BDH

The responses for every operation, with all the possible error codes, are:

Page 16: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 16/98

JOIN

Result Response code Response body

OK 200 (OK) SSAPResource with the assigned

sessionKey

Empty parameters 400 (BAD_REQUEST) Descriptive message

KP instance does

not exist

401 (UNAUTHORIZED) Descriptive message

Invalid token 401 (UNAUTHORIZED) Descriptive message

Any other error 501

(INTERNAL_SERVER_

ERROR)

Error information

LEAVE

Result Response code Response body

OK 200 (OK) empty

Empty parameters 400 (BAD_REQUEST) Descriptive message

Invalid sessionKey 400 (BAD_REQUEST) Descriptive message

Any other error 501

(INTERNAL_SERVER_

ERROR)

Error information

INSERT

Result Response code Response body

OK 200 (OK) SSAPResource with the objectId

assigned to the ontology instance in the

RTDB

Empty parameters 400 (BAD_REQUEST) Descriptive message

Invalid sessionKey 400 (BAD_REQUEST) Descriptive message

Ontology does not

exist

400 (BAD_REQUEST) Descriptive message

Page 17: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 17/98

Result Response code Response body

Operation not

allowed over the

ontology

403 (FORBIDDEN) Descriptive message

Ontology instance

to insert does not

fulfill schema

validation

400 (BAD_REQUEST) Descriptive message

Any other error 501

(INTERNAL_SERVER_

ERROR)

Error information

UPDATE

Result Response code Response body

OK 200 (OK) empty

Empty parameters 400 (BAD_REQUEST) Descriptive message

Invalid sessionKey 400 (BAD_REQUEST) Descriptive message

Ontology does not

exist

400 (BAD_REQUEST) Descriptive message

Operation not

allowed over the

ontology

403 (FORBIDDEN) Descriptive message

Ontology instance

to update does not

exist

400 (BAD_REQUEST) Descriptive message

Any other error 501

(INTERNAL_SERVER_

ERROR)

Error information

DELETE

Result Response code Response body

OK 200 (OK) empty

Page 18: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 18/98

Result Response code Response body

Empty parameters 400 (BAD_REQUEST) Descriptive message

Invalid sessionKey 400 (BAD_REQUEST) Descriptive message

Ontology does not

exist

400 (BAD_REQUEST) Descriptive message

Operation not

allowed over the

ontology

403 (FORBIDDEN) Descriptive message

Ontology instance

to delete does not

exist

400 (BAD_REQUEST) Descriptive message

Any other error 501

(INTERNAL_SERVER_

ERROR)

Error information

QUERY

Result Response code Response body

OK 200 (OK) SSAPResource with the query result

Empty parameters 400 (BAD_REQUEST) Descriptive message

Invalid sessionKey 400 (BAD_REQUEST) Descriptive message

Ontology does not

exist

400 (BAD_REQUEST) Descriptive message

Operation not

allowed over the

ontology

403 (FORBIDDEN) Descriptive message

Invalid queryType 400 (BAD_REQUEST) Descriptive message

Predefined query

identifier does not

exist in SIB

400 (BAD_REQUEST) Descriptive message

Misiing argument

for predefined

400 (BAD_REQUEST) Descriptive message

Page 19: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 19/98

Result Response code Response body

query

Any other error 501

(INTERNAL_SERVER_

ERROR)

Error information

3.3 Ajax Push (JavaScript)

AJAX (Asynchronous JavaScript And XML) is a web development technique to create

interactive applications or (Rich Internet Applications). Those applications run in the client,

meaning in the user’s browser, while at the same time an asynchronous communication with the

server is kept on the background.

Ajax is an asynchronous technology, meaning that additional data are requested to the server

and then are downloaded in the background, avoiding any interference with the page’s display

or behaviour.

Ajax Push allows for the interaction with the server’s Java code using the browser’s JavaScript

and vice versa: Making call to JavaScript functions in the user’s browsers from the server’s code

(reverse Ajax) and editing the web pages with the results of the queries in a way that is

transparent to the user.

3.3.1 Gateway Ajax Push

The SOFIA2 Platform deployed at sofia2.com provides an Ajax and Ajax Push Gateway through

the JavaScript library kp-core.js, which the client must import to interoperate with the SIB.

To import the library, the <script> tag must be used

<script type='text/javascript' src='kp-core.js'>;</script>

This is an example of use for this library.

/* e.g., to connect with the SIB, we can implement this functionality. It invokes the JOIN

operation, and provides it with parameter including user name, password, instance and SSAP

message */

function connectSIB(user, pass, inst) {

Page 20: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 20/98

join(user, pass, inst,function(SSAPmessage){ if(SSAPmessage != null && SSAPmessage.body.data != null && SSAPmessage.body.ok == true){ $("#infoConexion").text("Connected to SIB with sessionkey: "+SSAPmessage.sessionKey).show(); }else{ $("#infoConexion").text("Error when trying to connect with the SIB").show(); } }); }

3.4 Websocket

WebSocket is a technology that provides a bidirectional communication channel and full-

duplex on a single TCP socket. It is designed to be implemented in browsers and web

servers, but can be used by any client/server application.

The use of this technology provides similar functionality to opening multiple connections in

different ports, but multiplexing different WebSocket services over a single TCP port (at the cost

of a small protocol overhead) .

The browsers that currently support WebSocket are:

3.4.1 Gateway Websocket:

The deployment of the Sofia2 Platform on the address sofia2.com provides a WebSocket

Gateway. In the endpoint ws://sofia2.com/sib/api_websocket

3.5 Other protocols

The SOFIA roadmap includes adding other protocols in the future. Those protocols are:

AMQP (Advanced Message Queuing Protocol): Standard, open, application-layer

protocol for messaging. Allows for interoperability between different systems. Is

language-autonomous and implementation-autonomous. Includes Point-To-Point,

Page 21: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 21/98

Publish, Subscribe, Fan-Out and Request-Response patterns. It has several

implementations, being some of the most popular RabbitMQ, OpenAMQ, and StormMQ.

JMS (Java Message Service): This API is part of the J2EE platform to access

Messaging Systems (MOM). Allows the applications’ components to create, send,

receive and read messages. JMS offers a common access interface for different MOMs.

The JMS implementations support access to P2P and Publish/Subscribe messaging.

WebSockets: An HTML5 standard allowing bidirectional communication between the

client (can be any recent browser) and the web server. It does not work directly on

HTTP, but directly on a TCP socket, allowing for the creation of native bidirectional

communication. The messages are instantly exchanged with little overload.

Page 22: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 22/98

4 SSAP MESSAGING

SSAP (Smart Space Access Protocol) is the standard messaging protocol to communicate the

SIBs and the KPs.

SOFIA2 supports SSAP-XML and SSAP-JSON. We strongly suggest you to use SSAP-JSON

because, as it is based on JSON, is more suitable for IoT communication (With mobile devices,

browsers, etc).

The SSAP messages are:

4.1 JOIN

Message sent by a KP to the SIB to request the beginning of a session

It is a synchronous message. The SIB will return either:

o SessionKey if the authentication is successful.

o Authentication Error if the authentication fails.

4.1.1 Request:

{

"body": "{

\"token\":\"abcd0123def04569adecb\",

\"instance\":\"kpName:kpInstance\”

}",

"direction":"REQUEST",

"messageId":null,

"messageType":"JOIN",

"ontology":null,

"sessionKey":null

}

4.1.2 Response:

{

"body":"{

\"data\":\"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa\",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

Page 23: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 23/98

"messageId":null,

"messageType":"JOIN",

"ontology":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.1.3 Response to Incorrect Request:

4.1.3.1 Deactivated Token Example

{

"body": {

"data": null,

"error": "Token is deactivated",

"errorCode": "AUTENTICATION",

"ok": false

},

"direction": "ERROR",

"messageId": null,

"messageType": "JOIN",

"ontology": null,

"sessionKey": null

}

4.1.3.2 Non-existent KP Example

{

"body": {

"data": null,

"error": "KP does not exist",

"errorCode": "AUTENTICATION",

"ok": false

},

"direction": "ERROR",

"messageId": null,

"messageType": "JOIN",

"ontology": null,

"sessionKey": null

}

Page 24: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 24/98

4.1.3.3 Token not belonging to KP Example

{

"body": {

"data": null,

"error": "Token not valid the kp",

"errorCode": "AUTENTICATION",

"ok": false

},

"direction": "ERROR",

"messageId": null,

"messageType": "JOIN",

"ontology": null,

"sessionKey": null

}

4.1.3.4 Non-Existent Token Example

{

"body": {

"data": null,

"error": "Token does not exist",

"errorCode": "AUTENTICATION",

"ok": false

},

"direction": "ERROR",

"messageId": null,

"messageType": "JOIN",

"ontology": null,

"sessionKey": null

}

4.1.3.5 Non-Existent SessionKey

{

"body": {

"data": null,

"error": "Cannot renovate the sessionkey, the user is not

logged in the SIB",

"errorCode": "AUTHORIZATION",

"ok": false

Page 25: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 25/98

},

"direction": "ERROR",

"messageId": null,

"messageType": "JOIN",

"ontology": null,

"sessionKey": null

}

4.2 LEAVE

Message sent by a KP to the SIB to close the session.

It is a synchronous message.

4.2.1 Request:

{

"body":null,

"direction":"REQUEST",

"messageId":null,

"messageType":"LEAVE",

"ontology":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.2.2 Response:

{

"body":"{

\"data\":\"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa \",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":null,

"messageType":"LEAVE",

"ontology":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

Page 26: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 26/98

4.3 QUERY

Message sent by a KP to the SIB to perform a query on the SIB’s RTDB information.

It is a synchronous message. The SIB returns the query data.

A QUERY message’s type can be Native, SQL-Like or SIB-DEFINED.

4.3.1 Native Query

We understand that a Query is Native-type when the query is solved by the underlying RTDB

engine, which in the reference implementation is MongoDB.

The queries to MongoDB have a specific structure: They start with the string “db”, followed by

the character “.”, followed by the “collection name” (on which the data query is wanted), followed

again by the character “.”, followed by the method’s name (“find”, “aggregate”), and then, in

parenthesis, the conditions that must be fulfilled (combination of fields and operators).

The conditions tend to go within the parenthesis, grouped by {braces}. An example would be:

({measurement: 4}) meaning that the query looks for the records where the field measurement

equals 4. You can add more methods after the parenthesis following the same structure.

db.[collection].[method]([operators])

An example of MongoDB sentence:

db.TemperatureSensor.find({“TemperatureSensor.measurement:{$gt:25}}).limit(3

);

You can use the following sentence to ask for the number of elements in a collection (ontology):

db.TemperatureSensor.count()

You can use this other one to query the number of elements that fulfil a condition in a collection

(ontology):

db.TemperatureSensor.count({“identifier”: “STA-3231-1”})

MongoDB has an exhaustive guide that you can consult to see how to write queries, how to use

operators, what methods are available for MongoDB, etc.

Operators to launch queries: http://docs.mongodb.org/manual/reference/operator/

Collections of methods: http://docs.mongodb.org/manual/reference/method/js-collection/

4.3.1.1 Request:

{

Page 27: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 27/98

"body":"{

\"query\":\"{

TemperatureSensor.identifier:'**-TA3231-1'}\"

}",

"direction":"REQUEST",

"ontology":"TemperatureSensor",

"messageType":"QUERY",

"messageId":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.3.1.2 Response:

{

"body":"{

\"data\":\"\"[

{ \"_id\" : {\"$oid\" : \"510f86598dfe0dd9595f2e15\"} ,

\"TemperatureSensor\" : {

\"GpsCoordinate\" : {

\"heigth\" : 0.0 ,

\"latitude\" : 40.51083 ,

\"longitude\" : -3.669006} ,

\"identifier\" : \" TA3231-1'\",

\"measurement\" : 23 ,

\"unit\" : 1359971931226 ,

\"unidad\" : \"C\"}}

]\",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":null,

"messageType":"QUERY",

"ontology":"TemperatureSensor",

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

Page 28: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 28/98

4.3.2 SQL-Like-type Query

In this case, SOFIA translates the SQL query to the underlying query language, which is

MongoDB in the reference implementation.

SOFIA allows you to use a simple, more known language to perform queries on the RTDB, not

needing you to previously subscribe to data collections.

When queries are launched on an ontology, you must consider that the data will have been

saved as “documents” and, as such, when you want to ask for a specific attribute in an ontology,

you must specify it with the following syntax: [ontology].[attribute]. E.g.:

TemperatureSensor.measurement.

An example of SQL-Like sentence would be:

select * from TemperatureSensor where TemperatureSensor.measurement = 25

Being its MongoDB equivalent:

db.TemperatureSensor.find({TemperatureSensor.measurement:25});

Expressions:

SELECT

FROM

WHERE

ORDER BY

GROUP BY

COUNT

LIMIT

HAVING

ASC

DESC

AS

Relational Operators:

>

<

Page 29: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 29/98

=

>=

<=

!=

Logical Operators:

||

&&

OR

NOT

AND

Other Operators:

+

MAX

MIN

SUM

AVG

Mapping SQL expressions to MongoDB (Example):

SQL-Like MongoDB Language

select * from mysensor; db.mysensor.find();

select id,sensor_id, status from mysensor; db.mysensor.find({},{“sensor_id”:1,”status”:1,

_id:0});

select * from mysensor where status =

“ON”;

db.mysensor.find({“status”:”ON”});

select * from mysensor where status =

“ON” and value=50;

db.mysensor.find({“status”:”ON”},{“value”:50});

select * from mysensor where status =

“ON” order by sensor_id ASC;

db.mysensor.find({ “status”: "ON" } ).sort( { sensor_id: 1 } )

Page 30: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 30/98

select count(*) from mysensor; db.mysensor.count();

select count(*) from mysensor where

value >30

db.mysensor.count({“value”:{$gt:30}})

select from mysensor limit 1 db.mysensor.find().limit(1)

4.3.2.1 Request:

{

"body":"{

\"query\":\"{

Select * from TemperatureSensor where identifier = '**-TA3231-1'}\"

}",

"direction":"REQUEST",

"ontology":"TemperatureSensor",

"messageType":"QUERY",

"messageId":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.3.2.2 Response:

{

"body":"{

\"data\":\"\"[

{ \"_id\" : {\"$oid\" : \"510f86598dfe0dd9595f2e15\"} ,

\"TemperatureSensor\" : {

\"GpsCoordinate\" : {

\"altitude\" : 0.0 ,

\"latitude\" : 40.51083 ,

\"longitude\" : -3.669006} ,

\"identifier\" : \" TA3231-1'\",

\"measurement\" : 23 ,

\"timestamp\" : 1359971931226 ,

\"unit\" : \"C\"}}

]\",

\"error\":null,

\"ok\":true

}",

Page 31: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 31/98

"direction":"RESPONSE",

"messageId":null,

"messageType":"QUERY",

"ontology":"TemperatureSensor",

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.3.3 SIB-DEFINED-type Query

This query type allows you to launch queries to RTDB sending, instead of the query, the query’s

identifier as defined in the SIB. The persistence engine will recover the query from the

database, from the given query identifier, and then re-take the information.

SOFIA allows you to use a visual editor to manage pre-defined queries (e.g., define, modify,

delete and run queries). The pre-defined queries will be either SQL-Like or Native, and they will

be stored in the database.

This is an on-demand RTDB query type that does not require previous subscription.

The system allows you to define parameters in predefined queries. The way to define

parameters is using the character “#” followed by the name of the parameter, for example

#PARAM1. Please see some examples of queries with parameters:

select * from TemperatureSensor where humidity = #PARAMHUM

db.TemperatureSensor.find({humidity d:#PARAMHUM})

The parameters will be provided in SSAP messages sent by the KPs as key-value pairs (this is

to say, parameter and parameter value). The SIB will build the complete query by adding the

parameters in the message.

4.3.3.1 A Request without Parameters:

{

"body":"{

\"query\":\"{

selectAll }",

"direction":"REQUEST",

"ontology":"TemperatureSensor",

"messageType":"QUERY",

"messageId":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

Page 32: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 32/98

}

4.3.3.2 A Response without Parameters:

{

"body":"{

\"data\":\"\"[

{ \"_id\" : {\"$oid\" : \"510f86598dfe0dd9595f2e15\"} ,

\"TemperatureSensor\" : {

\"GpsCoordinate\" : {

\"altitude\" : 0.0 ,

\"latitude\" : 40.51083 ,

\"longitude\" : -3.669006} ,

\"identifier\" : \" TA3231-1'\",

\"measurement\" : 23 ,

\"timestamp\" : 1359971931226 ,

\"unit\" : \"C\"}}

]\",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":null,

"messageType":"QUERY",

"ontology":"TemperatureSensor",

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.3.3.3 Request with Parameters:

{

"body":"{

\"query\":\"{

selectAll }",

\”queryParams\”:\”{\"PARAM1\":\"ST-TA3231-1\"}”,

"direction":"REQUEST",

"ontology": null,

Page 33: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 33/98

"messageType":"QUERY",

"messageId":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

The predefined query that the SSAP message refers to must have been previously defined. It

will be:

select * from TemperatureSensor where identifier = #PARAM1

4.3.3.4 Response with Parameters:

{

"body":"{

\"data\":\"\"[

{ \"_id\" : {\"$oid\" : \"510f86598dfe0dd9595f2e15\"} ,

\"TemperatureSensor\" : {

\"GpsCoordinate\" : {

\"altitude\" : 0.0 ,

\"latitude\" : 40.51083 ,

\"longitude\" : -3.669006} ,

\"identifier\" : \" ST-TA3231-1 \",

\"measurement\" : 23 ,

\"timestamp\" : 1359971931226 ,

\"unit\" : \"C\"}}

]\",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":null,

"messageType":"QUERY",

"ontology":"TemperatureSensor",

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.3.4 BDH-type Query

This query type allows you to operate with HDB.

Page 34: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 34/98

It is remarkable that data are transferred automatically from RTDB to HDB when the real period

of time has passed for each ontology. In this sense, ontology’s data are mapped to a table with

the same name that the ontology at the HDB.

HDB allows two native operations through sending a QUERY message to HDB in SQL:

SELECT and INSERT. Both operations can be requested from a QUERY message with

queryType HDB.

SELECT: allows to consult data from HDB through a SQL sentence.

The SELECT sentence allows to retrieve data from one or more tables and produce a

consistent result for sets of rows and columns.

The HDB engine is based on Impala that supports for the SELECT statement:

o Clause DISTINCT.

o Subqueries at FROM block.

o Clauses WHERE, GROUP BY, HAVING

o Clause ORDER BY

o Clause LIMIT

o Clause JOIN

o Clause UNION ALL

o Clause OFFSET

o Clause UNION

o Relational Operators (>, <, =)

o Arithmetic Operators (+, -)

o Logic Operators (AND, OR, NOT)

o Aggregate Functions (COUNT, SUM, CAST, LIKE, IN, BETWEEN, COALESCE).

Complete content at http://www.cloudera.com/content/cloudera-content/cloudera-

docs/Impala/latest/Installing-and-Using-

Impala/ciiu_langref_sql.html?scroll=select_unique_1

NOTE: Given the large amount of data at HDB, a SELECT query for the BDH should

always have the LIMIT clause, being limited by the SIB in case it has not include the

clause.

A SSAP QUERY HDB-type for a SELECT must inform at SSAP REQUEST message the

following data in the body field:

Page 35: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 35/98

o query: SQL sentence sent to HDB engine.

o queryType: listed BDH

Featured as follows:

{ "body":{

"query":"

select * from SensorTemperatura where identificador = '**-

TA3231-1'",

"queryType":"BDH"},

"direction":"REQUEST",

"ontology":"SensorTemperatura",

"messageType":"QUERY",

"messageId":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

The response is a SSAP message including the table with the sentence results at the

data attribute.

The results table is represented by a JSON object that includes an array with

metainformation of the columns and the matrix with the results.

The form of this object is:

{ "columns": [ {"name":"id","type":"VARCHAR","index":1}, {"name":"timestamp_","type":"INTEGER","index":2}, {"name":"mensajealarma","type":"VARCHAR","index":3}, {"name":"mensajeexcepcion","type":"VARCHAR","index":5}, {"name":"causa","type":"VARCHAR","index":6}, {"name":"contextdata__session_key","type":"VARCHAR","index":7}, {"name":"contextdata__user_id","type":"VARCHAR","index":8}, {"name":"contextdata__kp_id","type":"VARCHAR","index":9}, {"name":"contextdata__kp_identificador","type":"VARCHAR","index":10}, {"name":"contextdata__timestamp_","type":"VARCHAR","index":11} ],

"values": [ ["ObjectID(52fa4787fee7acf12f75a893)",null,"","3.0","69.0","\"KPproductorHT01\"","1391976200443.0"], ["ObjectID(52fa530375926e9d0a8d4a66)",null,"","","",""," ","3.0","69.0","\"KPproductorHT01\"","1391976200441.0"], ["ObjectID(52fa53e475926e9d0a8d4a67)",null,"","","",""," ","3.0","69.0","\"KPproductorHT01\"","1391976200431.0"], ·········

] }

INSERT: allows to insert data at HDB through a SQL INSERT sentence.

The INSERT sentence supports:

o INSERT INTO

o INSERT OVERWRITE

Page 36: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 36/98

o Use SELECT to retrieve data from other table.

Complete content at http://www.cloudera.com/content/cloudera-content/cloudera-

docs/Impala/latest/Installing-and-Using-

Impala/ciiu_langref_sql.html?scroll=insert_unique_1

A SSAP QUERY BDH-type, in order to perfom an INSERT, should inform at the SSAP

REQUEST message the following data at body field:

o query: SQL sentence sent to the BDH engine

o queryType: listed BDH

Featured as follows:

{

"body":{

"query":"

insert into SensorTemperatura(id, identificador, medida) values (1, ‘ST-

TA23’, 23)",

"queryType":"BDH"

},

"direction":"REQUEST",

"ontology":"SensorTemperatura",

"messageType":"QUERY",

"messageId":null,

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

The answer is a SSAP message including the table with the number of affected records

at the data attribute.

4.4 INSERT

Message sent by a KP to the SIB to insert information in RTDB.

It is an asynchronous message, in which the SIB responds with the Object ID inserted.

4.4.1 Request:

{

"body": {

Page 37: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 37/98

"query": "{insert into Jardin (timestamp,assetId,parcela,humedad)

values (125896,'1',45,78.9)}",

"queryType": "SQLLIKE",

"queryParams": null

},

"direction": "REQUEST",

"ontology": "Jardin",

"messageType": "INSERT",

"messageId": null,

"sessionKey": "ff5b6c48-4cc3-4ce3-a30f-6bf8e18dc340"

}

4.4.2 Response:

{

"body":{

"data":{

"_id":ObjectId("53591d96def7260a09e96708")

},

"error":null,

"errorCode":null,

"ok":true

},

"direction":"RESPONSE",

"messageId":null,

"messageType":"INSERT",

"ontology":"Jardin",

"sessionKey":"ff5b6c48-4cc3-4ce3-a30f-6bf8e18dc340"

}

4.5 UPDATE

Message sent by a KP to the SIB to update information belonging to RTDB.

Response is synchronous, in which the SIB responds with the updated Object ID.

4.5.1 Request:

{ "body": {

Page 38: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 38/98

"query": "{update Jardin set Jardin.humedad = 100.0 where

Jardin.parcela = 45}",

"queryType": "SQLLIKE",

"queryParams": null

},

"direction": "REQUEST",

"ontology": "Jardin",

"messageType": "UPDATE",

"messageId": null,

"sessionKey": "59ff077c-d8a4-4cb8-be03-ebbcad32dec5"

}

4.5.2 Response:

{

"body":{

"data":{

"_ids":[{"_id":ObjectId("53591d96def7260a09e96708")}]

},

"error":null,

"errorCode":null,

"ok":true

},

"direction":"RESPONSE",

"messageId":null,

"messageType":"UPDATE",

"ontology":"Jardin",

"sessionKey":"59ff077c-d8a4-4cb8-be03-ebbcad32dec5"

}

4.6 DELETE

Message sent by a KP to the SIB to delete information belonging to RTDB.

Response is synchronous, in which the SIB responds with the deleted Object ID.

4.6.1 Request:

{

"body": {

"query": "{delete from Jardin where Jardin.parcela = 45}",

Page 39: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 39/98

"queryType": "SQLLIKE",

"queryParams": null

},

"direction": "REQUEST",

"ontology": "Jardin",

"messageType": "DELETE",

"messageId": null,

"sessionKey": "59ff077c-d8a4-4cb8-be03-ebbcad32dec5"

}

4.6.2 Response:

{

"body":{

"data":{

"_ids":[{"_id":ObjectId("53591d96def7260a09e96708")}]

},

"error":null,

"errorCode":null,

"ok":true

},

"direction":"RESPONSE",

"messageId":null,

"messageType":"DELETE",

"ontology":"Jardin",

"sessionKey":"59ff077c-d8a4-4cb8-be03-ebbcad32dec5"

}

4.7 SUBSCRIBE

Message sent by a KP to the SIB to subscribe to a given condition to be produced in the SIB’s RTDB. Refresh time can be specified.

Response is synchronous, specifying whether the SIB accepts the subscription or not.

4.7.1 Request:

{

"body":"{

Page 40: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 40/98

\"msRefresh\":10000,

\"query\":\"{TemperatureSensor.medida:{$gt:1}}\"

}",

"direction":"REQUEST",

"messageId":"c260fbd6-ce7e-4f1d-983d-0152b419223c",

"messageType":"SUBSCRIBE",

"ontology":"TemperatureSensor",

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.7.2 Response:

{

"body":"{

\"data\":\"d43a929d-4883-4640-8f73-1337c518bd17\",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":"c260fbd6-ce7e-4f1d-983d-0152b419223c",

"messageType":"SUBSCRIBE",

"ontology":"TemperatureSensor",

"sessionKey":"5b9349ab-d9a8-4fd0-b155-a11c5d8df6fa"

}

4.8 UNSUBSCRIBE

Message sent by a KP to the SIB to cancel a previously-made subscription.

This message is synchronous

4.8.1 Request:

{

"body":"{

\"idSuscripcion\":\"cef33c81-970f-4e9c-9203-6c87e25ca37c\"

}",

"direction":"REQUEST",

"messageId":null,

"messageType":"UNSUBSCRIBE",

Page 41: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 41/98

"ontology":" EnergyMeter ",

"sessionKey":"5230064e-f4f7-41ab-b6de-7ef7ad11668f"

}

4.8.2 Response:

{

"body":"{

\"data\":\"\",

\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":null,

"messageType":"UNSUBSCRIBE",

"ontology":"EnergyMeter",

"sessionKey":"5230064e-f4f7-41ab-b6de-7ef7ad11668f"

}

4.9 INDICATION

Message used by the SIB to notify any subscribed KP.

It is an asynchronous message: It is launched whenever the condition inserted by the KP is true.

4.9.1 Response

{

"body":"{

\"data\":\"[ {

\"_id\" : { \\\"$oid\\\" : \\\"511397883006732cf413d47b\\\"} , \"TemperatureSensor\" :

{

\"GpsCoordinate\" : {

\"altitude\" : 0.0 ,

\"latitude\" : 40.508416 ,

\"longitude\" : -3.669918

} ,

\"identifier\" : \"S_Temperature_00001\" ,

Page 42: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 42/98

\"measurement\" : 17 ,

\"timestamp\" : 1360238472000 ,

\"unit\" : \"C\"

}

}]\"

,\"error\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":"d1bc4fe5-54c3-4add-abb4-3108201e761f",

"messageType":"INDICATION",

"ontology":null,

"sessionKey":null

}

4.10 CONFIG

Message sent by a KP to the SIB to obtain the software configuration of its applications.

This message is synchronous.

Operation only available for JAVA KPs.

4.10.1 Request:

{

"body":"{

"instanciaKp":"KPvisualizacionHT01",

"kp":"KPvisualizacionHT",

"token":"cbb9364c434543a18dc6efa30dc780eb"

}",

"direction":"REQUEST",

"messageId":null,

"messageType":"CONFIG",

"ontology":null,

"sessionKey":null

}

4.10.2 Response:

{

Page 43: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 43/98

"body":"{

\"instanciaKp\":\"KPpubliAnuncios:KPpubliAnuncios01\",

\"kp\":\"KPpubliAnuncios\",

\"lappsw\":[{\"identificacion\":\"app1\",\"propiedadescfg\":{\"\\\"puerto\\\"\":\"\\\"808

0\\\"\",\"\\\"host\\\"\":\"\\\"localhost\\\"\"},\"url\":\"file:///Volumes/DATOS/app1.war\",\"versio

ncfg\":1,\"versionsw\":1}],

\"lasset\":[],

\"lmisc\":[],

\"lontologia\":[{\"esquemajson\":\"{ \\\"$schema\\\": \\\"http://json-

schema.org/draft-03/schema#\\\", \\\"title\\\": \\\"Anuncios Schema\\\", \\\"type\\\":

\\\"object\\\", \\\"properties\\\": { \\\"_id\\\": { \\\"type\\\": \\\"object\\\",

\\\"$ref\\\": \\\"#/titulo\\\" }, \\\"SensorAnuncio\\\": { \\\"type\\\": \\\"string\\\",

\\\"$ref\\\": \\\"#/datos\\\" } }, \\\"titulo\\\": { \\\"title\\\": \\\"id\\\",

\\\"description\\\": \\\"Titulo insertado del Anuncio\\\", \\\"type\\\": \\\"object\\\",

\\\"properties\\\": { \\\"$oid\\\": { \\\"type\\\": \\\"string\\\",

\\\"required\\\": false } } }, \\\"datos\\\": { \\\"title\\\": \\\"datos\\\",

\\\"description\\\": \\\"Info contenido\\\", \\\"type\\\": \\\"object\\\", \\\"properties\\\":

{ \\\"titulo\\\": { \\\"type\\\": \\\"string\\\", \\\"required\\\": true

}, \\\"timestamp\\\": { \\\"type\\\": \\\"integer\\\", \\\"minimum\\\":

0, \\\"required\\\": true }, \\\"contenido\\\": { \\\"type\\\":

\\\"string\\\", \\\"required\\\": true } } }, \\\"additionalItems\\\":

false}\",\"identificacion\":\"Anuncios\",\"tipopermiso\":\"QUERY\"}],

\"token\":\"d9e77d01d3c84f96994bfdcd428faa97\" }",

"direction":"RESPONSE",

"messageId":null,

"messageType":"CONFIG",

"ontology":null,

"sessionKey":null

}

4.11 BULK

Message sent by a KP to SIB that groups multiple messages of the type INSERT,

UPDATE, and DELETE.

The message will be broken down in the SIB, which will process the messages

individually just as if they had been sent on an individual basis

It is a synchronous message in which the SIB responds with an abstract containing:

Page 44: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 44/98

o Correct Operations: The ID of the inserted, modified, deleted objects

o Erroneous operations: The erroneous message with the error description

4.11.1 Request

{

"body":"[

{\"body\":\"<INSERT_MESSAGE1_BODY>\", \"ontology\":\"TestSensorTemperatura\",

\"type\":\"INSERT\"},

{\"body\":\"<INSERT_MESSAGE2_BODY>\", \"ontology\":\"TestSensorTemperatura\",

\"type\":\"INSERT\"},

{\"body\":\"<UPDATE_MESSAGE1_BODY>\", \"ontology\":\"TestSensorTemperatura\",

\"type\":\"UPDATE\"},

{\"body\":\"<UPDATE_MESSAGE2_BODY>\", \"ontology\":\"TestSensorTemperatura\",

\"type\":\"UPDATE\"}

]",

"direction":"REQUEST",

"messageId":null,

"messageType":"BULK",

"ontology":null,

"sessionKey":"<SESSION_KEY>"

}

4.11.2 Response

{

"body":"{

\"data\":\"{

\\\"deleteSummary\\\":null,

\\\"insertSummary\\\":{

\\\"errors\\\":[],

\\\"objectIds\\\":[···········]

},

\\\"updateSummary\\\":{

\\\"errors\\\":[],

\\\"objectIds\\\":[···········]

}

Page 45: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 45/98

}\",

\"error\":null,

\"errorCode\":null,

\"ok\":true

}",

"direction":"RESPONSE",

"messageId":null,

"messageType":"BULK",

"ontology":null,

"sessionKey":"<SESSION_KEY>"

}

Page 46: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 46/98

5 JAVA API

5.1 Introduction

SOFIA2 provides a Java API to develop KPs. This API is made of a set of JAVA classes and

interfaces that ease the generation and maintenance of SSAP message, as well as the

connection with the Platform using connectors that communicate with the Platform’s gateways.

5.2 Maven Dependency

SOFIA2’s SDK provides a Maven repository including the Java API library. The Maven

dependency that must be included in a KP’s pom.xml to import SOFIA2’s Java API is:

<dependency>

<groupId>com.indra.jee.arq.spring.sofia2</groupId>

<artifactId>kp-core</artifactId>

<version>1.0.0</version>

</dependency>

5.3 KP Interface

It provides the methods to connect to the Platform and Exchange SSAP messages.

This interface is implemented by several classes. Each class represents a specific protocol

connector (MQTT, HTTP).

It eases the KP’s migration to new protocols that may be defined in the future, by abstracting the

connection mode and the sending/reception of SSAP message from the used protocol.

The interface has this appearance:

public interface Kp { boolean isConnected();

String getSessionKey(); void connect() throws ConnectionToSibException; void disconnect();

void setConnectionConfig(ConnectionConfig config); void setXxteaCipherKey(String cipherKey); SSAPMessage send(SSAPMessage msg) throws ConnectionToSibException; SSAPMessage sendCipher(SSAPMessage msg) throws ConnectionToSibException; void addListener4SIBNotifications(Listener4SIBIndicationNotifications listener); void removeListener4SIBNotifications(Listener4SIBIndicationNotifications listener);

}

In the implementation, Java applications can use these operations to obtain the following effects:

Page 47: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 47/98

boolean isConnected(): Knows whether the KP is connected to a SIB or not.

String getSessionKey(): Once connected to the SIB, recovers the sessionKey

assigned for the connection.

void connect(): Creates a physical connection with the SIB through the Gateway of

the protocol that the class implements. The physical connection makes sense only for the MQTT connector.

void disconnect(): Closes the physical connection with the SIB that was established

with connect().

void setConnectionConfig(ConnectionConfig config): Configures parameters

to connect to the SIB. The parameter ConnectionConfig includes the configuration parameters to connect with the SIB’s Gateway and reports them to the KP.

void setXxteaCipherKey(String cipherKey): Establishes the XXTEA cipher

algorithm key to cipher the SSAP message Exchange. Allows associating the cipher key generated in the Web Console to the KP. Is informed in the KP’s creation as explained in point 10.1 Create a New KP of Web Console Use Guide.

SSAPMessage send(SSAPMessage msg): Sends a SSAP message to the SIB and

receives the SSAP response message.

SSAPMessage sendCipher(SSAPMessage msg): Sends a SSAP message to the SIB

and receives the SSAP response message. This communication is cipher using the XXTEA algorithm.

void addListener4SIBNotifications(Listener4SIBIndicationNotifications listener): Adds a listener to get subscription message notifications. A listener is a

class implementing the interface Listener4SIBIndicationNotifications. To implement this interface, you must implement the method onIndication, which receives the SSAP INDICATION message with subscription notification data as a parameter.

void removeListener4SIBNotifications(Listener4SIBIndicationNotifications listener): Deletes one listener, so as to stop receiving subscription message

notifications.

5.4 Protocol Connectors in the API

The communication protocols that the Java API provides are:

5.4.1 MQTT

The KP’s interface implementation for the MQTT protocol is the class KpMQTTClient.

It connects with the SIB’s MQTT Gateway.

This class receives its MQTT configuration through an instance of the class

MQTTConnectionConfig, where the following is informed:

Host: Machine where the SIB’s MQTT Gateway listens

Port: Port where the SIB’s MQTT Gateway listens

Page 48: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 48/98

Quality Of Service: How many instances of the SIB must receive the message?

Timeout: Connection timeout to the SIB’s MQTT Gateway.

MQTTConnectionConfig config = new MQTTConnectionConfig(); config.setHostSIB(host); config.setPortSIB(port); config.setQualityOfService(QoS.AT_LEAST_ONCE); config.setTimeOutConnectionSIB(5000); //We create the KP’s instance by providing the connection configuration Kp kp=new KpMQTTClient(config);

Once instantiated, the behaviour is as described in the interface.

5.4.2 RESTFul

The Java API RESTFul differs from the other APIs because of the intrinsic characteristics of the

RESTFul specification and the need to manage resources through the HTTP verbs. In this

direction, this API does not use the standard SSAP protocol but manages an object or resource

named SSAPResource via HTTP operations: POST, PUT, GET, and DELETE.

In the Java API, the resource SSAPResource is represented by the class SSAPResource that

has the following properties:

Page 49: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 49/98

While the Gateway interface with HTTP operations GET, POST, PUT, DELETE is provided by

the class SSAPResourceAPI with the methods:

insert(ssap:SSAPResource): Response

update(ssap:SSAPResource): Response

query($sessionkey:String, $ontology:String, $query:String, $queryArg:String,

$queryType:String):Response

query($oid:String, $sessionKey:String, $ontology:String):Response

delete(ssap:SSAPResource):Response

deleteOid($oid:String, $sessionKey:String, $ontology:String):Response

getConfig($kp:String, $instanciakp:String, $token:String):Response

Thereby covering the operations SSAP as follows:

SSAP Operation RESTFul Operation through the SSAPResourceAPI

JOIN insert (POST) sending a SSAPResource informing:

join: true

Page 50: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 50/98

instanceKP: Identifier of KP e identifier of the KP instance

token: Authentication Token

LEAVE

insert (POST) sending a SSAPResource informing:

leave: true

sessionkey: Session Key to expire

INSERT

insert (POST) sending a SSAPResource informing:

ontology: Ontology on which we send a new instance.

data: Instance of the Ontology sent.

sessionkey: SSAP key of the session the message belongs to

ó

query (GET) sending a SSAPResource informing through the queryParams of the

URL:

$ontology: Ontology on which we send a new instance.

$query: SQLLIKE Sentence of the type INSERT.

$sessionKey: SSAP key of the session the message belongs to

$queryType: SQLLIKE

UPDATE

update (PUT) sending a SSAPResource informing:

ontology: Ontology on which we are updating.

data: Instance of the ontology with the updated data.

sessionkey: SSAP key of the session the message belongs to

ó

query (GET) informing through the queryParams of the URL:

$ontology: Ontology on which we send a new instance.

$query: SQLLIKE Sentence of the type UPDATE.

$sessionKey: SSAP key of the session the message belongs to

$queryType: SQLLIKE

DELETE

delete (DELETE) sending a SSAPResource informing:

ontology Ontology on which we are deleting.

data: Instance of the ontology to delete.

sessionkey: SSAP key of the session the message belongs to ó

delete (DELETE) informing through the pathParam: the objectId in RTDB of the

ontology instance to delete. And through the queryParams of the URL:

$ontology: Ontology on which we want to delete.

$sessionKey: SSAP key of the session the message belongs to ó

query (GET) informing through the queryParams of the URL:

$ontology: Ontology on which we want to delete.

$query: SQLLIKE Sentence of the type DELETE.

$sessionKey: SSAP key of the session the message belongs to

$queryType: SQLLIKE

Page 51: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 51/98

QUERY

query (GET) informing through the queryParams of the URL:

$ontology: Ontology on which we query.

$query: Query Sentence

$sessionKey: SSAP key of the session the message belongs to

$queryType: Type of language of the query

$queryParams: Parametres to inform the query case predefined in the SIB with arguments.

ó

query (GET) informing through the pathParam: the objectId in RTDB of the instance of

ontology to query. And through the queryParams of the URL:

$ontology: Ontology on we query.

$sessionKey: SSAP key of the session the message belongs to

GET_CONFIG

getConfig (GET) informing through the queryParams in the URL:

$kp: Identifier of the KP from which we want to recover ithe configuration

$instanciaKp: Identifier of the instance of KP from which we want to recover the configuration

$token:Authentication Token

All operations return an object of type RESPONSE, which can be mapped to a SSAPResource

object with the response to the SIB using the method of the class SSAPResourceAPI:

responseAsSsap(resp:Response):SSAPResource

The SSAPResourceAPI constructor receives as arguments the endpoint url of the RESTFul

Gateway of Sofia2 on which the operations are carried out.

Use example:

SSAPResourceAPI api = new SSAPResourceAPI("http://sofia2.com/sib/services/api_ssap/");

//Genera un recurso SSAP con un JOIN SSAPResource ssapJoin=new SSAPResource(); ssapJoin.setJoin(true); ssapJoin.setInstanceKP(KP_INSTANCE); ssapJoin.setToken(TOKEN);

//Hace un POST del recurso, equivalente a una petici�n SSAP JOIN Response respJoin=this.api.insert(ssapJoin); String sessionkey=null; log.info("Codigo http retorno JOIN: "+respJoin.getStatus()); try{ sessionkey=this.api.responseAsSsap(respJoin).getSessionKey(); log.info("Sessionkey:"+sessionkey); assertEquals(respJoin.getStatus(), 200);

Page 52: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 52/98

}catch(ResponseMapperException e){ log.error(e.getMessage()); assertEquals(false, true); } if(sessionkey!=null){ //Genera un recurso SSAP con un LEAVE SSAPResource ssapLeave=new SSAPResource(); ssapLeave.setLeave(true); ssapLeave.setSessionKey(sessionkey); Response respLeave=this.api.insert(ssapLeave); log.info("Codigo http retorno LEAVE: "+respLeave.getStatus()); assertEquals(respLeave.getStatus(), 200); }

5.4.3 Websocket

The implementation of the Kp interface for the Websocket protocol is the class

KpWebSocketClient.

It connects with the WebSocket Gateway of the SIB.

This class receives its configuration through an instance of the class

WebSocketConnectionConfig, which reports:

endPointUri: URL where the WebSocket Gateway of the SIB hears.

method: HTTP Method used by the WebSocket Gateway of the SIB (default sofia2.com

GET).

timeOutConnectionSIB: Timeout to receive the response from the SIB

WebSocketConnectionConfig config=new WebSocketConnectionConfig(); config.setEndpointUri("http://sofia2.com/sib/api_websocket"); config.setMethod(METHOD.GET); config.setTimeOutConnectionSIB(5000); KpWebSocketClient kp=new KpWebSocketClient(config);

Once instanced the operation it is the one described in the interface.

Page 53: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 53/98

5.4.4 Extension with new protocols

As explained in the Guide to Configure, Extend and Customize SIB, you can extend the SIB

to a new communication protocol (Gateway). Once the SIB is extended with the new protocol,

we suggest that, to ease the use of the new protocol in the Java API, you extend the API to

support the protocol following the philosophy applied to the current protocols. To do so, the

steps to extend the API to a new protocol are:

Create the class that represents the new protocol’s connector’s implementation (the one

you will use to instantiate the KP interface, to send SSAP messages to the SIB).

The source code for the current protocols can be found in the package:

com.indra.sofia2.ssap.kp.implementations.

This class must implement the abstract class KpToExtend, which in turn implements the

interface KP:

The previous diagram shows only the API’s most important operations. The interface KP

describes all the operations that the API must have, no matter the protocol it uses; the

class KpToExtend groups the attributes and operations which will be shared by all the

implementations, no matter their protocol.

Finally, each specific protocol implementation implements those operations of the KP

interface that are different depending on the transport protocol. Specifically those

operations are:

o connect(): It establishes the physical connection with the SIB’s Gateway,

following the chosen protocol.

Page 54: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 54/98

o disconnect(): It closes the physical connection with the SIB’s Gateway, following

the chosen protocol.

o send(): It sends the SSAP messages to the SIB’s Gateway through the channel

provided by the chosen protocol.

Each protocol will have its own configuration parameters. To cover the configuration of each

protocol, the class ConnectionConfig is provided. This class can be extended to create a new

class covering the new protocol’s configuration properties. The abstract class KpToExtend,

which will implement the new protocol’s implementation, has several attributes including one

which is an instance of ConnectionConfig, and that will receive the builder among its

parameters. Thus, when instantiating each specific protocol, the builder will receive a specific

ConnectionConfig instance, adapted to the protocol and including the connection parameters:

5.5 API Utilities

5.5.1 Class SSAPMessageGenerator

This is a utility class providing a number of operations to allow for the generation of SSAP

messages without having to reach the detail of composing the JSON.

Page 55: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 55/98

generateJoinMessage: It allows you to build the message SSAPMessageJOIN

specifying the user, password and instance.

generateLeaveMessage: It allows you to build the message SSAPMessageLEAVE.

You must specify the sessionKey.

generateInsertMessage: It allows you to build the message SSAPMessageINSERT

specifying the sessionKey, ontology and data to be inserted.

generateUpdateMessage: It allows you to build the message SSAPMessageUPDATE

specifying the sessionKey, ontology, data to update and query.

generateRemoveMessage: It allows you to build the message SSAPMessageREMOVE

specifying the sessionKey, ontology and query.

generateQueryMessage: It allows you to build the message SSAPMessageQUERY

specifying the sessionKey, ontology and query.

generateSubscribeMessage: It allows you to build the message

SSAPMessageSUBSCRIBE specifying the sessionKey, ontology and query.

generateUnsubscribeMessage: It allows you to build the message

SSAPMessageUNSUBSCRIBE specifying the sessionKey, ontology and query.

5.5.2 Binary Support

The Support for Binary data type is supported by structural and utility classes, the methods that

facilitate working with this type of data are exposed in the following.

The classes SSAPBinaryMessage and SSAPBinaryMediaMessage are structural classes that

model the physical structure of the data type Binary. It is important to understand its functioning

although the utility classes abstract the developer from their use.

The builder of the class SSAPBinaryMessage that meets the following contract public

SSAPBinaryMessage(File data, Encoding binaryEncoding, Mime mime) creates an object with

Page 56: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 56/98

the file (data) serialized using the encoding (binaryEncoding) and the mime-type (mime) you

select

The Encoding listed only supports the type of BASE64 and BASE91 data, and will be the way in

which the attached file will be serialized.

NOTE: The encoding that is used to serialize the file must be the same as used to

generate the binary object from its serialized string.

The Mime listed contains a long list of enumerated.

APPLICATION_ATOM ("application/atom+xml"),

APPLICATION_VND ("application/vnd.dart"),

APPLICATION_ECMASCRIPT ("application/ecmascript"),

APPLICATION_EDIX12 ("application/EDI-X12"),

APPLICATION_EDIFACT ("application/EDIFACT"),

APPLICATION_JSON ("application/json"),

APPLICATION_JACASCRIPT("application/javascript"),

APPLICATION_OCTET ("application/octet-stream"),

APPLICATION_OGG ("application/ogg"),

APPLICATION_DASH ("application/dash+xml"),

APPLICATION_PDF ("application/pdf"),

APPLICATION_POSTCRIPT ("application/postscript"),

APPLICATION_RDF ("application/rdf+xml"),

APPLICATION_RSS ("application/rss+xml"),

APPLICATION_SOAP ("application/soap+xml"),

APPLICATION_FONT ("application/font-woff"),

APPLICATION_XHTML ("application/xhtml+xml"),

APPLICATION_XML ("application/xml"),

APPLICATION_XML_DTD ("application/xml-dtd"),

APPLICATION_XOP ("application/xop+xml"),

APPLICATION_ZIP ("application/zip"),

APPLICATION_GZIP ("application/gzip"),

APPLICATION_EXAMPLE ("application/example"),

APPLICATION_X_NACL ("application/x-nacl"),

APPLICATION_X_PNACL ("application/x-pnacl"),

APPLICATION_SMIL ("application/smil+xml"),

APPLICATION_VND_DEBIAN ("application/vnd.debian.binary-package"),

APPLICATION_VND_OASIS_TEXT ("application/vnd.oasis.opendocument.text"),

APPLICATION_VND_OASIS_SPREADSHEET ("application/vnd.oasis.opendocument.spreadsheet"),

APPLICATION_VND_OASIS_PRESENTATION

("application/vnd.oasis.opendocument.presentation"),

APPLICATION_VND_OASIS_GRAPHICS ("application/vnd.oasis.opendocument.graphics"),

APPLICATION_VND_MS_EXCEL ("application/vnd.ms-excel"),

APPLICATION_VND_OPENXMLFORMART_SHEET ("application/vnd.openxmlformats-

officedocument.spreadsheetml.sheet"),

APPLICATION_VND_MS_POWERPOINT ("application/vnd.ms-powerpoint"),

APPLICATION_VND_OPENXMLFORMART_PRESENTATION ("application/vnd.openxmlformats-

officedocument.presentationml.presentation"),

APPLICATION_VND_MOZILLA ("application/vnd.mozilla.xul+xml"),

APPLICATION_VND_GOOGLE_EARTH_XML ("application/vnd.google-earth.kml+xml"),

APPLICATION_VND_GOOGLE_EARTH ("application/vnd.google-earth.kmz"),

Page 57: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 57/98

APPLICATION_VND_ANDROID ("application/vnd.android.package-archive"),

APPLICATION_VND_MS_XPS ("application/vnd.ms-xpsdocument"),

APPLICATION_X_7Z ("application/x-7z-compressed"),

APPLICATION_X_CHROME ("application/x-chrome-extension"),

APPLICATION_X_DVI ("application/x-dvi"),

APPLICATION_X_FONT ("application/x-font-ttf"),

APPLICATION_X_JAVASCRIPT ("application/x-javascript"),

APPLICATION_X_LATEX ("application/x-latex"),

APPLICATION_X_MPEGURL ("application/x-mpegURL"),

APPLICATION_X_RAR ("application/x-rar-compressed"),

APPLICATION_X_SHOCKWAVE ("application/x-shockwave-flash"),

APPLICATION_X_STUFFIT ("application/x-stuffit"),

APPLICATION_X_TAR ("application/x-tar"),

APPLICATION_X_WWW ("application/x-www-form-urlencoded"),

APPLICATION_X_XINSTALL ("application/x-xpinstall"),

APPLICATION_X_ACC ("audio/x-aac"),

APPLICATION_X_CAF ("audio/x-caf"),

APPLICATION_X_XCF ("image/x-xcf"),

APPLICATION_X_RPC ("text/x-gwt-rpc"),

APPLICATION_X_JQUERY ("text/x-jquery-tmpl"),

APPLICATION_X_MARKDOWN ("text/x-markdown"),

APPLICATION_X_PKCS12 ("application/x-pkcs12"),

AUDIO_BASIV ("audio/basic"),

AUDIO_L24 ("audio/L24"),

AUDIO_MP4 ("audio/mp4"),

AUDIO_MPEG ("audio/mpeg"),

AUDIO_OGG ("audio/ogg"),

AUDIO_FLAC ("audio/flac"),

AUDIO_OPUS ("audio/opus"),

AUDIO_VORBIS ("audio/vorbis"),

AUDIO_VND_RN ("audio/vnd.rn-realaudio"),

AUDIO_VND_WAVE ("audio/vnd.wave"),

AUDIO_WEBM ("audio/webm"),

AUDIO_EXAMPLE ("audio/example"),

EXAMPLE ("EXAMPLE"),

IMAGE_GIF ("/gif"),

IMAGE_JPEG ("image/jpeg"),

IMAGE_PJPEG ("image/pjpeg"),

IMAGE_PNG ("image/png"),

IMAGE_SVG ("image/svg+xml"),

IMAGE_TIFF ("image/tiff"),

IMAGE_VND ("image/vnd.djvu"),

IMAGE_EXAMPLE ("image/example"),

MESSAGE_HTTP ("message/http"),

MESSAGE_IMDN ("message/imdn+xml"),

MESSAGE_PARTIAL ("message/partial"),

MESSAGE_RFC822 ("message/rfc822"),

MESSAGE_EXAMPLE ("message/example"),

MODEL_IGES ("model/iges"),

MODEL_MESH ("model/mesh"),

MODEL_VRML ("model/vrml"),

MODEL_X3D_BINARY ("mdel/x3d+binary"),

MODEL_X3D_FASTINFOSET ("model/x3d+fastinfoset"),

MODEL_X3D_VRML ("model/x3d-vrml"),

MODEL_X3D_XML ("model/x3d+xml"),

MODEL_EXAMPLE ("model/example"),

MULTIPART_MIXED ("multipart/mixed"),

MULTIPART_ALTERNATIVE ("multipart/alternative"),

MULTIPART_RELATED ("multipart/related"),

MULTIPART_FORM ("multipart/form-data"),

MULTIPART_SIGNED ("multipart/signed"),

MULTIPART_ENCRYPTED ("multipart/encrypted"),

Page 58: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 58/98

MULTIPART_EXAMPLE ("multipart/example"),

TEXT_CMD ("text/cmd"),

TEXT_CSS ("text/css"),

TEXT_CSV ("text/csv"),

TEXT_EXAMPLE ("text/example"),

TEXT_HTML ("text/html"),

TEXT_PLAIN ("text/plain"),

TEXT_RTF ("text/rtf"),

TEXT_VCARD ("text/vcard"),

TEXT_VND_A ("text/vnd.a"),

TEXT_VND_ABC ("text/vnd.abc"),

TEXT_XML ("text/xml"),

VIDEO_AVI ("video/avi"),

VIDEO_EXAMPLE ("video/example"),

VIDEO_MPEG ("video/mpeg"),

VIDEO_MP4 ("video/mp4"),

VIDEO_OGG ("video/ogg"),

VIDEO_QUICKTIME ("video/quicktime"),

VIDEO_WEBM ("video/webm"),

VIDEO_MATROSKA ("video/x-matroska"),

VIDEO_X_MS ("video/x-ms-wmv"),

VIDEO_X_FLV ("video/x-flv"),

OTHER ("not-defined");

The ontology schema defines what Encodig it supports.

Once we have created the object SSAPBinaryMessage the information retrieval is performed

through the methods

getMedia () Returns the object SSAPBinaryMediaMessage with the meta-information file

name, type of encodig and mime-type associated with the binary.

getBinaryData () Returns a byte [] with the deserialized binary. This method detects the

encoding from its meta-information and uses it to reverse the serialization of the binary data.

{"data":"SERIALIZACION DEL BINARIO OMITIDA"

,"media":{"binaryEncoding":"BASE91","mime":"application/pdf","name":"A

XADOC124013.pdf"}}

The class SSAPMessageGenerator exposes a number of methods that are intersection

between the structure of the Binary data type and the SSAP messages.

The method addBinary (String fieldName, File binary, Mime mime) to add binary files indicating:

The name of the field you want to add the file (This is especially useful in ontologies that

allow more than one binary file)

The binary file

The mime-type of the correspondent file.

Once we have added all the binary that we want to attach to our ontology, the

generateJSONBinary () method returns a String with the different Binary structures in JSON

Page 59: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 59/98

format. This JSON structure can be added the our Data section of our insert SSAP and record

the information in Sofia2.

NOTE: Once we have finished working with binary we must erase the data structure

using the cleanBinary () method.

Once we retrieve the data stored in Sofia2, and we have launched our SSAP Query, we can

rcuperar all binary message containing it.

Through getBinary (String JSON) get a estrcutura Map <String, SSAPBinaryMessage>

containing all the binaries exist in the JSON response. Where the key is the field name and

value the SSAPBinaryMessage with serialized binary structure and meta-information

5.5.3 SSAPMessage and derived classes

They represent the abstraction of JSON SSAP messages to be handled from Java.

SSAPMessage is the class grouping all the properties of any SSAP message, no matter its

type. It is a Java bean with methods get() and set() for all the properties, plus methods toJson()

and fromJson() to translate to and from JSON:

The properties direction and messageType represent the direction and type of SSAP

message, respectively:

SSAPMessageDirection: A list with the values REQUEST, RESPONSE, ERROR.

SSAPMessageTypes: A list with the values JOIN, INSERT, UPDATE, DELETE,

QUERY, LEAVE, SUBSCRIBE, UNSUBSCRIBE.

The property body represents an SSAP message’s body. It is a String including the JSON with

the properties of whatever message it deals with. The way to handle the attribute body changes

Page 60: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 60/98

depending on the message type, because each type has its own properties. To do so, we have

the following classes:

SSAPBodyJoinUserPasswordMessage: Body of JOIN message with user/password

authentication.

SSAPBodyJoinTokenMessage: Body of JOIN message with token-based

authentication.

SSAPBodyLeaveMessage: Body of LEAVE message.

SSAPBodyOperationMessage: Body of INSERT, UPDATE and REMOVE message.

SSAPBodyQueryMessage: Body of QUERY message.

SSAPBodyQueryWithParamMessage: Body of QUERY message that includes a Map

with the paremeters to send a predefined query.

SSAPBodySubscribeMessage: Body of SUBSCRIBE message.

SSAPBodyUnsubscribeMessage: Body of UNSUBSCRIBE message.

SSAPBodyReturnMessage: Body of return-from-the-SIB message.

All these JavaBean classes have toJson() and fromJson() methods to translate to and from

JSON.

The way to create messages using the traditional utility is as follows:

// We create the SSAP JOIN message to connect with the SIB SSAPMessage msg = this.ssapMessageGenerator.generateJoinMessage( username, password, instance); // We send the SSAP JOIN SSAPMessage retorno = kp.send(msg); //We check the SIB’s response if (retorno == null)

throw new ExcepcionGateway("Cannot connect to the SIB"); //We translate the JSON message to the Object. SSAPBodyReturnMessage retornoBody =

SSAPBodyReturnMessage.fromJsonToSSAPBodyReturnMessage(retorno.getBody());

5.5.4 SSAPBulkMessage and derived classes

This is the class used in the Java API to build SSAP BULK type messages. It is a class derived

from SSAPMessage, it inherits all the attributes and adds methods to facilitate the construction

of a SSAP message of BULK type from SSAP messages of the type INSERT, UPDATE, and

DELETE. These methods are:

Page 61: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 61/98

addMessage(ssapMessage: SSAPMessage):SSAPBulkMessage: Adds to the

attribute "body" of the SSAPBulkMessage message, the INSERT, UPDATE, or

DELETE message indicated by parameters.

Returns the object SSAPBulkMessage itself to facilitate the linking of topics:

msgBulk.addMessage(msgInsert1).addMessage(msgInsert2).addMessage(msgInsert3);

In case the message added is not type INSERT, UPDATE, or DELETE, the

method will throw an exception of the type

NotSupportedMessageTypeExepcion.

addMessage(ssapMessages: List<SSAPMessage>):void: Adds to the

attribute "body" of the message SSAPBulkMessage a list of INSERT, UPDATE,

or DELETE messages indicated by parameters.

In case any one of the added messages is not a type INSERT, UPDATE, or

DELETE, the method will throw an exception of the type

NotSupportedMessageTypeExepcion.

5.6 Use Example

You want to create a KP that uses the MQTT protocol. You define the physical connection with

the SIB through MQTT, and then you create the KP’s instance.

Once you’ve done that, you are ready to invoke the operations to interoperate with the SIB.

// We define the configuration parameters for the physical connection with the SIB

Kp kp; try { MQTTConnectionConfig config = new MQTTConnectionConfig(); config.setHostSIB(host); config.setPortSIB(port); config.setQualityOfService(QoS.AT_LEAST_ONCE); config.setTimeOutConnectionSIB(5000);

// We build the KP instance with MQTT configuration kp=new KpMQTTClient(config); } catch (Exception e) { log.error("Cannot connect to the SIB using TCP: "+e.getMessage()); throw new ExcepcionGateway("Cannot connect to the SIB using TCP:

"+e.getMessage()); }

// From this point on, we will use the utility class SSAPMessageGenerator to // invoke the different operations to interoperate with the SIB

Page 62: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 62/98

6 ANDROID API

6.1 Introduction

The Android application development is done in Java programming language and a set of

development tools called Android SDK.

SOFIA2 provides a Java API for developing KPs on the Android SDK. This API consists of a set

of Java classes and interfaces that facilitate the generation and process of SSAP messages as

well as the connection to the platform through connectors that communicate with the platform’s

gateways.

6.2 Distribution

Sofia2 API for Android development is provided in a jar library that will be necessary to include

in the KPs and projects that include android device connectivity with the SIB. The library ssap-

android.jar will be included in the Android SDK distribution for SOFIA2.

6.3 KP Interface

It provides methods to connect to the platform and exchange SSAP messages.

This is an interface that several classes implement, each class representing a protocol specific

connector (MQTT, HTTP).

It facilitates the migration of a KP to new protocols that can be defined in the future, abstracting

how to connect and send / receive SSAP messages from the protocol used.

The interface has the following form:

public interface Kp { boolean isConnected();

String getSessionKey(); void connect() throws ConnectionToSibException; void disconnect();

void setConnectionConfig(ConnectionConfig config); void setXxteaCipherKey(String cipherKey); SSAPMessage send(SSAPMessage msg) throws ConnectionToSibException; SSAPMessage sendCipher(SSAPMessage msg) throws ConnectionToSibException; void addListener4SIBNotifications(Listener4SIBIndicationNotifications listener); void removeListener4SIBNotifications(Listener4SIBIndicationNotifications listener);

}

These operations in different implementations allow Java applications:

boolean isConnected(): Knows whether the KP is connected to a SIB or not.

String getSessionKey(): Once connected to the SIB, recovers the sessionKey

assigned for the connection.

Page 63: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 63/98

void connect(): Creates a physical connection with the SIB through the Gateway of

the protocol that the class implements. The physical connection makes sense only for the MQTT connector.

void disconnect(): Closes the physical connection with the SIB that was established

with connect(). void setConnectionConfig(ConnectionConfig config): Configures parameters

to connect to the SIB. The parameter ConnectionConfig includes the configuration parameters to connect with the SIB’s Gateway and reports them to the KP.

void setXxteaCipherKey(String cipherKey): Establishes the XXTEA cipher

algorithm key to cipher the SSAP message Exchange.

SSAPMessage send(SSAPMessage msg): Sends a SSAP message to the SIB and

receives the SSAP response message. SSAPMessage sendCipher(SSAPMessage msg): Sends a SSAP message to the SIB

and receives the SSAP response message. This communication is cipher using the XXTEA algorithm.

void addListener4SIBNotifications(Listener4SIBIndicationNotifications listener): Adds a listener to get subscription message notifications. A listener is a

class implementing the interface Listener4SIBIndicationNotifications. To implement this interface, you must implement the method onIndication, which receives the SSAP INDICATION message with subscription notification data as a parameter.

void removeListener4SIBNotifications(Listener4SIBIndicationNotifications listener): Deletes one listener, so as to stop receiving subscription message

notifications.

6.4 Similarities with JAVA API

Sofia2 API for Android development is an independent development of Java API. However, their development is an adaptation of the original Java classes to be compatible with concrete implementations in the Android dalvik: AOP cleaning, minimizing dependencies, security, etc.. Because of this parallelism, appearance, performance and functionalities of the Android API are exactly the same as in the Java API, except a couple of details:

The API classes can be found at the package:

package com.indra.sofia2.ssapandroid;

Allow developed apps to connect to internet, at AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

This section of the Android API only focuses on reviewing the main aspects of this implementation. For more detail review points 5.4 Protocol connectors in the API and 5.5 API Utilities.

6.5 Use Example

In order to create a KP using MQTT protocol, we will define the physical connection to the SIB

through MQTT and we will create the instance of KP.

Once this is done we will be prepared to invoke operations to interoperate with the SIB.

Page 64: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 64/98

// Establecemos los parámetros de configuración para la conexión física con el SIB

Kp kp; try { MQTTConnectionConfig config = new MQTTConnectionConfig(); config.setHostSIB(host); config.setPortSIB(port); config.setQualityOfService(QoS.AT_LEAST_ONCE); config.setTimeOutConnectionSIB(5000);

// Creamos la instancia del KP con la configuración MQTT kp=new KpMQTTClient(config); } catch (Exception e) { log.error("Imposible conectar al SIB por TCP: "+e.getMessage()); throw new ExcepcionGateway("Imposible conectar al SIB por TCP:

"+e.getMessage()); }

//A partir de aquí a través de la clase de utilidad de SSAPMessageGenerator iríamos

invocando a las diferentes operaciones para interoperar con el SIB

Page 65: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 65/98

7 ARDUINO API

7.1 KPMqtt Library

This API provides the Platform for Arduino devices. It includes operations to interoperate with

the SIB: connect, send and receive messages from the SIB.

/** * Method to establish client’s id */ void setClientId(char* cId);

/** * Method to obtain client’s id */

char* getClientId();

/** * Method returning whether the KP is currently connected to the SIB */

bool isConnected();

/** * Method returning the sessionKey for the current connection with the SIB * response is null if not connected to the SIB */

char* getSessionKey();

/** * Method connecting the KP with the SIB by sending a SSAP JOIN message. */

void connect();

/** * Method to physically disconnect a KP from the SIB */

void disconnect();

/** * Method establishing the configuration parameters for the physical connection of * the KP with the SIB */

void setConnectionConfig(ConnectionConfig* config);

/** * Method to send SSAP messages to the SIB * @return */

SSAPMessage send(SSAPMessage* msg);

/** * Method to send ciphered SSP messages to the SIB using XXTea algorithm */

SSAPMessage sendEncrypt(char* msgJson, unsigned char* key, int keyLength);

/** * Method to register a listener for subscription notifications */

void addListener4SIBNotifications(Listener4SIBIndicationNotifications listener);

/** * Method to release a subscription notification listener

Page 66: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 66/98

*/ void removeListener4SIBNotifications(Listener4SIBIndicationNotifications listener);

/** * Method to register a listener to receive messages from the SIB */

void addListener4SIBCommandMessageNotifications(Listener4SIBCommandMessageNotifications listener);

/** * Method to release a listener and stop receiving messages from the SIB */

void removeListener4SIBCommandMessageNotifications(Listener4SIBCommandMessageNotifications listener);

/** * Method to launch the loop to receive notifications from the SIB */

void loopMqtt();

/** * Callback to receive notifications from the SIB */

void callback( char* topic, byte* payload, unsigned int length );

7.2 Supported protocols

7.2.1 MQTT

Arduino has the library PubSubClient that allows for simple operations of publishing and

subscribing from client on a server using the MQTT protocol.

To use this library, you only have to import it in the Arduino code:

#include <PubSubClient.h>

The messages to connect with the SIB will be performed in a similar way to the other API’s,

through SSAP messages:

SSAPMessage joinMessage; Serial.println("Send join"); // We create the SSAP JOIN message joinMessage=ssapGenerator.generateJoinMessage("abcd23efca238daddd32398d", "KPArdu:001"); // We send the message SSAPMessage joinResponse=kp.send(&joinMessage); Serial.println("Receives join"); char* bodyJoin=joinMessage.getBody(); delete[] bodyJoin; // We get the body of the response message char* responseBody=joinResponse.getBody(); // We translate the received message from JSON to the Object

Page 67: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 67/98

SSAPBodyReturnMessage bodyMessage=SSAPBodyReturnMessage::fromJSonToSSAPMessage(responseBody);

Page 68: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 68/98

8 JAVASCRIPT API

8.1 kp-core.js library

The Platform also provides an API to interoperate with the SIB using JavaScript.

The JavaScript API provides a set of functions covering all the SSAP operations, thus

abstracting the programmer from the message building process.

Each function receives arguments with the data on the message type it abstracts, along with a

callback function which will invoke the API to notify the response once it is sent.

The JavaScript API considers that all the callback functions have one only argument, which is

an object with the response SSAP message.

The JavaScript library interface looks like this:

function setKpName(kpName); function join(user, pass, instance, joinResponse); function joinCipher(user, pass, instance, joinResponse); function joinByToken(token, instance, joinResponse); function joinByTokenCipher(token, instance, joinResponse); function leave(leaveResponse); function leaveCipher(leaveResponse); function insert(data, ontology, insertResponse); function insertCipher(data, ontology, insertResponse); function query(query, ontology, queryResponse); function queryCipher(query, ontology, queryResponse); function subscribe(suscription, ontology, refresh); function subscribeCipher(suscription, ontology, refresh); function unsubscribe(querySubs, unsubscribeResponse, unsubscribeMessages); function unsubscribeCipher(querySubs, unsubscribeResponse, unsubscribeMessages); function setCipherKey(key);

setKpName: Reports the KP name to the API.

join: Sends a SSAP JOIN message to authenticate with user name and password. It

receives response through the callback joinResponse function. The argument of this

function is the RESPONSE-type SSAP JOIN message with the assigned sessionKey.

joinByToken: Sends a SSAP JOIN message to authenticate via token. It receives

response through the callback joinResponse function. The argument of this function is

the RESPONSE-type SSAP JOIN message with the assigned sessionKey.

leave: Sends a SSAP LEAVE message. You do not have to specify the sessionKey

because the API controls it. It receives response through the callback leaveResponse

function. The argument of this function is the RESPONSE-type SSAP LEAVE message,

specifying whether the operation was successful or not.

insert: Sends a SSAP INSERT message with the specified data and on the specified

ontology. It receives response through the callback insertResponse function. The

Page 69: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 69/98

argument of this function is the RESPONSE-type SSAP INSERT message, specifying

whether the operation was successful or not.

query: Sends a SSAP QUERY message with the specified query and on the specified

ontology. It receives response through the callback queryResponse function. The

argument of this function is the RESPONSE-type SSAP QUERY message, which

returns the data from the query.

subscribe: Sends a SSAP SUBSCRIBE message with the specified subscription query

and refresh time, and on the specified ontology..

unsubscribe: Sends a SSAP UNSUBSCRIBE message with the specified subscription

query. It receives response through the callback unsubscribeResponse function, and

errors through unsubscribeMessages.

In the case of subscriptions, the programmer must implement the following functions:

function subscriptionWellLaunchedResponse(subscriptionId, suscription): It

notifies a query’s subscribption Id after a successful subscription.

Function indicationForSubscription(ssapMessage): It notifies an INDICATION-

type SSAP message for a subscription notification.

The JavaScript API allows for XXTEA cipher. To do so, the API provides this function:

setCipherKey: Reports the cipher key to the API.

It also provides, for each function, a homonym cipher function: xxxCipher(). (e.g. :

joinCipher(), insertCipher()….).

8.2 Supported Protocols

8.2.1 Webscoket

It is supported through the WebSocket Gateway of Sofia2.

This API requires:

Import the following libraries:

o Library of the API Javascript: sofia2-api-js_v2<minor-version>.js

(supported from the version sofia2-api-js_v2.8.0.js.

Initialize the variable pathToWebsocketServer indicating the API the endpoint of

the Gateway of the SIB.

Page 70: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 70/98

Use example

//Cargamos la librería del api <script type='text/javascript' src="sofia2-api-js_v2<minor-version>.js">;</script> <script type="text/javascript"> var pathToWebsocketServer =

"ws://sofia2.com/sib/api_websocket";</script>

//Para conectar con el SIB, nos creamos una función que será la que invoque a la operación de //conectar disponibilizada en la librería. function conectarSIB(user, pass, inst) { sofia2.join(user, pass, inst,function(mensajeSSAP){ //Comprobamos si se ha establecido la conexión o no if(mensajeSSAP != null && mensajeSSAP.body.data != null &&

mensajeSSAP.body.ok == true){

$("#infoConexion").text("Conectado al sib con sessionkey: "+mensajeSSAP.sessionKey).show(); }else{ $("#infoConexion").text("Error conectando del sib").show(); } });

8.2.2 AJAX/AJAX Push

It is supported through the DWR Gateway of Sofia2.

This API requires:

Import the following libraries:

o Library of the API Javascript: kp-core.js (deprecated) or sofia2-api-

js_v2<minor-version>.js

o Library DWR of the Gateway of sofia2.com:

http://sofia2.com/sib/dwr/engine.js, http://sofia2.com/sib/dwr/util.js,

http://sofia2.com/sib/dwr/interface/GatewayDWR.js

Initialize the variable pathToDwrServlet that indicates the API the endpoint of the

Gateway of the SIB

Activate the option of reverse Ajax of DWR to receive subscription notifications

through:

o dwr.engine.setActiveReverseAjax(true);

o dwr.engine.setTimeout(0)

Use example:

Page 71: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 71/98

//Cargamos la librería del api <script type='text/javascript' src="sofia2-api-js_v2<minor-version>.js">;</script> <script type='text/javascript' src='http://sofia2.com/sib/dwr/engine.js'></script> <script type='text/javascript' src='http://sofia2.com/sib/dwr/util.js'></script> <script type='text/javascript' src='http://

sofia2.com/sib/dwr/interface/GatewayDWR.js'></script> <script type="text/javascript"> var pathToDwrServlet = 'http://sofia2.com/sib/dwr';</script> $(function(){

try {

dwr.engine.setActiveReverseAjax(true);

dwr.engine.setTimeout(0);

} catch(e) {}

});

//Para conectar con el SIB, nos creamos una función que será la que invoque a la operación de //conectar disponibilizada en la librería. function conectarSIB(user, pass, inst) { sofia2.join(user, pass, inst,function(mensajeSSAP){ //Comprobamos si se ha establecido la conexión o no if(mensajeSSAP != null && mensajeSSAP.body.data != null &&

mensajeSSAP.body.ok == true){

$("#infoConexion").text("Conectado al sib con sessionkey: "+mensajeSSAP.sessionKey).show(); }else{ $("#infoConexion").text("Error conectando del sib").show(); } }); }

Page 72: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 72/98

9 NODE.JS API

9.1 Introduction

Node.js (http://nodejs.org/) is a platform that enables the development of JavaScript on the

server side through V8 JavaScript engine developed by Google. Its architecture is event-

based and designed for asynchronous programming. It consists of several modules that

facilitate the use of this language.

SOFIA2 provides a Node.js API for the development of KPs. This API is a set of utilities that

facilitate the generation and processing of SSAP messages and the connection with the

platform through MQTT to communicate with the platform’s gateways.

9.2 KpMQTT.js Library

The platform also provides an API to interoperate from the server side through javascript.

It provides an "interface" that abstracts the low-level implementation of MQTTClient.js class and

along with the SSAP message generator allows us to operate directly with the SIB. For this API,

it is set a two topics criteria, one is set to publish messages and the other topic for receive

messages from SIB.

The methods of the "interface" KpMQTT.js are:

function connect(port, host)

function disconnect()

function isConnected()

function send(ssapMessage)

function sendCipher(ssapMessage)

function setCipherKey(_cipherKey)

function messageDispatcher();

Page 73: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 73/98

connect: Allow the connection with the SIB providing the url and port.

disconnect: Free an existing connection with the SIB.

isConnected: Return a Boolean indicating whether the session has been started or not.

send: Send a SSAP message to the SIB and subscribe to topic response for that

message.

sendCipher: Send a SSAP encrypted message to the SIB. To do this, the API provides

encryption classes base64.js and XXTEA.js.

setCipherKey: Set the encryption key that receives as a parameter.

messageDispatcher: Listener waiting for a message arriving from the topic of

notifications.

9.3 SSAP Message Generator

There is also available a class responsible of generating the different messages with SSAP

format called SSAPMessageGenerator.js. This class is identical to the Javascript API class,

except that encrypted messages are not included, since the KpMQTT.js class allows sending

encrypted and unencrypted messages through the methods send () and sendCipher ().

The functions are:

function join(user, pass, instance, joinResponse);

function joinToken(token, instance, joinResponse);

function leave(leaveResponse);

function insert(data, ontology, insertResponse);

function insertWithQueryType(data, ontology, queryType, insertResponse);

function update(data, query,ontology, updateResponse);

function updateWithQueryType(data, query, ontology, queryType, updateResponse);

function remove(query, ontology, removeResponse);

function removeWithQueryType(query, ontology, queryType, removeResponse);

function query(query, ontology, queryResponse);

function queryWithQueryType(query, ontology, queryType, queryParams, queryResponse);

function subscribe(suscription, ontology, refresh);

function subscribeWithQueryType(suscription, ontology, queryType, refresh);

function unsubscribe(querySubs, unsubscribeResponse, unsubscribeMessages);

join: Send a authentication user / password JOIN SSAP message. It gets the response

through the callback function joinResponse, whose argument is the SSAP JOIN

RESPONSE-type message with the SessionKey assigned by the SIB once credentials

are checked.

Page 74: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 74/98

joinToken: Send a authentication token JOIN SSAP message. It gets the response

through the callback function joinResponse, whose argument is the SSAP JOIN

RESPONSE-type message with the SessionKey assigned by the SIB once token has

been validated.

leave: Send a SSAP LEAVE message. There is no need to specify the SessionKey

since it is managed by the API. It receives the response through leaveResponse

callback function, whose argument is a SSAP LEAVE message RESPONSE-type

indicating whether the operation was successful.

insert: Send a SSAP INSERT message with data at the specified ontology. It gets the

response through the callback function insertResponse, whose argument is a SSAP

INSERT message RESPONSE-type indicating whether the operation was successful.

The data sent must be in Native MongoDB format to be inserted.

InsertWithQueryType: Send a SSAP INSERT message with data at the specified

ontology. It gets the response through the callback function insertResponse, whose

argument is a SSAP INSERT message RESPONSE-type indicating whether the

operation was successful.

The data sent can be either in native format or Insert statement SQL-Like type. The

queryType argument with "NATIVE" or "SQLLIKE" values is used to indicate a

circumstance or another.

update: Send a SSAP UPDATE message to update existing data of the specified

ontology. To do this, the value of the new data is reported in the data argument, and the

criteria to be met to update are reported in the query argument. It gets the response

through the callback function updateResponse, whose argument is a SSAP UPDATE

message RESPONSE-type indicating whether the operation was successful.

Both the data sent and the selection criteria for updating, must be in Native MongoDB

format to be updated.

updateWithQueryType: Send a SSAP UPDATE message to update existing data at

the specified ontology. It gets the response through the callback function

updateResponse, whose argument is a SSAP UPDATE message RESPONSE-type

indicating whether the operation was successful.

The data sent can be either in native format or Insert statement SQL-Like type. The

queryType argument with "NATIVE" or "SQLLIKE" values is used to indicate a

circumstance or another.

Page 75: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 75/98

If the native format is used, you must specify in the data argument the new value, and in

the query argument the criteria to meet to be updated.

If the SQLLIKE format is used, the data argument will be null and the query argument is

the Update statement in SQLLIKE format.

remove: Send a SSAP DELETE message to delete existing data at the specified

ontology. To do this, the delete sentence is reported in native MongoDB deleted format

in the query argument. It gets the response through the callback function

removeResponse, whose argument is a SSAP DELETE message RESPONSE-type

indicating whether the operation was successful.

removeWithQueryType: Send a SSAP DELETE message to update existing data at

the specified ontology. It gets the response through the callback function

removeResponse, whose argument is a SSAP DELETE message RESPONSE-type

indicating whether the operation was successful.

The data can be deleted either in native format or Delete statement SQL-Like type. The

queryType argument with "NATIVE" or "SQLLIKE" values is used to indicate a

circumstance or another.

If the native format is used, you must specify in the argument MongoDB delete sentence.

If the SQLLIKE format is used, the query argument will be the sentence in SQLLIKE

format.

query: Send a SSAP QUERY message with the query and the given ontology. It gets

the response through the callback function queryResponse, whose argument is the

SSAP QUERY message RESPONSE-type returning the query data.

The query data format must be native MongoDB.

queryWithQueryType: Send a SSAP QUERY message with the query and the

specified ontology. It gets the response through the callback function queryResponse,

whose argument is the SSAP QUERY message RESPONSE-type returning the query

data.

The query criteria of the query argument can indicated both using the native format, or

using a SQL Like Select statement. The queryType argument with "NATIVE" or

"SQLLIKE" values is used to indicate a circumstance or another.

If the native format is used, you must specify in the query argument the data for the

query in MongoDB format.

Page 76: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 76/98

If the SQLLIKE format is used, the query argument will be the Select sentence in

SQLLIKE format.

It can also run predefined queries in the SIB, in this case you must specify in the query

argument the identifier of the predefined query and in queryType argument the value

"SIB_DEFINED".

Additionally, in case of a predefined query SIB_DEFINED that supports input

parameters, these can be sent through queryParams argument, passing a javascript

Map:

var params = {};

params["PARAM1"] = '\"S_Temperatura_00001\"';

params["PARAM2"] = '20';

In the rest of cases(NATIVE, SQLLIKE or SIB_DEFINED without parameters), the

queryParams argument will be null.

subscribe: Send a SUBSCRIBE SSAP message with the subscription, updating query

at the specified ontology.

The subscription query data must be in native MongoDB format.

subscribeWithQueryType: Send a SSAP SUBSCRIBE message with the

subscription, updating query at the specified ontology.

The query criteria of the query argument can be indicated both using the native format,

or using a SQL Like Select statement. The queryType argument with "NATIVE" or

"SQLLIKE" values is used to indicate a circumstance or another.

If the native format is used, you must specify in the query argument the data for the

query in MongoDB format.

If the SQLLIKE format is used, the query argument will be the Select sentence in SQL

like format.

unsubscribe: Send a SSAP UNSUBSCRIBE message at the subscription query

indicated. It gets the response through unsubscribeResponse callback function and

errors through unsubscribeMessages.

Page 77: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 77/98

9.4 Supported protocols

9.4.1 MQTT

Node.js API runs on MQTT protocol, for this purpose it is available the MQTTClient.js class that

manages this protocol and exports the following functions:

function create_conection(port, host, clientID);

function publish(pub_topic, payload);

function subscribe(sub_topic);

function unsubscribe(topic);

function ping();

function disconnect();

create_connection: Create a connection to SIB using Port, url host and client id, although

this last parameter is optional.

publish: Sending messages (payload) to a queue or topic of receiving messages.

subscribe: It is subscribed directly to a topic that receives as a parameter, for receiving

messages.

unsubscribe: This function sends a message to the SIB to stop receiving notifications

through a topic.

ping: Send a message to check the connection to the MQTT server.

disconnect: Free the connection established with the SIB.

9.5 Use Example

The following section shows a use example of how to use Node.js. API:

First thing to do is to import the three modules you see in the image header:

kpMQTT in order to use the NODE.JS API functions.

SSAPMessageGenerator to generate the different SSAP messages to send to the SIB.

Finally, the module wait.for that will make possible to run the execution in a separate

thread wait.launchFiber(main.

Page 78: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 78/98

NOTE: wait.for. Through this function you can call any standard asynchronous function

from Node.js in synchronous or sequential mode, waiting for the results without locking the

node event loop. Available through modules that Node.js provides.

A basic cycle for the ontology SensorTemperatura is shown below:

- A JOIN message to the SIB to obtain the SessionKey in the response, allowing us to

send insert, delete, update, subscription messages.

- Next in the test is sending a subscription message for those measures larger above 18

° C, if all goes well. Those data introduced in the ontology satisfying this condition will be

returned by notifying the MQTT_INDICATION topic, and will be processed by the

MessageDispatcher kp function.

- Finally, an insert is done in the ontology of a measure of 21 ° C, in order to get the

corresponding notification.

Page 79: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 79/98

Page 80: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 80/98

10 C API

10.1 libssap-core-api-c library

It provides a dynamic link library for the development of KPs using the C language.

For compatibility among platforms, the source code of the library is provided along with a

Makefile to compile it.

The API can be found in the SDK bundle, in the folder SOFIA\SOFIA-SDK\API\API-KP-C\ssap-

core-api-c.

This way it’s possible to generate the library and use the header files to solve compilation

dependencies.

The code structure is that of a C dynamic link library Netbeans project, although it can be

compiled directly with the make tool.

build: folder where the library object files are generated.

dist: folder where the library is generated.

nbproject: folder with the library compilation parameters.

src: library source code.

Makefile: main file for library compilation. It makes reference to the configuration stored

in the nbproject folder.

This way it’s posible to open the project with Netbeans and configure the different compilation

parameters through the wizards, or configure them manually in nbproject/ Makefile-

variables.mk

10.2 Compiling with Make

To generate the library with the with the Make tool follow these steps:

Page 81: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 81/98

1. Configure the variables in the file nbproject/Makefile-variables.mk.

In the Release section assign the folders and the library name if you want to modify

them.

2. Delete files from previous compilations by executing from the project root the following

command:

make –f nbproject/Makefile-Release.mk QMAKE= SUBPROJECTS= .clean-conf

3. Create the library with the following command:

make –f nbproject/Makefile-Release.mk QMAKE= SUBPROJECTS= .build-conf

When finished, the library will be in the folder indicated in the file nbproject/Makefile-

variables.mk.

10.3 Supported protocols

The protocol supported by the library to communicate with the SIB is MQTT.

10.4 API features

The API provides a set of utilities and functions to:

Connect to/disconnect from the platform.

Generate and encapsulate SSAP messages.

Send SSAP messages to the platform.

Parse SSAP and JSON messages.

Subscribe to events in the platform.

10.5 API functions

10.5.1 KP-SIB communication functions

KpMqtt_connect(connectionConfig: mqtt_connection_config*): enum ConnectionStatus

o Description: opens a physical connection with the platform MQTT Gateway. It’s

described in the header file KpMQTT.h

o Returns: connection status. Possible values are:

Page 82: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 82/98

CONNECTED: connection has been successful.

FAILED_CallbacksNotRegistered: connection has not been established

since it has been impossible to register the callback mechanism.

FAILED_PhysicalConnection: connection has not been established

since it has been imposible to connect with the indicated gateway.

FAILED_SubscriptionToSIBTopic: connection has not been

established since the MQTT Gateway rejects the KP to subscribe to the

needed topics.

o Parameters:

connectionConfig: mqtt_connection_config*: pointer to the

mqtt_connection_config structure that stores the connection parameters

to the platform MQTT Gateway. These parameters are:

serverAddress:char*: MQTT Gateway IP address or name.

serverPort:char*: Port where the MQTT Gateway is listening.

clientId:char*: Identifier given to this MQTT client.

KpMqtt_disconnect(timeout: int, clientId: char*): enum DisconnectionStatus

o Description: closes the physical connection with the platform MQTT Gateway.

It’s described in the header file KpMQTT.h.

o Returns: disconnection status. Possible values are:

DISCONNECTED: disconnection has been successful.

FAILED_ClosePhysicalConnection: there has been an error closing the

connection.

o Parameters:

timeout:int: time in milliseconds to close the connection.

clientId: Identifier o the MQTT client that was used to open the

connection.

KpMqtt_send(request: ssap_message*, response: ssap_message*, timeout: int): enum

SendStatus

Page 83: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 83/98

o Description: Sends an SSAP message to the platform and receives the

response. It’s described in the header file KpMQTT.h.

o Returns: delivery status. Possible values are:

OK: sending has been successful.

FAILED_SendMessage: there has been a failure sending the message. It

has not arrived to the platform.

FAILED_SIBReceptionConfirmation: A reception confirmation has not

been received for the message. It may have arrived to the platform.

FAILED_ReceivingSSAPResponse: An SSAP response has not been

received for the message.

o Parameters:

request:ssap_message*: pointer to the ssap_message structure with the

SSAP message sent to the platform.

response:ssap_message*: pointer to the ssap_message structure with

the SSAP message returned from the platform.

timeout:int: time in milliseconds to complete the operation.

KpMqtt_setIndicationListener(KPMQTT_IndicationReceived* il):void

o Description: registers the callback function through which the KP will receive the

notifications of SSAP subscriptions. This is where the KP developer will program

the logic for handling the notification. It’s described in the header file KpMQTT.h

o Parameters:

il:KPMQTT_IndicationReceived*: pointer to the callback function defined

by the user that will handle the reception of the SSAP message. This

function will be invoked when the API receives a subscription notification

from the platform.

The function definition is the following:

KPMQTT_IndicationReceived(indicationMessage ssap_message*):int

It receives as a parameter a pointer to the ssap_message structure with

the data of the received SSAP message, of type INDICATION.

mqtt_connection_configFree(config: mqtt_connection_config*):void

Page 84: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 84/98

o Description: frees the memory assigned to a mqtt_connection_config

structure. It’s described in the header file KpMQTT.h

o Parameters:

config:mqtt_connection_config*: pointer to the structure to be freed.

10.5.2 SSAP messages handling functions

generateJoinMessage(token: char*, instance: char*,joinMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

JOIN message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

token:char*: authentication token to be included in the JOIN message.

Instance:char*: identifier of the KP instance to be included in the JOIN

message.

joinMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateLeaveMessage(sessionKey: char*, leaveMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

LEAVE message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the LEAVE message.

leaveMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateInsertMessage(sessionKey: char*, ontology: char*, data: char*,

insertMessage:ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

INSERT message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the INSERT message.

ontology:char*: Ontology over which the INSERT is performed.

data: Data of the ontology instance to insert in MongoDB native format.

Page 85: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 85/98

insertMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateInsertMessageWithQueryType(sessionKey: char*, ontology: char*, data:

char*, queryType: enum SSAPQueryType, insertMessage ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

INSERT message, specifying the used language type. It’s defined in the header

file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the INSERT message.

ontology:char*: Ontology over which the INSERT is performed.

data: INSERT statement in the specified language.

queryType: Language type used in the statement. Possible values are:

NATIVE: statement in MongoDB native language.

SQLLIKE: statement in SQL.

insertMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateUpdateMessage(sessionKey: char *, ontology: char*, data: char*, query: char*,

updateMessage: ssap_message*): void

o Description: generates a ssap_message structure with the data for a SSAP

UPDATE message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the UPDATE message.

ontology:char*: Ontology over which the UPDATE is performed.

data: Data of the ontology instances to update in MongoDB native format.

query: Criteria for selection of the ontology instances to update in

MongoDB native format.

updateMessage:ssap_message*: pointer to the ssap_message

structure where the generated SSAP message is returned.

generateUpdateMessageWithQueryType(sessionKey: char *,ontology: char*, data:

char*, query:char*, queryType: enum SSAPQueryType, updateMessage:

ssap_message*):void

Page 86: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 86/98

o Description: generates a ssap_message structure with the data for a SSAP

UPDATE message, specifying the used language type. It’s defined in the header

file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the UPDATE message.

ontology:char*: Ontology over which the UPDATE is performed.

data: Data of the ontology instance to update in MongoDB native format.

In case of using SQLLIKE, this parameter will be NULL.

query: UPDATE statement in the specified language.

queryType: Language type used in the statement. Possible values are:

NATIVE: statement in MongoDB native language.

SQLLIKE: statement in SQL.

updateMessage:ssap_message*: pointer to the ssap_message

structure where the generated SSAP message is returned.

generateRemoveMessage(sessionKey: char *, ontology: char *, query: char*,

removeMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

DELETE message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the DELETE message.

ontology:char*: Ontology over which the DELETE is performed.

query: Criteria for selection of the ontology instances to remove in

MongoDB native format.

o removeMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateRemoveMessageWithQueryType(sessionKey: char *, ontology: char *,query:

char*, queryType: enum SSAPQueryType, removeMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

DELETE message, specifying the used language type. It’s defined in the header

file SSAPMessageGenerator.h.

o Parameters:

Page 87: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 87/98

sessionKey:char*: SessionKey to be included in the DELETE message.

ontology:char*: Ontology over which the DELETE is performed.

query: DELETE statement in the specified language.

queryType: Language type used in the statement. Possible values are:

NATIVE: statement in MongoDB native language.

SQLLIKE: statement in SQL.

deleteMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateQueryMessage(sessionKey: char *,ontology: char *, query: char*,

queryMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

QUERY message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the QUERY message.

ontology:char*: Ontology over which the QUERY is performed.

query: Criteria for selection of the ontology instances to return in

MongoDB native format.

queryMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateQueryMessageWithQueryType(sessionKey: char *,ontology: char *, query:

char*, queryType: enum SSAPQueryType, queryMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

QUERY message, specifying the used language type. It’s defined in the header

file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the QUERY message.

ontology:char*: Ontology over which the QUERY is performed.

query: QUERY statement in the specified language, or the query identifier

in case of a SIB_DEFINED query.

queryType: Language type used in the statement. Possible values are:

NATIVE: statement int MongoDB native language.

Page 88: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 88/98

SQLLIKE: statement in SQL.

SIB_DEFINED: query stored in the SIB. In this case, its identifier is

specified in the query parameter.

BDH: query over the Historical Database.

o queryMessage:ssap_message*: pointer to the ssap_message structure where

the generated SSAP message is returned.

generateSIBDefinedQueryMessageWithParam(sessionKey: char *,query: char*,

params[]:queryParam, numOfParams: int, queryMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

QUERY message for a query stored in the SIB, which receives parameters for its

execution. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the QUERY message.

query: Identifier of the query stored in the SIB.

params[]:queryParam: Array with the parameters that are passed to the

query. Each parameter is encapsulated in a queryParam structure, that

consists a key-value pair:

key: Name of the parameter in the predefinied query

value: Value provided by the program for that parameter

numOfParams: Number of parameters in the params array.

queryMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

generateSubscribeMessage(sessionKey: char *, ontology: char *, msRefresh:int,

query: char*, subscribeMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

SUBSCRIBE message. It’s defined in the header file

SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the SUBSCRIBE

message.

ontology:char*: Ontology over which the SUBSCRIBE is performed.

Page 89: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 89/98

msRefresh: Interval of notification from the SIB between two different

notifications in case of existing data.

query: Criteria for selection of the ontology instances to notify about in

MongoDB native format.

subscribeMessage:ssap_message*: pointer to the ssap_message

structure where the generated SSAP message is returned.

generateSubscribeMessageWithQueryType(sessionKey: char *, ontology: char *,

msRefresh: int, query: char*, queryType: enum SSAPQueryType, subscribeMessage:

ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

SUBSCRIBE message, specifying the used language type. It’s defined in the

header file SSAPMessageGenerator.h.

o Parameters:

sessionKey:char*: SessionKey to be included in the SUBSCRIBE

message.

ontology:char*: Ontology over which the SUBSCRIBE is performed.

msRefresh: Interval of notification from the SIB between two different

notifications in case of existing data.

query: QUERY statement in the specified language, or the query identifier

in case of a SIB_DEFINED query.

queryType: Language type used in the statement. Possible values are:

NATIVE: statement in MongoDB native language.

SQLLIKE: statement in SQL.

SIB_DEFINED: query stored in the SIB. In this case, its identifier is

specified in the query parameter.

subscribeMessage:ssap_message*: pointer to the ssap_message

structure where the generated SSAP message is returned.

generateUnsubscribeMessage(sessionKey: char *, ontology: char *, suscriptionId: char

*, unsubscribeMessage: ssap_message*):void

o Description: generates a ssap_message structure with the data for a SSAP

UNSUBSCRIBE message. It’s defined in the header file

SSAPMessageGenerator.h.

Page 90: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 90/98

o Parameters:

sessionKey:char*: SessionKey to be included in the UNSUBSCRIBE

message.

ontology:char*: Ontology over which the UNSUBSCRIBE is performed.

subscriptionId: Identifier of the subscription the KP is unsubscribing

from.

o unsubscribeMessage:ssap_message*: pointer to the ssap_message structure

where the generated SSAP message is returned.

ssap_messageFree(ssap_message* message):void

o Description: frees the memory assigned to a structure with the contents of an

SSAP message. It’s defined in the header file SSAPMessageGenerator.h.

o Parameters:

message:ssap_message*: pointer to the ssap_message structure

whose memory has to be freed.

ssap_messageToJson(ssap_message* message): char*

o Description: generates the JSON string with the SSAP message from the data

stored in a ssap_message structure. It’s defined in the header file

SSAPMessageGenerator.h.

o Parameters:

message:ssap_message*: pointer to the ssap_message structure to be

converted to JSON.

o Returns: JSON string with the SSAP message.

ssapMessageFromJson(char* source, ssap_message* message):void

o Description: parses a JSON string with an SSAP message to the equivalente

ssap_message structure. It’s defined in the header file

SSAPMessageGenerator.h.

o Parameters:

source:char*: JSON string with an SSAP message.

message:ssap_message*: pointer to the ssap_message structure

obtained from the JSON.

void query_paramFree(queryParam* param)

Page 91: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 91/98

o Description: frees the memory of the properties of a queryParam structure. It’s

defined in the header file SSAPMessageGenerator.h.

o Parameters:

param: queryParam*: pointer to the structure to be freed.

10.5.3 Structures used in the API

ssap_message:

o Description: encapsulates all the properties of an SSAP message. It’s used like

a DTO to send and receive them through the functions for communicating with

the SIB. It can be written to and generated from a JSON string. It’s defined in the

header file SSAPMessageGenerator.h

o Attributes: the properties of the SSAP specification:

messageId:char*

sessionKey:char*

ontology:char*

direction:enum SSAPMessageDirection. Its value depends on if the

message goes from the KP to the SIB or vice versa:

REQUEST

RESPONSE

ERROR

messageType:enum SSAPMessageTypes. Its value depends on the

message type:

JOIN

LEAVE

INSERT

UPDATE

DELETE

QUERY

Page 92: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 92/98

SUBSCRIBE

INDICATION

UNSUBSCRIBE

persistenceType:enum SSAPPersistenceType. Currently not used, but

included for future compatibility.

body:char*

queryParam:

o Description: encapsulates a parameter of a predefined query. It’s used to pass

the parameter list of a predefined query to the function

generateSIBDefinedQueryMessageWithParam. It’s a key-value pair, to replace

each key in the query with its corresponding value. It’s defined in the header file

SSAPMessageGenerator.h

o Attributes: the properties of the SSAP specification:

key: Name of the parameter in the predefinied query

value: Value provided by the program for that parameter.

mqtt_connection_config:

o Description: encapsulates the connection parameters sent to the

KpMqtt_connect function about the MQTT Gateway. It’s defined in the header

file KpMQTT.h.

o Attributes:

serverAddress:char*: IP address or name of the MQTT Gateway.

serverPort:char*: Port where the MQTT Gateway is listening.

clientId:char*: Identifier given to this MQTT client.

10.6 Additional utilities

10.6.1 cJSON

Utility library to work with JSON. It allows building a JSON tree and converting it to a string, as

well as parsing a JSON string to obtain the equivalent JSON tree.

It’s defined in the header file cJSON.h

All the information about this library can be looked up in the address

http://cjson.sourceforge.net/

Page 93: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 93/98

It will allow parsing the body attribute received in the ssap_message structure, as well as any

other functionality that requires building or parsing JSON.

10.7 API usage

10.7.1 Connect to the platform

To use the functions that allow connecting to the platform you need to include the header file

KpMQTT.h in your program.

Once included, you have to build the structure with the data to connect to the platform through

the MQTT Gateway, and pass it to the KpMqtt_connect function. This function will establish

the physical connection to the platform MQTT Gateway, so you can send and receive SSAP

messages through the rest of the program:

Page 94: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 94/98

The KpMqtt_connect function will return an enumerated value indicating how the operation has

finished. Possible values have been previously specified in the function description.

10.7.2 Disconnect from the platform

Once the program has ended, you have to disconnect from the platform. To do that the

KpMqtt_disconnect function is used:

The KpMqtt_disconnect function will return an enumerated value indicating how the operation

has finished. Possible values have been previously specified in the function description.

Page 95: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 95/98

10.7.3 Send SSAP messages

After connecting to the platform, the following step is to generate and send SSAP messages

through an SSAP sesión. To do that, you have to generate the corresponding SSAP message

using the generator provided in the API.

You include the header file SSAPMessageGenerator.h in your program:

And you use the corresponding function for the message to generate (see section API

functions):

The SSAP message is encapsulated in a structure, which you have to send to the platform

using the KpMqtt_send function, along with another SSAP message structure for the response

message:

Page 96: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 96/98

10.7.4 Processs the response with cJSON

In case of having to process the SSAP message response body, the cJSON library

(http://cjson.sourceforge.net/) allows converting the “body” field from a response structure in

and object with accessible JSON attributes.

Page 97: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 97/98

10.7.5 Liberar memoria de estructuras utilizadas

Both the structures for the SSAP messages and for the SIB configuration should be freed once

they’re not needed anymore:

10.8 Compiler parameters to include the API

In order to include the API, it’s necessary to point the compiler to the folder where the API

header files are found through the -I parameter:

gcc -c -g -I../includes

It’s also necessary to tell the linker where the API .dll (or .so) library is:

gcc -o dist/Debug/Cygwin_4.x-Windows/ejemploapi-c build/Debug/Cygwin_4.x-Windows/main.o

../ssap-core-api-c/dist/Release/Cygwin_4.x-Windows/libssap-core-api-c.dll

Page 98: SOFIA2 APISsofia2.com/docs/(EN) SOFIA2-SOFIA2 APIs.pdf · SOFIA2 APIs Page 8/98 3 COMMUNICATION PROTOCOLS (KP-SIB) Within a SOFIA SmartSpace, the SIB acts as a communication gateway

SOFIA2 APIs Page 98/98

11 OTHER APIS

The Platform roadmap includes implementing other libraries, following the style of Java/Arduino

APIs, for the following languages:

Android

iOS