Monday, September 20, 2010

Ruby- Basics

RUBY

Ruby is a programming language which is somewhat same as Python more complex than python. We can write a program and save it with an extension of 'filename.rb' and can run this program using 'ruby filename.rb'.

To write to the screen puts, print and printf are used.
PUTS- Write on the screen with a return at the end.
PRINT-Write on the screen without a return at the end.
PRINTF- I cant understand the main difference for printf from puts and print. i think printf is mainly used to print a floating point variables, strings etc.

To Read from the console we use gets
STDIN.gets-Standard input to the console is taken by the gets.
For example,
---------------------------------------
puts "What is your name?"
$name = STDIN.gets
puts "Hi "+$name
---------------------------------------

Functions

  We can define a method using def,
--------------------------------
def method_name(values)
    statements
end
-------------------------------
A method must end with 'end'. Indention has no importance here. end shows the ending of that method.

Uppercase- To make a string to upper case we can use upcase.
"hello".upcase => HELLO

To Return a value from a method 'return' is used. If return is not provided Ruby will return the contents of the last expression.
We can assign optional argument values and extra arguments to a method. Extra arguments are gathered into the last variable if preceded with a "*"
for example
--------------------------------
def test(a=1,b=2,*c)
   puts "#{a},#{b}"
   c.each{|x| print "#{x} "}
end
test 3,4,5,6,7,8,9
--------------------------------
which produces
-------------------------------
3,4
5,6,7,8,9
-------------------------------
If # is provided inside double quotes, #{variable} will evaluate the variable.

Sunday, September 12, 2010

Project Phase 2: Google_Appengine

Project Phase 2: GOOGLE APPENGINE

    Google appengine is a cloud platform. First download google_appengine from google website. Googgle_appengine recomments Python 2.5 .So install Python 2.5. Then install libssl-dev and libsqlite3-dev. Now unzip the google_appengine folder and copy to a folder that is created for this work. We are using the web server of the appengine for getting the information received to the RFID reader, and store it in the database of the appengine.
    For this process we have to POST a request containing the data that is read from the RFID to the appengine web server and the GET request will get this request and save this data to the database. All the files needed for getting and posting must be in a located in a unique directory. This directory must contain a configuration file called 'app.yaml'. Following is the app.yaml code

app.yaml
----------------------------------
  application: <directoryname>
  version: 1
  runtime:python
  api_version: 1

  handlers:
  - url: /.*
    script: <filename>
------------------------------------

    application: <directoryname> is the directory where this configuration file and all other files needed for the appengine is kept.

    script: <filename> is the name of the file which is to be excecuted when appengine starts.


POST REQUEST

    For posting a request we have to import 2 modules to this program- httplib and urllib. httplib is for creating a connection to the localhost and urllib is for encoding the data to a url.  It is the duty of the httplib to post the request. The code for post is given below.

post.py
---------------------------------------------------------------
import httplib
from urllib import urlencode

parameters=urlencode({'post1':'hello','post2':'world'})
headers={"Content-Type":"application/x-www-form-urlencoded",
            "Accept":"text/plain"}
conn=httplib.HTTPConnection("127.0.0.1:8080")
conn.request("POST","/",parameters,headers)
response=conn.getresponse()
print response.status,response.reason
print data
conn.close()
---------------------------------------------------------------

    parameters is urlencoded encoded data. Data to be posted is first added to a dictionary. We can provide the key and using the keys we can retrive the values(data).

    headers is the part which tells the web server how the data is encoded and how to decode it.
    Response from the web server can be received using getresponse(). We can print the status and reason of the response



GET REQUEST

    GET request comes inside our main program. Name of this file must be given in the configuration file app.yaml. The database is also created inside this  program. We can use templates for seperating the html part from this program. The code is given below.

main.py
------------------------------------------------------------------
import cgi
import os
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class Storage(db.Model):
    post1=db.StringProperty()
    post2=db.StringProperty()
    time=db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def post(self):
        storage=Storage()
        storage.post1=self.request.get('post1')
        storage.post2=self.request.get('post2')
        storage.put()

    def get(self):
        storages_query=Storage.all()
        storages=storages_query.fetch(10)

        template_values = {
                'storages':storages
                }
        path=os.path.join(os.path.dirname(__file__),'index.html')
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication([('/',MainPage)],debug = True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
----------------------------------------------------------------------------

    We have to import all the necessary modules from webapp like db, template etc. Create a database for storing the information that received from the post method. Data can be stored to the database by using <databasename>.put() . Here templates are use for seperation the designing codes from this program. All the information that we want to print in out main page is passed to this template. Path tells the appengine where to pass the information and template.render() which has two arguments, one is the path and other is the information to be passed.Here the informations are passed to a html file called index.html .

index.html
------------------------------------------------------------------------------
<html>
    <head>
        <script type='text/javascript'>
        </script>
    </head>
    <body onload="JavaScript: timedRefresh();">
        {% for storage in storages %}
        <b>Post1:</b> {{ storage.post1|escape }}<br/>
        <b>Post2:</b> {{ storage.post2|escape }}<br/>
        {% endfor %}
        <a href="javascript:location.reload(true)">Refresh</a>
    </body>
</html>
-----------------------------------------------------------------------------

    Adding the RFID reader program with the post method mentioned above and applying the necessary changes will make our RFID reader compactible with PC.

Saturday, September 11, 2010

Project Phase 1: RFID READER


    RFID reader reads EM4100 family transponder tags. Each tag contains a 10 unique data byte. The reader has a 12 byte output with one start and stop and the 10 unique data byte. The start and stop bytes are used to identify that a correct string has been received from the reader.There is a LED provided to indicate the detection of the card. Normal detection range of the reader is 10-15cm for the tags. The power requirement for RFID reader is 7-9V DC.
    RFID reader connects directly to an RS-232 compatible interface. When the RFID is powered up,then a green LED will be ON.When the antenna gets signal from the transponder tag a red LED starts blinking.If a transponder tag is place within the range of RFID reader a unique 10 byte ID of the tag which is printable ASCII string is passed to the PC.
    As the first phase of our project, we had connected this RFID reader to our PC through RS-232 serial port. We are using python as the programming language. We have to install pyserial for programming using serial ports. Following is a simple program in python used to retrive data from the serial port.

------------------------------------------
import serial
p=serial.Serial('/dev/ttyS1')
def readport(port):
    x=port.read(12)
    return x
r=readport(p)
------------------------------------------

    The function readport() returns the string that is read from theserial port. By importing a module serial we can access the serial ports.
  ser=serial.Serial('/dev/ttyS1') opens the port ttyS1. ser.read(100) reads the data from the ttyS1 up to 100 bytes.

    Our plan is to pass the retrived data to a database so that we can get the complete details of the person using the tag. We are using Google Appengine for this process.