# The Mobile Hub

The Mobile Hub (M-Hub) is a general-purpose middleware that enables mobile personal devices (Android smartphones and tablets) to become the propagator nodes (i.e. gateways to the Internet) for the simpler IoT objects or Mobile Objects (M-OBJ) (sensors/actuators) with only short-range WPAN interfaces. It provides context information such as current local time and/or the (approximate) location to the data obtained from the M-OBJs to which it is connected. The M-Hub is the natural extension of the Scalable Data Distribution Layer (SDDL).

The M-Hub application (apk ) requires Android >=4.3 and a Gateway. The current implementation has support for Bluetooth Low Energy as a WPAN technology, so it is also required unless you intend to include a different technology. On the settings activity of the M-Hub, you can uncheck some services/manager to disable them, also you can set the M-Hub to start at boot, the minimum allowed signal to connect or to auto-connect with any M-OBJ that it could find. Moreover, you can set some parameters specific from the different services than are going to be explained later on.

1. Start the gateway with the public IP, port and DDS product (e.g. \$ gateway 127.0.0.1 5500 OpenSplice)
2. Instantiate a processing node
3. Configure the M-Hub parameters that are shown in the images below
4. Start the M-Hub with the play button, or remove previous configurations with the delete button

Once the M-Hub is started, it will start scanning for devices under the supported technologies, and connect to them if auto-connect is enabled. The information obtained from the devices can be visualized in the viewer and events activity that are shown below. The application can be stopped at any moment by pressing the stop button.

### Receiving Messages from the M-Hub

Once the M-Hub is connected with a gateway, it will start sending some information that can be used for further processing. Such information is in JSON format and are of three types: LocationData that samples the current location of the M-Hub, SensorData which is the raw sensor values obtained from the M-OBJs, EventData that describes events obtained from doing some processing over the sensor data, and ErrorData/ReplyData that came from a component with a message. Some examples are:

{  "tag": "LocationData",   "uuid": "b06de58d-6a20-44f9-8cd4-83f074c2edd6", // M-Hub UUID  "latitude": -22.98137128,  "longitude": -43.23421961,  "battery": 50,  "charging": false,  "timestamp": 1442169467 } {  "tag": "SensorData",   "uuid": "b06de58d-6a20-44f9-8cd4-83f074c2edd6",  // M-Hub UUID  "source": "00000000-0000-0000-0001-bc6a29aecef5", // M-OBJ UUID  "action": "found|connected|disconnected|read",   "signal": -48,  "sensor_name": "Temperature",  "sensor_value": [21.70,23.42],  "latitude": -22.98137128,  "longitude": -43.23421961,  "timestamp": 1442169467 } {  "tag": "EventData",   "uuid": "b06de58d-6a20-44f9-8cd4-83f074c2edd6", // M-Hub UUID  "label": "AVGTemp",  "data": {"value": 22.30},  "latitude": -22.98137128,  "longitude": -43.23421961,  "timestamp": 1442169467 } {  "tag": "ErrorData|ReplyData",   "uuid": "b06de58d-6a20-44f9-8cd4-83f074c2edd6", // M-Hub UUID  "component": "MEPAService|S2PAService",  "message": "Action not supported.",  "latitude": -22.98137128,  "longitude": -43.23421961,  "timestamp": 1442169467 }

A small example of how you can parse such data on a processing node (You can also use the Hakke tool), and realize some further processing.

Hello.java
@Overridepublic void onNewData( ApplicationObject topicSample ) {	if( topicSample instanceof Message ) {		Message msg = (Message) topicSample;		String content = new String( msg.getContent() );		JSONParser parser = new JSONParser(); 		try {	                JSONObject object = (JSONObject) parser.parse( content );	                String tag = (String) object.get( "tag" ); 	        	switch( tag ) {	        		case "SensorData":	        			handleSensorData( object );	        		break; 	        		case "EventData":	        			final String label = (String) object.get( "label" );	        			final String data  = (String) object.get( "data" );	        			handleEvent( label, data );		        	break; 	        		case "ReplyData":		        		        		case "ErrorData":	        			handleMessage( tag, object );			        break;	        	}		} catch( Exception ex ) {			System.out.println( ex.getMessage() );		}	}}

### Sending Messages to the M-Hub

SDDL Core applications can send ApplicationMessages to Mobile Nodes, being the M-Hub a special kind of it. Nevertheless, the M-Hub only allows a certain kind of messages that can change its behaviour. To do that, the content object in the message must be a JSON String. There are numerous JSON libraries for Java, in the following code we will use Simple-JSON. The following code shows a sample JSON message of the current allowed operation. It allows the modification of a service called MEPA service which will be explained later.

{ "MEPAQuery": {  "type":"add|remove|start|stop|clear|get",  "label":"AVGTemp",  "object":"rule|event",  "rule":"SELECT avg(sensorValue[1]) as value FROM       SensorData(sensorName='Temperature')      .win:time_batch(10 sec)",  "target":"local|global" }}
JSONObject jsonMSG = new JSONObject();// Build the JSON messageApplicationMessage msg = new ApplicationMessage();msg.setContentObject( jsonMSG.toString() );msg.setPayloadType( PayloadSerialization.JSON );// Send it!!nodeCon.sendMessage( msg );

The M-Hub consists of four services and one manager, all executing in background. The S2PA Service is responsible of discovering and monitoring nearby M-OBJs that use the supported WPAN technologies. This service keeps a record of the current provided sensors/actuators (e.g. temperature, accelerometer, humidity, etc.) and publish the sensed information to all the components that require it. One of which is the Connection Service, where messages are sent to/from the Cloud in a JSON format through an Internet connection. Messages possess different relevance, the important messages (e.g. M-OBJ connection/disconnection) are sent immediately to the cloud, while sensor data or low relevance messages (e.g. temperature, humidity readings) are grouped, to be transmitted as a bulk message at a certain time interval.

Messages that are going to be send to the cloud are enriched with context information, like a timestamp and the approximate location. The location is obtained through the Location Service, responsible for sampling the M-Hub’s current position obtained from different providers like GPS, network, or a manually entered in case of a static location. The periodicity and duration of all of these three service’s actions, is influenced by the device’s current energy level (LOW, MEDIUM, HIGH), and is set by the Energy Manager, which from time to time sample’s the device battery level and checks if it is connected to a power source. The communication among all the services is done using an EventBus , which is a Publish-Subscribe (PubSub) event bus optimized for Android that helps to decouple the components, and allows the inclusion of different services without many code modifications. In order to include a new service that subscribes to some data generated from other services (e.g. SensorData, LocationData, EventData), you will need to include the following functions (also look at the documentation of EventBus):

@Overridepublic void onCreated() {    // register to event bus    EventBus.getDefault().register( this );    //...} @Overridepublic void onDestroy() {    // unregister from event bus    EventBus.getDefault().unregister( this );    //...} /** The data type will change depending on the subscription */public void onEvent( SensorData sensorData ) {    //...}

The Mobile Event Processing Agent (MEPA) Service includes local processing of the data received from the Mobile Objects. It keeps a record of the running CEP rules, to be able to start and stop them. The CEP engine has a primitive event for the data arriving from the M-OBJs, which contains the sensors names and their respective values (Sensor Data JSON Message). As shown in the figure below, the MEPA Service is subscribed to all the messages that are sent from the S2PA and Connection services, the former collects the data from the M-OBJs, and the latter receives commands from the cloud to modify the behaviour of the MEPA Service. Every time a complex event is detected, it will be published for any interested component that could be the connection service, or another rule in the MEPA Service.

In the settings activity you can set the HIGH/MEDIUM/LOW parameters for the different services. In case you deactivate the Energy Manager, you can also modify the current value. If the ConnectionService current time interval (MESSAGES INTERVAL) is set to 0, then no messages are going to be group, and low relevance message are not going to be send to the cloud. Currently, the only message allowed by the M-Hub allows to modify the MEPA service. The messages are encapsulated as a MEPAQuery object that contains information about the type (i.e. add/remove/start/stop/clear) and a label to identify the CEP queries. In the case of an add type, the EPL query will be also included as a string, and a target value is required (i.e. local or global). If it is defined as global the detected events will be send to the cloud, and as local will be send as an input for a different rule . Examples of allowed CEP rules:

SELECT avg(sensorValue[0]) FROM SensorData(sensorName='Humidity').win:time_batch(1 minute);

SELECT Math.sqrt(Math.pow(avg(sensorValue[0]), 2.0) + Math.pow(avg(sensorValue[1]), 2.0) + Math.pow(avg(sensorValue[2]), 2.0)) as value from SensorData(sensorName='Accelerometer').win:time_batch(1 minute);

SELECT * FROM SensorData(sensorName='Temperature') match_recognize ( measures A as temp1, B as temp2, C as temp3, D as temp4 pattern (A B C D) define A as A.sensorValue[0] > 20, B as (A.sensorValue[0] < B.sensorValue[0]), C as (B.sensorValue[0] < C.sensorValue[0]), D as (C.sensorValue[0] < D.sensorValue[0]));

### Short-Range Sensor, Presence and Actuation API

In order to allow developers to include uniformly other WPAN technologies such as ANT+, NFC, etc. we included a protocol based on two interfaces. On the one hand, the Technology Interface maps the main capabilities of each WPAN technology to some methods that have to perform the following actions: 1) Discovery of, and connection to M-OBJs, 2) Discovery of services provided by each M-OBJ, 3) Read and write of service attributes (e.g., sensor values, and actuator commands) and 4) Notifications about disconnection of M-OBJs. And on the other hand, the Technology Listener Interface is implemented by the S2PA Service to listen to all the important events that occur on the different technologies and publish them for the any interested component.

The Technologies have to include an ID at programming time to be uniquely identified. This ID is also combined with the M-OBJ’s mac address to form the Mobile Object Universally Unique Identifier (MOUUID) which help developers to differentiate all the M-OBJs, even if they are communicating with the M-Hub under different WPAN technologies. For example, the current implementation of Bluetooth Low Energy (a.k.a. Bluetooth Smart - BLE) is defined with the ID 1.

1. The Mobile Hub source code can be found in: https://bitbucket.org/endler/mobilehub. For repository access, you may ask permission to one of our collaborators:
• Felipe Carvalho: fcarvalho@inf.puc-rio.br
• Vitor Almeida: valmeida@inf.puc-rio.br
• Markus Endler: endler@inf.puc-rio.br
2. And an example implementation of a processing node receiving information from the M-Hub in: https://bitbucket.org/luistlvr/simpleserver

### Troubleshooting

The Mobile Hub makes use of Asper, a version of ESPER(CEP) for Android. When compiling, In some cases (most) it will require some configurations that depending on the IDE could be in the eclipse.ini (Eclipse) or in the studio.vmptions (Android Studio). In the case of Android Studio your file should look as follows:

-server
-Xms512m
-Xmx1024m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=150m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-ea
-Djna.nosys=true
-Djna.boot.library.path=

-Dawt.useSystemAAFontSettings=lcd