Showing posts with label sensor data. Show all posts
Showing posts with label sensor data. Show all posts

24 Nov 2015

IOT : Sensing & Controlling an Android Device through MQTT Messages

In two earlier posts, we had explored how to create (a) LightWatch - an IOT proof-of-concept  for an ambient light sensor based on Android and the XMPP chat protocol and (b) LightWatchMQ - which would essentially do the same thing but use the more popular MQTT protocol. In each case we were essentially trying to simulate an IOT system based on the Android platform that will use native (or external ) sensors attached to the Android device to communicate with a central "controller" machine. This machine could be a simple Android device with the XMPP or MQTT client or could be running a Python program that listens for messages, extracts data and stores the same in a SQL database.

In this application, we, in a sense close the loop! Not only does the Android device transmit data from its sensors but in term it can be controlled to perform a physical activity -- sound a bell or flash its LED light when "instructed" to do so by the central machine.


The sequence of events is as follows :
  1. A custom built app IOT7939 is started on the remote Android device. This measures the ambient light near the device and publishes two messages on the IOT79 topic of a publicly hosted MQTT webserver, eg http:/broker.hivemq.com:1883 or http://test.mosquitto.org:1883
  2. A central MQTT client subscribes to this topic, IOT79, using, for example a websockets client available at http://www.hivemq.com/demos/websocket-client/ or http://test.mosquitto.org/ws.html Both these clients can Publish or Subscribe to their respective brokers. However any third party MQTT client can also be used. Hence data from the Android machine is received here.
  3. If the central MQTT client wants to initiate an activity on the Android device, it publishes a message on the IOT39 topic. The remote Android machine has subscribed to this topic and listens for a message. When the message arrives, three things happen : 
    1. Another publishing activity is triggered on the Android App, as a kind of acknowledgment for the message received and also to transfer fresh sensor data.
    2. A bell mp3 file is played. If the message contains the world "siren" a different alarm mp3 file is played.
    3. The LED flash on the Android is activated for 5 seconds.
While the Publish and Subscribe activities are reasonable easy to build into the app, the flashing light constitutes a challenge. While there are many webposts that explain how to operate the flash on an Android device and even give the sample code,  almost all of them are based on the deprecated camera class of Android and samples with the new camera2 class are not easily available. What this means is that code that runs on one machine may not run on another. For example, the Flashlight code that was used in this application runs happily on my Motorola with Android 5.1 but did not run on my Micromax with Android 6!

Rather than breaking our head on this, what we did was to de-couple the LED-flashing code from the general MQTT Pub/Sub code and created two apps. The LED Flashlight app is a very simple app that "OnStart" switches on the LED, waits for 5 second, switches the LED off and then exits. This app can easily be replaced with any more rugged Flashlight app that has an inbuilt feature to turn-on itself during the start. This LED flashlight app can be called from the main App with a few lines of code, provided we know the package and the activity name.

    String ExternalAppPackage = "org.iothub.flashlight";
    String ExternalAppActivity = "org.iothub.flashlight.MainActivity";
 
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setComponent(new ComponentName(ExternalAppPackage,ExternalAppActivity));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);


Another very interesting feature of this app is that each device on which this app is run, automatically gets its own id derived from the Android ID . This is Published. So messages Published by the central server can contain this Android ID and the app can be modified to parse subscribed message so that each machine ONLY responds to messages that contains its own Android ID. So in effect, the broadcast can be converted into a narrow-cast and target only specific machines.


This screen-shot shows the WebSockets client on the central machine that receives message on IOT79 topic and these messages contain the Android ID as the first field. Also note that when it Publishes on the IOT39 topic, the message is trapped on the Android app and published "back". Since the message can be trapped, it can be parsed and acted upon "intelligently" with a simple if-then-else construct.

In fact, any third party MQTT client can be used to subscribe to and publish messages on the IOT79, IOT39 topics as shown in this screen capture here



The entire code for the main MQTT Pub/Sub app IOT7939 and the auxiliary Flashlight app is available in GitHub code repository.

Android is one of the most widely used platforms in the world and it is very likely that The Smartphone and the Internet of Things will get very closely tied to each in the future. Hence it makes sense to learn and explore how the key features of IOT can be implemented with Android. This was the motivation for building this proof-of-concept. 

30 Oct 2015

Lightwatch : An IOT prototype using XMPP and Android

In two earlier posts, we have shown how to build (a) an XMPP chat client in Python that can listen for incoming messages and, where applicable, store the data in an SQLite database and (b) a XMPP chat client for Android that can transmit data from an Android device. With these two components we are now in a position to build a realistic prototype of an IOT system that will continuously transmit information about ambient light conditions from an Android device.

This prototype will demonstrate all the essential components of an IOT system namely
  • A  physical sensor - in this the light sensor built into an Android device that measures the lux intensity of ambient light
  • A central message broking service -- in this case an Ignite Openfire server that runs an XMPP protocol based messaging service. This is commonly known as an Instant Messaging or Chat server. XMPP is one of the standard protocols used in IOT.
  • A way to securely pass information across multiple devices. Security is established through the userid and password of the logged in users
  • A SQL compliant RDBMS that receives the light intensity data and stores it for future processing.
[ What is IOT ? Ooops ... sorry, please check out this or this :-) to understand why we are doing any of this ! ]

The overall architecture is as follows :


Any Android device has a set of physical sensors, that can be accessed from a program and these can be identified through any standard utility app, like Sensor Box. In this example, we build a sensor app that accesses the light sensor, one of the most widely available sensors, to determine the level of ambient light near the device.

The sensor app opens an XMPP chat dialogue with a controller device, which is any device that supports a generic XMPP chat client, and waits for a signal to transmit data. Once this signal is received, the sensor app opens a second XMPP chat dialogue with the Python listener and keeps sending ambient light data every 5 seconds, in the format that the listener will accept and store in the SQLite database. This continues until the controller device sends a hold signal, when the data transmission is paused. The transmission can be resumed or paused as and when required. Finally, when the controller sends a quit message, the sensor app shuts down.

To build this app, we broadly follow the instructions given in the earlier post on how to build an XMPP chat client for Android. In addition, the code to handle the light sensor is adapted from this page. In this case, the application is called LightWatch and the key files that need to be changed / modified are as follows 
  1. src/org/iothub/lightwatch/LightWatch.java
  2. res/layout/activity_light_watch.xml
  3. res/values/strings.xml
  4. res/drawable/iothub0.9.png
  5. AndroidManifest.xml
All these files are available in GitHub. 

To test out the application we need three Internet connected devices
  1. A Unix machine running the ChatIOT.py application as described in this post. This needs to be started with a XMPP userid / password [ referred to as the ReporterID in the LightWatch.java file]
  2. A controller device (Android, Unix, Windows whatever ) that has a chat client that is logged in with another XMPP userid / password [ referred to as the Controller ID]
  3. An Android device where the LightWatch application is installed. This application needs a third userid / password.
All three userids should be in the same XMPP server, which in our case is adastra.re and should be defined as each others chat "contacts". Otherwise messages will never be delivered or accepted.

If everything works well, the sensor app will send a message to the controller device announcing its presence. From the controller device, the message "xmit" needs to be sent back. This will initiate the transmission of a set of messages like "PUSH <lux value>" to the data store. The data store should accept these and store them in the SQLite database. If you cover the Android device with the LightWatch app with a piece of paper, you will notice a sharp fall in the lux value that is being transmitted. This was the humble goal of this application.

Everything has been tested on a Motorola phone and an Xioami tablet and it all works. 





One problem that happens is when the LightWatch gets paused, the flow of data stops! To overcome this, the app was redesigned with the bulk of the activity migrated into an Android Service. This is the LightWatch2 application that can be built with the following files -- that are available in Github. [ Actually, the entire project itself can be downloaded from here.]
  1. src/org/iothub/lightwatch/LightWatch2.java
  2. src/org/iothub/lightwatch/LightWatchService.java
  3. res/layout/activity_light_watch2.xml
  4. res/values/strings.xml
  5. res/drawable/iothub0.9.png
  6. AndroidManifest.xml
  7. res/drawable/pmbutton.xml
Both the applications work very similarly except that in the case of LightWatch2, the service has to started and stopped by pressing buttons on the main screen. After that the behaviour is similar to the LightWatch.

Building a trivial app for Android is easy but one that involves using XMPP libraries and accessing sensor data is a little more complicated. The initial effort required in setting up the process is significant, but once this done, the rest follows relatively smoothly. If you want to set up a small IOT system that is described here, follow the sequence of posts given in this blog.

  1. Build the python chat listener - chatiot.py
  2. Set up your Eclipse environment for Android
  3. Build a basic XMPP client app for Android
  4. Then do what is explained in this blog!
Where can this technology be used ?

One obvious application is in smart cities, where we can measure parameters like air pollution on a continuous basis using tools like Aircast as explained in this blog post.

9 Sept 2015

DIY IOT : Collecting Remote Data over the Internet

One of the primary requirements for IOT - the "Internet of Things" is to collect data from remote devices over a TCP/IP internet connection and use the same for  analysis. Since the number of devices is expected to be very large -- far larger than the the number of IPv4 IP addresses that are possible, it is expected that IPv6 addressing will be used. However the sluggish rollout of IPv6 enabled network devices has necessitated the usage of intermediate "broker" services that allow the collection of data from devices and then publish the same for subsequent analytics.



This post will describe the architecture of such a system and provide sample codes that can be used to get a basic IOT Sensor Data collection.

Since the data will be travelling over the internet, the edge device must be a TCP/IP enabled computing device to which the sensor is connected. The simplest possible computer would be a Raspberry Pi2 or Arduino Yún  or similar machine, running on some lightweight flavour Unix or Linux. So in this case the sensor will be simulated by a small shell program that, in this case, emits two pieces of data (a) a sensor ID and (b) a numeric value, of temperature or pressure or voltage, that has been recorded by the sensor. With a real sensor device, this program will collect, or read it, from the sensor through a device driver program.

Once the data is available to a shell program ( we will call it ISD_pushData.sh ) it must be pushed into a central server and the easiest way to do it is using the curl command that is available in any Unix distribution. Where does one find such servers?

Companies like Carriots and GroveStream offer services that allows one to define a "device" that uses curl to send data in JSON or XML format to a datastream where it is stored for subsequent analysis. Carriots in fact offers a free service in which one can connect up to ten devices from which to collect, store and display data. Simple tutorials are available through which one can learn "How to send a stream using curl" and "How to create triggers" that will initiate actions based on the value of data that is received.

After working through these tutorials it becomes very evident that a similar service can be created on a Apache/MySQL/PhP platform that is widely available from any webhosting service like x10hosting or hostinger. The free versions are good enough for our purpose. This post in tweaking4all shows how this can be done and is forms the basis of this post.

What we need is (a) MySQL table to store the data (b) a shell program that will send data using curl to a destination URL on the web server and (c) a PhP program, available at the destination URL, that will accept data passed as parameters and insert it into the MySQL table.

The SQL command to create the MySQL table looks like this : ( Create_IOT_SensorData.sql)

CREATE TABLE `IOT_SensorData` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'unique ID',
`event` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Event Date and Time',
`sensorID` VARCHAR(30 ) NOT NULL COMMENT 'Unique ID of the sensor',
`Value` NUMERIC( 4,1 ) NOT NULL COMMENT 'Value of data recorded'
);


This PhP program (ISD_pushData.php) that sits on the web server and accepts the data

<?php
    // Connect to MySQL
    include("dbConnect.php");

    $con = mysql_connect($MyHostname, $MyUsername, $MyPassword) or die(mysql_error());
    if (!$con)
     {
       die("Could not connect: 1" . mysql_error());
     }
     mysql_select_db($MyDBname) or die(mysql_error());

    // Prepare the SQL statement
    $SQL = "INSERT INTO IOT_SensorData (sensorID ,Value) VALUES ('".$_GET["sensorID"]."', '".$_GET["Value"]."')";  
    
    // Execute SQL statement
    mysql_query($SQL,$con);
    
    // Send Mail
    $mailMSG = $SQL;
    $mailDEST = "someone@somewhere.com";
    if ($_GET["Value"] > 50){
      $mailSUB = "Warning : Value HIGH";
      } else {
      $mailSUB = "Value Normal";
      }
    mail($mailDEST,$mailSUB,$mailMSG);

?>


The PhP program  on the web server accepts the data from the following shell (ISD_pushData.sh) program, running on the remote Linux machine. Instead of reading a value from the sensor, the program is generating a random number and sending it.

p1="http://prithwis.x10.bz/IOT/ISD_pushData.php?sensorID="
sensorID="1003B"
p2="&Value="
Value=$(shuf -i 1-80 -n 1)   # random number being generated for Value
URL=$p1$sensorID$p2$Value
echo $URL
# -------------------------------------------------------
curl $URL


In fact, the PhP push program on the server is not only inserting the data into the MySQL table but is also acting as a trigger by sending two different types of mail depending on the value of the data that is received from the remote sensor.

Once the data is available in the MySQL table, it can be displayed (using ISD_viewData.php) as

In fact, one can run the shell script on any machine and the new value will appear when this pages is refreshed!

It is also possible to visualize the data graphically (using ISD_graphData.php)

All the codes used in creating this post are available on Github. The graph has been created with free tools available from JpGraph and the specific graph shown here is based on the sample shown here.

In this post we have demonstrated how data lying on remote Linux machine ( that is possibly connected to a physical sensor ) can be pushed into webserver and subsequently used for data analytics.