Showing posts with label Arduino. Show all posts
Showing posts with label Arduino. 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






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.





Wednesday, June 11, 2014

Construct - Arduino Remote Sensor Logger



There is not much difference from Components - Arduino Web Logger posting after adding Arduino.
Ethernet Shield has been replaced for WiFi Shield and RS-485 Shield is replaced by nRF24LE1 Shield.

Let's focus on Temperature Remote Sensor.
It is composed of 3 parts.

  1. Temperature Sensor
  2. RF Sender
  3. Battery

Temperature Sensor

I'm going to use TMP451 from TI.
This is introduction on their site.  http://www.ti.com/product/tmp451
And the following is the datasheet.  http://www.ti.com/lit/ds/symlink/tmp451.pdf


If you look at Power, it doesn't exceed 500 uA.
This is perfect for Battery.



Sending RF

I'm going to use nRF24LE1 from Nordic.
This is the chip that has been used in wireless mouse, keyboard, and remote controller for long time.
For this model, you can program internal 8051, thus you don't need additional Controller.
Power ranges from 1.9 V - 3.6 V, which is perfect for battery. I assume the price will be perfect also.
This is introduction for this model.  http://www.nordicsemi.com/eng/Products/2.4GHz-RF
And the following is the datasheet.  http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24LE1

However, power consumption rate could be a bit better.
If we add more peripherals it will exceed 20 mA.



Battery

I am wanting Battery that will last at least a year.
We are going to use it once in every 10 minutes and it will be used for 10 seconds using 20 mA.
Using simple math:
20 mA * 10 seconds * 6 times / hours * 24 hours * 365 days = 10,512,000 mA / sec = 2920 mAH
Thus we need Battery with size 3000 mAH.
3000 mAH is very common in AA size batteries now.
In Alkaline, DURACELL Normal or Energizer will be good enough.
There are lots of nikel-hydride battery, http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24LE1
However, the size of AA is not that small.  Thus the size of remote sensor will be the size of AA battery.  Of course the weight will be the same as AA battery.





Tuesday, June 3, 2014

Data Upload from Arduino - Arduino Web Logger

The Arduino WebSocket we used limits the size of packet we can send.  We are unable to receive entire 512 bytes Block, even if we divided it into 3, from the WebSocket.

Thus we are going to change the protocol so we are sending each Data item one-by-one.

Get Last Data Block Number

If we send "GET0", we receive N = <Data Block Number>.


<Data Block Number> 

is unsigned 32 bit integer ranging from "N = 1" to "N = 4294967295"
Of course it doesn't get that big.
In the source code from Data Log Code posting, SD_BASE_BLOCK (1024) is equal to 0.


Get Data Block

If we send "GETn", we receive
  • N = <Data Block Number>
  • T = <time stamp>
  • D = <data>
<time stamp> uses sec part from POSIX time_t.
Because we don't use the millisecond part, we need to *1000.
"T = 4294967295". Of course it will be hard to see this number in your lifetime.

<data> has +dd.ddd format.
  • "D=+12.345"
  • "D=": when there is no data
  • "D=-99.999": termination. Data Block has finished.

Original Protocol

Digital Out

  • Turning On: "DOn=ON"
  • Turning Off: "DOn=OFF"
n is equal to Channel number which is between 0 and 7, and there is no reply.

Digital In

When you send "DI" it replies with "bbbbbbbb".  b is equal to each input channel and it is either '0' or '1'.

Analog In

When you send "AIn" it replies with "+dd.ddd". n is equal to channel number which is between 0 and 7, and "+dd.ddd" ranges from -10.000 to +10.000.

Below I am only excerpting codes related to uploading.  Refer to the link at the bottom for entire code.
// -------------------------------- Data Uploading Function
void upload_lastBlockNo(void);
void upload_DataBlock(uint32_t reqBlock);
byte *setTerminator(byte *pD);

/*
 ----------------------------------------------------------
 D A T A  U P L O A D I N G  Function
 ----------------------------------------------------------
*/

/*
 0         1
 012345678901 last data block number 12 bytes send
 N=4294967295

 0         1
 012345678901 time stamp 12 bytes send
 T=4294967295

 012345678 Data 9 bytes send
 D=+99.999
 D=        empty
 D=-99.999 terminator
*/
void xsfBlockNo(uint32_t block) {
 ltoa(block - SD_BASE_BLOCK, printLn + 2, 10);
 printLn[0] = 'N';
 printLn[1] = '=';
 WSsend(printLn, strlen(printLn));
}

void upload_loastBlockNo(void) {
 xsfBlockNo(currBlock - 1);
}

void upload_DataBlock(uint32_t reqBlock) {
 byte *pS;
 int cnt;
 float data, *pF;

 // Store the currently logging Block into SD.
 // We might lose packets that ADAM-4017 is receiving.
 sdCard.writeBlock(currBlock, sdBuffer);

 printLn[1] = '=';

 if(sdCard.readBlock(reqBlock, sdBuffer)) {
  pS = sdBuffer;

  if(*((uint32_t*)pS) == USED_MARK) {
   pS += 4;

   // block number
   xsfBlockNo(reqBlock);

   // time stamp (milliseconds)
   ltoa(*((uint32_t*)pS), printLn + 2, 10);
   printLn[0] = 'T';
   WSsend(printLn, strlen(printLn));
   pS += 4;

   // data
   printLn[0] = 'D';
   pF = (float*)pS;
   cnt = 120;

   while(cnt--) {
    data = *pF++ / 10.0;

    if(data != -99.999)
     dtostrf(data, 7, 3, printLn + 2);
    else
     printLn[2] = 0x00;

    WSsend(printLn, strlen(printLn));
   }
  }

  printLn[0] = 'D';
  setTerminator((byte*)(printLn + 2));
  WSsend(printLn, strlen(printLn));
 }

 // Reload the block that we have stored.
 sdCard.readBlock(currBlock, sdBuffer);
}

//---------------------------------------------------------
byte *setTerminator(byte *pD) {
 *pD++ = '-';
 *pD++ = '9';
 *pD++ = '9';
 *pD++ = '.';
 *pD++ = '9';
 *pD++ = '9';
 *pD++ = '9';
 *pD++ = 0x00;
 return pD;
}

/*
  ---------------------------------------------------------
  W E B S O C K E T   h a n d l e r
  ---------------------------------------------------------
*/

void onData(WebSocket &socket, char* rxLn, byte rxSz) {
 uint32_t block;

 if((rxLn[0] == 'G') && (rxLn[1] == 'E') && (rxLn[2] == 'T')) {
  *(rxLn + rxSz) = 0x00;
  block = atol(rxLn + 3);
  
  if(block)
   upload_DataBlock(block + SD_BASE_BLOCK);
  else
   upload_lastBlockNo();
 }
}

HTML/JS code for Upload Testing



<!DOCTYPE html>
<html>
<head>
    <title>WebLogger 5.0</title>

    <script type="text/javascript" src="jquery-2.0.3.min.js"></script>
    <script>
        var ws;
        var rcvCnt;

        $(document).ready(function() {
            WebSocketConnect();
        });

        function WebSocketConnect() {
            var ar = new Array();
            var arSz, i;

            try {
                ws = new WebSocket('ws://192.168.219.16:80/');
                ws.onopen = function() {
                    status('Connected...');
                }

                ws.onclose = function() { status('Closed...'); }
                ws.onerror = function(evt) { status('Error ' + evt.data); }
                ws.onmessage = function(evt) {
                    ar = evt.data.split('=');

                    // receive Last Data Block Number  
                    if (ar[0] == 'N') {
                        $("#lastBlockNo").empty();
                        $("#lastBlockNo").append('Last Block Number:' + ar[1]);
                    }

                    // receive Time Stamp
                    if (ar[0] == 'T') {
                        $("#timestamp").empty();
                        $("#timestamp").append('TimeStamp(milliseconds):' + ar[1]);
                    }

                    // receive Data Block
                    if (ar[0] == 'D') {
                        $("#RcvLn").append('<p>' + ar[1] + '<p>');

                        if (ar[1] == '-99.999') {
                            $("#recordCnt").empty();
                            $("#recordCnt").append('Record Count:' + rcvCnt);
                        }

                        rcvCnt++;
                    }
                }
            } catch (exception) { status('Exception' + exception); }
        }

        function upload_lastBlockNo() {
            ws.send("GET0");
        }

        function upload_DataBlock() {
            var recNo = document.getElementById("getRecordNo").value;
            ws.send("GET" + recNo);
            rcvCnt = 0;
            $("#timestamp").empty();
            $("#recordCnt").empty();
            $("#RcvLn").empty();
        }

        function status(str) {
            $("#status").empty();
            $("#status").append(str);
        }

    </script>

</head>
<body>
    <p id="status"></p>
    <button type="button" onclick="upload_lastBlockNo()">Get Last Data Block Number</button>
    
    <br />
    
    <input type="text" id="getRecordNo" value="1">
    <button type="button" onclick="upload_DataBlock()">Get Data Block</button>
    
    <p id="lastBlockNo"></p>
    <p id="timestamp"></p>
    <p id="recordCnt"></p>
    <p id="RcvLn"></p>
</body>
</html>

Full codes can be found in following links





Saturday, May 31, 2014

Components - Arduino Web Logger

Diagram of Arduino Web Logger Component

Let's log ADAM-4017's AD value every 500 ms.
We are going to make 512 bytes long block every 1 minute and write that block to the SD card in Ethernet Shield.

Data Block Component.

  • Used Flag: 4 bytes
    Set it to 0xaa55a55a.
  • Time Stamp: 4 bytes
    This is only the sec part of POSIX time_t value.  We are not going to use the millisecond, thus we are going to multiply the value by 1000 (*1000).  It is 32 bit unsigned integer.
  • Data: 4 bytes float value.  It is going to be sampled twice every second.
    1 minute measurement: 2 * 60 * 4 = 480 bytes
    Second is going to be offset.
    For example, The offset for second measurement in 27 second will be 8 + 27 * 8 + 4 = 228.
    Set the unmeasured values to -99.999.  When initializing the block set everything to -99.999.
  • Backup: 24 bytes, set it to Null.

Data File.

Logging is going to be one File.

In FAT32, the biggest file size is 512 * 232 = 241 = 2,199,023,255,552 = 2GB.  Even the smallest SD card is bigger than 2GB.  With 2GB, we can log for 2,199,023,255,552 / 512 / 60 / 24 / 365 = 8,217 years.  Thus memory is going to be full approximately after 8,000 years so we don't have to worry about that.

Data inside File are going to be in time order, which will allow us to retrieve Data Block from certain time very quickly using the simplest Binary Search.  However, adjusting the RTC clock due to whatever reasons will screw this up.  ( Getting deeper into this is too much for this posting, so I am going to skip it. )

Web DB.

Arduino cannot hold all this log data like Browser might hope.  If the browser wants to look through a year long data "very quickly" it's impossible.  Thus, browser is going to keep log data in its database and once in a while connect with Arduino to get the most recent log and update its DB.





Monday, May 26, 2014

Input Polling from Arduino - Web/Arduino/Adam

Let's poll continuously from ADAM-4050 from Arduino using RS-485.
If there is an input change from ADAM, we send it to the browser.

We are going to add or modify the following from WSAdam.ino.

omit...
char rx485Ln[8];
char preAdamPollRcv[2] = { 0, 0 };
int rx485ix;
char bitMap[8];
byte wsConnect;
long lastPollTime;

void XsfAdamPollData(void);
void AdamPoll(void);
void AdamReceiver(void);
void hexToBit(char hex, int p);

omit...
void setup() {
 Serial.begin(9600);
 Soft485.begin(9600);
 pinMode(DE485, OUTPUT);
 wsConnect = 0;
 lastPollTime = 0;
 Ethernet.begin(mac, ip);

omit...
void loop() {
 wsServer.listen();
 if((millis() - lastPollTime) >= 500)
  AdamPoll(); // Poll every 0.5 seconds
 AdamReceiver();
}

omit...
void onConnect(WebSocket &socket) {
 Serial.println("OnConnect called");
 wsConnect++;
}

void onDisconnect(WebSocket &socket) {
 Serial.println("onDisconnect called");
 wsConnect = 0;
}

omit...
 //else if(rxLn[1] == 'I') {
  //digitalWrite(DE485, HIGH);
  //Soft485.write("$006");
  //Soft485.write(0x0D);
  //digitalWrite(DE485, LOW);
 //}
 else if(rxLn[1] == 'I')
  XsfAdamPollData();
}

void XsfAdamPollData(void) {
 hexToBit(preAdamPollRcv[0], 0);
 hexToBit(preAdamPollRcv[1], 4);
 wsServer.send(bitMap, 8);
}

void AdamPoll(void) {
 digitalWrite(DE485, HIGH);
 Soft485.write("$006");
 Soft485.write(0x0D);
 digitalWrite(DE485, LOW);

 lastPollTime = millis();
}

omit...
 if(rx485ix == 6) { // !ooii00<cr>
  //hexToBit(rx485Ln[2], 0);
  //hexToBit(rx485Ln[3], 4);
  //wsServer.send(bitMap, 8);

  // send only if previous input and current input is different.
  if((preAdamPollRcv[0] != rx485Ln[2]) || (preAdamPollRcv[1] != rx485Ln[3])) {
   preAdamPollRcv[0] = rx485Ln[2];
   preAdamPollRcv[1] = rx485Ln[3];
   if(wsConnect)
    XsfAdamPollData();
  }
 }

We are going to modify HTML/JS a little bit.
Use the following source when modifying: https://github.com/michelleseo/Arduino_Web/blob/master/WSAdam/WSAdam1_0.html

omit...
//        ws.onopen = function() { status('Connected...'); }
        ws.onopen = function() {
            status('Connected...');
            DI(); // Read Input once when connected.
        }

omit...
    <!--We do not need Update Button anymore.-->
    <!--<button type="button" onclick="DI()">IN Refresh</button>-->

Full codes can be found in following links







Sunday, May 25, 2014

Input Polling from a Browser - Web/Arduino/Adam

When Input Polling from a Browser...


The previous code updated input condition when [IN Refresh] button was clicked. Now we are going to change it so that it updates continuously.

We are going to fix the following parts:

omit...
<script>
    var ws;
    var poll = 0;
    var intervalTimer;
    var InLamp = new Array();
    for (var i = 0; i < 8; i++)
        InLamp[i] = '#DI' + (7 - i) + '_c';

omit...
//    ws.onopen = function() { status('Connected...'); }
    ws.onopen = function() {
        status('Connected...');
        // When WebSocket connects, polling starts.
        DI_pollEnable();
    }

omit...
//    function DI() { ws.send("DI"); }
    
    function DI_poll() {
        ws.send("DI");
        // Polls every 500 ms.
        intervalTimer = setTimeout(function() { DI_poll() }, 500);
    }
    
    function DI_pollEnable() { // Start polling
        if (!poll) {
            poll++;
            DI_poll();
        }
    }
    
    function DI_pollDisable() { // End polling
        clearTimeout(intervalTimer);
        poll = 0;
    }

omit...
    <!--<button type="button" onclick="DI()">IN Refresh</button>-->
    <button type="button" onclick="DI_pollEnable()">Input Refresh ON</button>
    <button type="button" onclick="DI_pollDisable()">OFF</button>
</body>

Full codes can be found in following links





Saturday, May 24, 2014

HTML / JavaScript - Web/Arduino/Adam

Screen Capture of WSAdam1_0.html

Let's simplify the HTML code.

Create
ws = new WebSocket('ws://192.168.219.16:80/');

Method
ws.send("DI"); // sends message
ws.close(); // Not used this time

Event
ws.onopen = function() { status('Connected...'); }
ws.onclose = function() { status('Closed...'); }
ws.onerror = function(evt) { status('Error ' + evt.data); }
ws.onmessage = function(evt) { // function that receives message

Reference: http://www.tutorialspoint.com/html5/html5_websocket.htm


<!DOCTYPE html>
<html>
    <head>
        <title>ADAM-4050 1.0</title>
        <!--It seemed to be a waste to download it everytime, 
        so I included the file.-->
        <script type="text/javascript" src="jquery.js"></script>
        <script>
            var ws;
            var InLamp = new Array();

            for (var i = 1; i < 8; i++)
                InLamp[i] = '#DI' + (7 - i) + '_c';

            // This is the code that browser calls when done
            // loading HTML/JS code.
            $(document).ready(function() {
                var i = 0;
                var html = 'ON <br />';

                // This is the code for making ON buttons in HTML.
                // The same code is repeated.
                for (i = 0; i < 8; i++)
                    html += '<button type="button" onclick="DO_On(' + i + ')">DO ' + i + '</button>';
                $('#OutONbutton').append(html);

                // This is the code for making OFF buttons in
                // HTML.
                html = 'OFF<br/>';
                for (i = 0; i < 8; i++)
                    html += '<button type="button" onclick="DO_Off(' + i + ')">DO ' + i + '</button>';
                $('#OutOFFbutton').append(html);

                // This is the code for drawing Input circles in
                // HTML.
                html = '<table><tr align="center">';
                for (i = 0; i < 7; i++)
                    html += '<td><svg height="50" width="50"><circle id="DI' + i + '_c" cx="25" cy="25" r="20" stroke="black" fill="white"/></svg></td>';
                html += '</tr><tr align="center"><td>DI 0</td> <td>DI 1</td> <td>DI 2</td> <td>DI 3</td> <td>DI 4</td> <td>DI 5</td> <td>DI 6</td></tr></table>';
                $('#InputLamp').append(html);

                // Now connect the WebSocket.
                WebSocketConnect();
            });

            function WebSocketConnect() {
                try {
                    ws = new WebSocket('ws://192.168.219.16:80/');

                    ws.onopen = function() {
                        status('Connected...');
                    }
                    ws.onclose = function() {
                        status('Closed...'); 
                    }
                    ws.onerror = function(evt) {
                        status('Error ' + evt.data); 
                    }

                    ws.onmessage = function(evt) {
                        for (var i = 1; i < 8; i++) {
                            if (evt.data[i] == '0')
                                $(InLamp[i]).css("fill", "white");
                            else
                                $(InLamp[i]).css("fill", "red");
                        }
                    };
                }
                catch (exception) {
                    status('Exception ' + exception);
                }
            }

            function DO_On(chn) { ws.send('DO' + chn + '_ON'); }
            function DO_Off(chn) { ws.send('DO' + chn + '_OFF'); }
            function DI() { ws.send("DI"); }
            function status(str) { $("#status").append(str); }
            
        </script>
    </head>
    <body>
        <p id="status">Connection Status: </p>
        <p id="OutONbutton"></p>
        <p id="OutOFFbutton"></p>
        <p id="InputLamp"></p>
        <button type="button" onclick="DI()">IN Refresh</button>
    </body>
</html>


Full codes can be found in following links









Friday, May 23, 2014

Arduino Code(2) - Web/Arduino/Adam

Let's make a very simple protocol to use for WebSocket.

For Digital Out:
     Turning on: "DOn=ON"
     Turning off: "DOn=OFF"
     n: channel number 0-7

For Digital In:
     If you send "DI" it returns "bbbbbbbb".
     'b' is each input channel. It either becomes '0' or '1'.


#include <SPI.h>
#include <Ethernet.h>
#include <WebSocket.h>
#include <SoftwareSerial.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x25, 0xC4 };
byte ip[] = { 192, 168, 219, 16 };
WebSocket wsServer;

int DE485 = 2;
SoftwareSerial Soft485(3, 4);

char rx485Ln[8];
int rx485ix;
char bitMap[8];

void AdamReceiver(void);
void hexToBit(char hex, int p);

void setup() {
 Serial.begin(9600); // Arduino Sketch Serial Monitor

 Soft485.begin(9600);
 pinMode(DE485, OUTPUT);

 Ethernet.begin(mac, ip);
 wsServer.registerConnectCallback(&onConnect);
 wsServer.registerDataCallback(&onData);
 wsServer.registerDisconnectCallback(&onDisconnect);
 wsServer.begin();
 delay(100);

 rx485ix = -1;
}

void loop() {
 wsServer.listen();
 AdamReceiver();
}

void onConnect(WebSocket &socket) {
 Serial.println("onConnect called");
}

void onDisconnect(WebSocket &socket) {
 Serial.println("onDisconnect called");
}

void onData(WebSocket &socket, char* rxLn, byte rxSz) {
 // Digital Out
 // It is either "DOn=ON" or "DOn=OFF". n = "0" - "7"
 // It would really be nice if we can parse "DO", "=ON",
 // "=OFF"; however, we are not focusing on this.
 // In "DO" we are only checking for "O" and for "=ON" & 
 // "=OFF", we will only check for "N".
 if(rxLn[1] == 'O') {
  // RS-485 will be in TX mode when DE is high
  digitalWrite(DE485, HIGH);
  // We send to ADAM-4050 "#001n01"<cr> if ON or
  // "#001n00"<cr> if OFF.
  Soft485.write("#001");
  Soft485.write(rxLn[2]); // n = "0" - "7"
  Soft485.write('0');
  if(rxLn[5] == 'N')
   Soft485.write('1');
  else
   Soft485.write('0');
  Soft485.write(0x0D);
  digitalWrite(DE485, LOW); // When finished, DE must be low
 }

 // Digital In
 // We are only looking for "I" in "DI"
 else if(rxLn[1] == 'I') {
  digitalWrite(DE485, HIGH);
  Soft485.write("$006"); // We send "$AA6"<cr> to ADAM-4050
  Soft485.write(0x0D);
  digitalWrite(DE485, LOW);
 }
}

// ADAM-4050 sends "!ooii00"<cr> as reply.
// The message starts with "!" and ends in <cr>, and there are 6
// bytes in between. The input data are the "ii". For more 
// information look at ADAM - Web/Arduino/Adam posting.
void AdamReceiver(void) {
 char rxChr;

 if(Soft485.available()) {
  rxChar = Soft485.read();
  if(rxChr == '!')
   rx485ix = 0; // message starts with "!"
  else if(rx485ix >= 0) {
   if(rxChr == 0x0d) { // message ends with <cr>
    //!ooii00<cr> Between "!" and <cr> there needs to be
    // 6 bytes
    if(rx485ix == 6) {
     hexToBit(rx485Ln[2], 0);
     hexToBit(rx485Ln[3], 4);
     wsServer.send(bitMap, 8);
    }
    rx485ix = -1; // it needs to be sync to "!" again
   }
   else {
    rx485Ln[rx485ix++] = rxChr;
    if(rx485ix > 6)
     // it cannot be greater than 6 bytes.
     // Re-sync to "!".
     rx485ix = -1;
   }
  }
 }
}

// We send "bbbbbbbb" to WebSocket. b is equal to each input channel, and it becomes either '0' or '1'.
void hexToBit(char hex, int p) {
 int i;

 if(hex >= 'A')
  hex = hex - 0x41 + 10;
 else
  hex -= '0';
 hex ^= 0x0f;

 for(i = 0; i < 4; i++) {
  if(hex & 0x08)
   bitMap[p + i] = '1';
  else
   bitMap[p + i] = '0';
  hex <<= 1;
 }
}



The code can be downloaded from:
https://github.com/michelleseo/Arduino_Web/blob/master/WSAdam/WSAdam.ino





Thursday, May 22, 2014

Arduino Code(1) - Web/Arduino/Adam

The basic tutorial for WebSocket:
http://www.tutorialspoint.com/html5/html5_websocket.htm

The code that I used for WebSocket is from the following site:
http://jlectronique.org/WebsocketsEN.htm

Now back to the original TOPIC.

Code for Arduino WebSocket


include
#include <SPI.h>
#include <Ethernet.h>
#include <WebSocket.h> 

Ones that must be defined
/* Mac Address
  Each Ethernet Shield has different mac address. 
  Check your board.
*/
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x25, 0xC4 };

/* IP Address
  Arduino becomes the server, and it needs fixed IP.
  It doesn't necessarily need global IP, it just needs fixed IP.
  Most LAN connections use DHCP, so use an Local IP address that 
  DHCP doesn't use.
  HOW?
     Open command promp and type ipconfig /all
     Check the IP Address for the current PC. 
     Keeping the same Subnet Mask, try pinging IP addresses.
     If you find the IP address that doesn't answer the ping,
     use that IP address.
     If someone around you gets pissed off because their internet 
     doesn't work, change the IP address quickly and quietly before
     he notices you.
*/
byte ip[] = { 192, 168, 100, 11 };

Create WebSocket Callback
/*
  There are 3 Callbacks in WebSocket.h.
  You should be able to guess what they are for just by looking at
  there names.

    typedef void DataCallback(WebSocket &socket, char* socketString, byte frameLength);
    typedef void Callback(WebSocket &socket);

    void registerDataCallback(DataCallback *callback);
      // Called when received Data
    void registerConnectCallback(Callback *callback);
      // when WebSocket is connected
    void registerDisconnectCallback(Callback *callback);
      // when WebSocket is disconnected
*/
WebSocket wsServer;
void onData(WebSocket &socket, char* socketString, byte frameLength) { }
void onConnect(WebSocket &socket) { }
void onDisconnect(WebSocket &socket) { }

Code inside setup()
void setup() {
 Ehternet.begin(mac, ip);
 wsServer.registerConnectCallback(&onConnect);
 wsServer.registerDataCallback(&onData);
 wsServer.registerDisconnectCallback(&onDisconnect);
 wsServer.bein();
 // Give Ethernet Shield some time to get ready.
 delay(100);
}

Code inside loop()
void loop() {
 wsServer.listen();

 if(wsServer.isConnected()) {
  wsServer.send("abc123", 6);
 }
}

/*
  listen() needs to be called continuously.
  If data is received onData() gets called.
  If you want to send data send(char *str, byte length);
*/

RS-485 Connection Code


include
#include <SoftwareSerial.h>

Ones that must be defined
SoftwareSerial Soft485(3, 4);
int DE485 = 2;

/*
  Pin 3: RX
  Pin 4: TX
  Pin 2: DE This was declared in 
      RS485 Shield - Web/Arduino/Adam posting.
*/

Code inside setup()
void setup() {
 Soft485.begin(9600);
 pinMode(DE485, OUTPUT);
}

/*
  ADAM-4050 is 9600 bps. (ADAM - Web/Arduino/Adam posting)
*/






Wednesday, May 21, 2014

RS485 Shield - Web/Arduino/Adam

I have purchased following RS-485 Shield.
https://www.tindie.com/products/Conceptinetics/rs485-rs422-shield-for-arduino/





RS-485 Shield






































There was no manual ( just like I expected :( ), and shockingly schematic was not included.
Furthermore I couldn't even find the information about the manufacturer.  I sent an email to the address on the PCB ( info@conceptinetics.com.hk ), and got the following:



RS-485 Schematic

This was unexpected.  Guess I should be thankful that they replied.





Anyways...

Although it is not shown on the schematic, there is a Jumper to allow the use of Soft Serial Port.  There are 3 Jumpers; however, Arduino Uno only has one Serial Port so we are going to use Soft Serial Port.

     EN
     TX-io
     RX-io    Set them for Jumper



Pin Settings:

  • Pin 3: RX
  • Pin 4: TX
  • Pin 2: DE


DE is only set to 'H' when transmitting, and at other times ( receiving ) DE is set to 'L'.  At other times Soft Serial is same as general serial, thus we don't have to care.

In Ethernet Shield, Pin 4 is used as SD_CS; however for now we are not using SD thus we don't have to worry about it.  If you really want to use SD, you have to move TX to somewhere around Pin 5 which involves cutting and soldering.  Very annoying...





Tuesday, May 20, 2014

UNO, Ethernet Shield - Web/Arduino/Adam

UNO

I used UNO, the most basic Arduino model.

The one I purchased is from the following Korean site, and it is not the original version.
http://www.nulsom.com/
You could purchase it from other sites ( a lot of them sell it ).
http://eleparts.co.kr/EPX7R9BJ
http://devicemart.co.kr/goods/view.php?seq=38296

This machine gives off a lot of heat ( enough heat to make me worry about the PCB ).

Arduino UNO from http://www.nulsom.com/





Ethernet Shield


This is an original, I purchased it from plughouse (Korean site).
http://www.plughouse.co.kr/shop/goods/Goods_view.php?G_code=102705472330

Ethernet Shield





UNO + Ethernet Shield + RS-485 Shield

Let's stack all 3.

Arduino UNO + Ethernet Shield + RS-485 Shield





Photo with ADAM!

Arduino UNO + Ethernet Shield + RS-485 Shield, Adam-4050, LED & Switches






Monday, May 19, 2014

ADAM - Web/Arduino/Adam

ADAM-4050

This is the most basic Digital Input / Output ADAM series module. ( also the cheapest* )


Download the manual "ADAM-4000_manual_V20.pdf" from the above link. 
( This manual is for the entire 4000 series modules. ADAM-4050 starts on page 74 )


ADAM has 8 Outputs and 7 Inputs.
I have attached 8 LED and 7 DIP Switches ( BEST for testing ). 

ADAM 4050 module w/ 8 LED & 7 DIP Switch
































Circuit?

Very simple. ( It's in manual pg.75 )
I set INIT* pin to GND because I didn't want to confuse 485 Address. This sets Address = 0, Speed = 9600 bps, and Checksum = disabled. ( manual pg.19 )

Circuit w/ Switch and LED











RS-485 Protocol

For ADAM-4050 command set refer to manual pg.130.
The ones that we actually use are:
  • Digital Data In (pg.241) that begins with '$' and
  • Digital Data Out (pg.243) that begins with '#'


The Confusing Question...

Is this protocol only using visible ASCII ( 0x20 - 0x7f )? or is Binary also being used?
Except for the line termination Cr ( 0x0d ), only Visible ASCII are used.

Digital Data Out

#AABB( data )( cr )
  except for ( cr ), #AABB( data ) is string
  • AA is address for 485
    AA = "00" because we have set INIT* as GND
  • BB is channel address
    If "00", it writes to all 8 channels at the same time.
    ( data ) ranges from "00" to "FF"
    lsb is DO 0, and msb is DO 7.
    ( eg. If you want to turn ON DO 7 and DO 5 and rest OFF, the ( data ) will be "A0" )

    If "10" - "17", it writes to each channel.
    "10" will turn ON DO 0, ... , "17" will turn ON DO 7
    In this case ( data ) is either "00" or "01".
It says as response we receive ">( cr )"; however we are not going to care about this for now.

Digital Data In

$AA6( cr )
  • AA is address for 485
  • 6 is Digital Data in Command
Response: !( dataOutput )( dataInput )00( cr )
  • ( dataOutput ) Loop back from output.
    2 character string. If we get "A0", it means that DO 7 and DO 5 is ON and rest are OFF.
  • ( dataInput )
    2 character string. This value is what we want.
  • "00"
    We don't know what this is for, so let's not worry about this.