Sofia2 IoT example with Android: Tag, you’re it!


This post is an example on how easy is to integrate an IoT scenario using Sofia2 IoT platform. The example was presented on February 17th during an introduction lecture on Sofia2 basics for the Embedded & Distributed Systems Sofware Master course at the Universidad Politécnica de Madrid (UPM).

The setup will simulate a typical IoT scenario with just a couple of elements:

  • Android Smarpthone (running at least a 4.4 Android version)
  • BLE (Bluetooth Low Energy) Beacon
  • An upgraded user for platform (ROL_COLABORADOR)



The demo app will periodically fetch data from the smartphone’s accelerometer sensor and GPS. It will also operate as a BLE scanner, triggering an asynchronous event when the selected beacon is placed nearby. Data will be modeled using a Sofia2’s Ontology. Using Sofia2 console, we will create a Dashboard to represent periodic real-time data. A Groovy script will be also generated to evaluate whether the beacon was detected. If that is the case, it will send an e-mail to the user: “Tag, you’re it!”

Let’s go and build this example from scratch!

First we will navigate smoothly over Sofia2’s configuration (we will link you to detailed posts already publish on Sofia2’s blog on the configuration process, while also providing you with the exact values you will need to input to build this example on your own). Then we will move our focus to the Android world and how the app behaves and communicates with Sofia2.  Finally we will show you how the example looks like when finished. Game on!

User, Ontology and ThinKP creation

You will need a collaborator role (ROL_COLABORADOR) for your user. You will also need to define the data model for this example in an Ontology. This post from the IoT Device Integration workshop in Sofia2 series will guide you through these steps.

Find below an example instance of the Ontology  you must reproduce in order to run the example (just change ‘yourOntology’ to your actual ontology name) :

{“yourOntology”:{ “geometry”:{“type”:”Point”, “coordinates”:[9,19.3]},”email”:”string”,”accelX”:28.6,”accelY”:28.6,”accelZ”:28.6,”event”:true}}

Once the data model is all set, it is time to configure the ThinKP to be able to insert data from the device. This post explains how to create a ThinKP and how to obtain its token to use it in your mobile app.

Script definition

A Groovy script will automate the beacon detection rule and its associated action. This post will guide you through the process of writing and activating an ontology-based Groovy script on Sofia2.

The rule we used for the example just needs the IF and THEN section to be coded. These are the code snippets you need to input.

IF Tab:

def apiutils = new APIUtils();

def event=apiutils.getValueJson(ontology, “yourOntology.event”);

if (event==”true”) {
return true;
} else {
return false;

The IF section will be the first one executed whenever a new intance of yourOntology is inserted into Sofia2. In the example we are going to fetch the ‘event’ field from the ontology instance and evaluate it. If true, THEN section will be executed. Otherwise, ELSE section will run (this time it is empty, so no further action will occur).


def apiutils = new APIUtils();
def apimail = new APIMail();
String [] to = [apiutils.getValueJson(ontology,””)];
def subject=”Sofia2 Message”;
def msg=”Tag, you’re it!”;

apimail.sendMail(to, subject, msg);

If the ‘event’ field evaluates as true, this block uses the APIMail to compose an e-mail with a not-so-kind Sofia2 Message.. Tag, you’re it!

Gadgets and dashboard composition

For data visualization, we are going to compose two gadgets and integate them into a dashboard. Again, please read the first section of this post to learn how to build gadgets and dashboards. Our case is pretty similar to the post’ case in the link so it will be pretty straightforward to reproduce it. The approach for the example is to compose two gadgets with live data, one for the accelerometer axis (‘accelX’, ‘accelY’ and ‘accelZ’ fields from yourOntology) and another one for the location (‘geometry’ field from yourOntology).

Your final Dashboard should look similar to this one:


API manager – API creation

Lastly, we are going to create an API to interface with the example data using REST. This may come handy when developing a web-client consuming these data. This post contains a guide on how to implement a GET call on the data using Sofia2’s API Manager.

As an example you may create a GET query operation. Then you can test your API by clicking on ‘My Subscriptions’ tab, searching and finding your API, clicking on Test&Doc, and then editing the fields. You should end up with a setup like this:


The API-Key header can be found under the tab ‘My APIKey’. Upon submission, you should get the last instance inserted in the platform.


Test your Sofia2 setup

Feel free to repeat this testing operation at any point of the exercise. Inside the Ontologies menu, there is a section called ‘Crud Management of Intances’. There you may find your Ontology and then edit a custom “dummy” instance of it. This instance will be inserted to Sofia2 as a real one and will trigger all events.

Whenever you feel comfortable with your Sofia2 setup, move on to the Android section.

Android App overview

The Android app code is uploaded to Sofia2’s Github account under this repo. Feel free to download, fork or suggest improvements! The app turns your smartphone into a IoT gateway. Leveraging the smartphone’s on-board sensors,  geo-positioning capabilites and wireless connectivity (both for BLE scanning and Internet connection), this setup serves as a good integrated example for many IoT applications.

Moving away from Android-specific code, we will focus on how to connect and interact with Sofia2 from the smartphone. For simplicity, this example uses REST to connect to Sofia2. All the connection methods are located in class, although we will mainly use the send method (using the popular and easy HttpURLConnection class) for this example:

send-method is an Android service carrying all the load related to sensor fetching, framing and connection to Sofia2. Again we opted to construct the frame in a very easy way using String concatenation:


For the connection part, we just call the send method, passing by arguments the ThinKP details:


This setup will be enough to insert data into Sofia2. If your testing was correct, now you may expect the same behaviour, but hey, this time data is for real!

Tag, you’re it!


On the Github repo you may find a copy of the .APK. After installation it may require some extra permissions from your side since we are using geo-positioning + BLE scanning.

After editing the settings (do not forget to change the e-mail to the one set on the script), you should be good to go! We filmed a short video highlighting the results. The video also shows our Dashboard showing real-time data from the sensors. Upon beacon detection, you can see how the e-mail arrives as a notification.


We are eager to hear that you made it happen. Please drop us a comment if you manage to do it. Also feel free to contribute to the Github repo since the example is at a very early stage and could be vastly improved 🙂

Sofia2 IoT example with Android: Tag, you’re it!

Un comentario en “Sofia2 IoT example with Android: Tag, you’re it!


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s