Showing posts with label MQTT. Show all posts
Showing posts with label MQTT. Show all posts

Thursday, June 19, 2014

DHT Subscriber - MQTT Arduino Gateway

Use WMQTT Utility to Subscribe Uploaded DHT-11 Temperature & Humidity Data


Download WMQTT Utility

http://www14.software.ibm.com/cgi-bin/weblap/lap.pl?popup=Y&li_formnum=L-TMAN-5N7JL9&accepted_url=ftp://public.dhe.ibm.com/software/integration/support/supportpacs/individual/ia92.zip
Dowload ia92.zip. No need to install, you just need to unzip.

For example, if you unzipped in C:\Evaluation\preview\MQTT\ia92 in DOS Box
cd C:\Evaluation\preview\MQTT\ia92\J2SE
java -jar wmqttSample.jar

Manual is in page 49 of IBM MQTT RedBook. (The page number refers to PDF Viewer's page)


Subscribe

Broker TCP/IP address - broker.mqttdashboard.com
Connect, if green light turns on,
Subscribe Topic - DHT11/temphum
and you will see DHT-11 Temperature & Humidity data in History


Subscribe Using WebSocket

For full source code refer to the link at the bottom.

If you want to see only the MQTT part -> https://gist.github.com/matbor/8837988



<!DOCTYPE html>
<html>
  <head>
    <title>Temperature & Humidity Subscriber</title>
    
    <script type="text/javascript" src="jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="globalize.min.js"></script>
    <script type="text/javascript" src="dx.chartjs.js"></script>
    <script type="text/javascript" src="knockout-3.0.0.js"></script>
    <script type="text/javascript" src="mqttws31.js"></script>
    
    <script type="text/javascript">
        var client;
        var t, h;

        $(document).ready(function() {
            t = $('<div style="width: 50%; height: 100%; float: left;" />').appendTo('#chartContainer');
            h = $('<div style="width: 50%; height: 100%; float: left;" />').appendTo('#chartContainer');
            var options = { scale: { startValue: 0, endValue: 40, majorTick: { tickInterval: 5}} };

            t.dxCircularGauge($.extend(true, {}, options, {
                geometry: { startAngle: 180, endAngle: 90 },
                value: 0,
                rangeContainer: {
                    ranges: [
                      { startValue: 28, endValue: 40, color: '#CE2029' },
                      { startValue: 0, endValue: 10, color: '#0077BE' }
                  ]
                },
                valueIndicator: { type: 'rangeBar' },
                title: { text: 'Temperature' },
                scale: {
                    label: { customizeText: function(arg) {
                    return arg.valueText + '&deg;C';
                    }
                    }
                }
            }));

            h.dxCircularGauge($.extend(true, {}, options, {
                scale: { startValue: 100, endValue: 0, majorTick: { tickInterval: 10 },
                    label: { customizeText: function(arg) {
                        return arg.valueText + '%';
                    }
                    }
                },
                geometry: { startAngle: 90, endAngle: 0 },
                value: 0,
                valueIndicator: { type: 'rangeBar' },
                rangeContainer: {
                    ranges: [
                        { startValue: 33, endValue: 0, color: '#77DD77' },
                        { startValue: 67, endValue: 33, color: '#E6E200' },
                        { startValue: 100, endValue: 67, color: '#92000A' }
                    ]
                },
                title: { text: 'Humidity' }
            }));
        });

        client = new Messaging.Client("broker.mqttdashboard.com", 8000, "HTMLTempHumSensor" + parseInt(Math.random() * 100, 10));

        // Connection Lost Message
        client.onConnectionLost = function(responseObject) {
            alert("Connection Lost: " + responseObject.errorMessage);
        };

        // Message Arrival
        client.onMessageArrived = function(message) {
            var data = message.payloadString.split(",");
            var temperature = parseInt(data[0]);
            var humidity = parseInt(data[1]);
            $(t).dxCircularGauge('instance').value(temperature);
            $(h).dxCircularGauge('instance').value(humidity);
        };

        // Connect Options
        var options = {
            timeout: 3,
            onSuccess: function() {
                alert("Connected");
            },
            onFailure: function(message) {
                alert("Connection failed: " + message.errorMessage);
            }
        };

        var publish = function(payload, topic, qos) {
            var message = new Messaging.Message(payload);
            message.destinationName = topic;
            message.qos = qos;
            client.send(message);
        }
        
    </script>
  </head>
  
  <body>
    <div id="chartContainer" style="height:450px;width:1000px;" align="center"></div>
    
    <table width="1000px">
      <tr>
        <td align="right">
          <button type="button" style="width:200px;" onclick="client.connect(options);">
            Connect
          </button>
        </td>
        <td align="center"> 
          <button type="button" style="width:200px;" onclick="client.subscribe('DHT11/temphum', { qos: 2 }); alert('Subscribed');">
            Subscribe
          </button>
        </td>
        <td align="left">
          <button type="button" style="width:200px;" onclick="client.disconnect();">
            Disconnect
          </button>
        </td>
      </tr>
      
      <tr>
        <td colspan="3">
          <div id="messages"></div>
        </td>
      </tr>
    </table>
  </body>
</html>



Full codes can be found in following links





Wednesday, June 18, 2014

DHT Publisher - MQTT Arduino Gateway

Uploading DHT-11 Temperature & Humidity Data using MQTT

Refer to Log Data Upload - Humidity & Temperature Web Logger posting for more information about Arduino & DHT-11.


Download MQTT Publisher Library for Arduino



Choose MQTT Broker

There are several public MQTT brokers; however, we are going to use HTML/JS to see Temperature & Humidity Data thus we need to use WebSocket.
I am going to use broker.mqttdashboard.com because it supports WebSocket.
IP is 212.72.74.21

Other good Brokers:
  • m2m.eclipse.org (IP: 198.41.30.241)
  • test.mosquitto.org (IP: 85.119.83.194)

If you want your own Broker, use Mosquitto.
Install and run mosquitto.exe.


TOPIC NAME

broker.mqttdashboard.com only supports 1 sub-tree, which means that it is possible to use "DHT11/temphum" as TOPIC, but "DHT11/temphum/room" will not work.



For full source code refer to the link at the bottom.
#include <SPI.h>
#include <Ethernet.h>
#include <dht.h>
#include <PubSubClient.h>

#define DHT11_PIN     A0
#define POLLINTERVAL  10000   // 10seconds interval

#define CLIENTID      "ArduinoTempHumSensor"
#define TOPICNAME     "DHT11/temphum"

byte mac[]    = { 0x90, 0xA2, 0xDA, 0x0F, 0x25, 0xC4 };
byte server[] = { 212, 72, 74, 21 };    // "broker.mqttdashboard.com"

dht DHT;

PubSubClient arduinoClient(server, 1883, callback); // We don't use it

char charSensorVal[20];
double humidity    = 0.0; // Sensed Humidity
double temperature = 0.0; // Sensed Temperature
int seq = 0;


void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  
  // Connect to the MQTT Server - broker.mqttdashboard.com
  beginConnection();
}

void loop() {
  if((millis() % POLLINTERVAL) == 0) {
    if(getSensorVal()){
      dtostrf(temperature, 5, 2, charSensorVal);
      charSensorVal[5] = ',';
      dtostrf(humidity, 5, 2, charSensorVal + 6);
      // One line publishing
      arduinoClient.publish(TOPICNAME, charSensorVal);
      Serial.print(seq++);
      Serial.print(":");
      Serial.println(charSensorVal);    
    }
  }
}

void beginConnection() {

  Serial.println("Try connect to MQTT server");    
  
  int connRC = arduinoClient.connect(CLIENTID); // MQTT Broker connection
  
  if(!connRC) {
    Serial.println(connRC);
    Serial.println("Could not connect to MQTT Server");
    
    delay(100);
    exit(-1);
  }
  else {
    Serial.println("Connected to MQTT Server...");
  }
}

void callback(char* topic, uint8_t* payload, unsigned int length) {}

byte getSensorVal() {
  if(DHT.read11(DHT11_PIN) == DHTLIB_OK) {
    humidity = DHT.humidity;
    temperature = DHT.temperature;
    return 1;
  }
  else return 0;
}
Full codes can be found in following links






Saturday, June 14, 2014

Introduction - Heart Rate Monitor by MQTT

The wristband looks splendid, but the accuracy of measurement is apparently crappy.

Do wristband heart trackers actually work? A checkup.
According to the above link, finger tip works the best (Samsung Galaxy S5).

Performance wise we can say: finger tip > chest strap > wristband.
Wristband is is most wearable.
Unless you are planning on doing intense workout chest strap seems inconvenient.
Getting further into it will just be a waste of time.
Thus I'm going to ignore how pretty each things are and get into how each things will be implemented (if we start getting into how to make things more prettier, we will be creating super thimble at some point).



1. Photoplethysmographic Sensor



It calculates heart rate using the change in reflectance of light source as blood pressure changes.
There are plenty of cases relating to this on the internet.

Few examples:
Apparently all the batteries will be used by IR LED.
In normal condition we should constantly increase the measuring rate, and in abnormal condition we are in emergency state anyways.
In that condition battery should not be the problem, thus let's assume that we are going to measure constantly.



2. Bluetooth

Due to problem with battery we will have to use Bluetooth Low Energy (BLE), which only has 10 m long output power ( it will decrease even more because we are using PCB antenna ).
Depending on the situation we might have to use 2 APs.
The protocol will be MQTT-SN.



3. Battery

If we want to use Bluetooth to keep 24/7 watch, it will be impossible to use same battery for months.
Henceforth, when we are picking elegant design while increasing the volume we can use Lithium Polymer (Li-Po) battery.
Or even later on when we are mass producing we can customize the battery shape so that it fits into the case ( This is the ultimate goal ).
Two set of heart rate monitor should be one package, so that when one is being used the other can be charging.
Then it should contain a LED light that will let you know when the charging is needed.




4. MQTT

I'm going to use MQTT, because I don't need to build separate Service Server.
People who have huge interest in someone's heart can just register as subscriber to the broker.
If there is problem, Broker will send an e-mail or SMS immediately.
If there is no message, you could ask Broker.
However, the most simple way will be to call the person directly.




Friday, June 13, 2014

Summary of MQTT

MQTT (Message Queue Telemetry Transport)

The official Website

http://mqtt.org/

The final version of MQTT is 3.1


The final version of MQTT-SN (SN or S, Sensor Network) is 1.2
The client is WSN node (Wireless Sensor Network, like ZigBee), and we need broker like MQTT-S Gateway.

The spec sheet for MQTT is only 42 pages long and MQTT-S is only 28 pages long.

PT Informations to Help you Understand Better

Low Latency Messaging for Mobile Apps or When HTTP and Push Notification are Simply Not Enough
Building WSN with MQTT, RPi & Arduino

MQTT - MQ Telemetry Transport
Connecting Cars with IoT MQTT

Important Documents

IBM MQTT RedBook.  
Building Smarter Planet Solutions with MQTT and IBM WebSphere MQ Telemetry



Tips

.MQTT uses Network Byte / Bit ordering. (MSB is equal to bit<0>)
However, remaining length is in LSB-MSB order.