Friday, February 4, 2011

Yii web service and php soap client

A web service is a method of communication between two machines. The web methods are exposed for world wide access. Yii has support for implementing web services. It uses SOAP as its foundation layer.

To create a web service-

1. Create a web app using Yii console application.
2. Inside the controllers folder, create a file lets say 'ServiceController.php'.
3. Add the following code, which implements two functions. One adds a session variable and the other returns it back.
<?php
class ServiceController extends CController
{
   public function actions()
    {
       return array(
        'wreader' => array(
          'class' => 'CWebServiceAction',
        ),
      );
    }

    /**
     * @param string username
     * @return float
     * @soap
     */
     public function getauth($uname)
     {
              
            $session = Yii::app()->session;
            $session['u_id'] = 1111;
            return 1;
     }

     /**
     * @param string username
     * @return float
     * @soap
     */
     public function getemp($uname)
     {
        $session = Yii::app()->session;
        return isset($session['u_id'])?$session['u_id']:999;
     }
}

* Remember to mark the web methods with the tag @soap in its doc comment. Yii relies on doc comment to specify the data type of the web method's input parameters and return value.

Create a php file and enter the following code which consumes the web service.
<?php
$client=new SoapClient('http://127.0.0.1/s/index.php/service/wreader');
echo "\n".$client->getauth('harpreet');
echo "\n".$client->getemp('harpreet');

?>

Execute the php script in a terminal to check out your web service.

Open to suggests/improvements.

Read from Magtek card swipe reader in HID mode using libusb-win

This post deals with reading card swipe information from a Magtek USB Swipe Reader when set in HID mode. I used Visual Studio C++ Express Edition for a windows development environment. I installed libusb-win32 from http://www.libusb.org/wiki/libusb-win32
Create a C++ project in Visual studio, include the usb.h file and link the project with libusb.lib. Both of these are included in the libusb package.

The following can be used to read the card information-

// magtekusbhidcardswipe.cpp : Defines the entry point for the console application.
//
#include
#include

#include "stdafx.h"
#include "usb.h"

int _tmain(int argc, _TCHAR* argv[])
{
    struct usb_bus *busses;
    struct usb_bus *bus;
    struct usb_device *dev;
    int c, i, res;
    char data[337];
    char idata[10];

    usb_init();
    usb_find_busses();
    usb_find_devices();
    busses = usb_get_busses();
    for (bus = busses; bus; bus = bus->next) {

        for (dev = bus->devices; dev; dev = dev->next) {           
        if(dev->descriptor.idProduct == 2 && dev->descriptor.idVendor == 0x801) {
        printf("Product id: %04hx" ,dev->descriptor.idProduct);
        printf("Vendor id: %04hx \n" ,dev->descriptor.idVendor);
               
        usb_dev_handle *l_Handle = usb_open( dev);
        if( NULL == l_Handle ){
            printf( "usb_open(): no handle to device\n" );
        }
        res = usb_claim_interface(l_Handle, 0);
        if(res  < -EBUSY) {
            printf("Device interface not available to be claimed! \n");
            exit(0);
        }
        if(res < -ENOMEM) {
            printf("Insufficient Memory! \n");
            exit(0);
        }
        printf( "\nPlease swipe your card\n",res );
       
        res = usb_interrupt_read(l_Handle, 0x81, data, 337, -1);
        printf( "\nusb_interrupt_read %d \n",res ); 
       
        c=-1;
                //I am interested in only 10 characters in this range
        for(i=1;i<10;i++) {
            idata[++c] = data[i];
        }
        c=atoi(idata);
        printf( "\nMy data : %d\n",c);
       
        usb_release_interface(l_Handle, 0);            
        usb_close(l_Handle);
        }
       }
    }
    getchar();
    return 0;
}
 


Suggestions/improvements are welcome as always.



Tuesday, February 1, 2011

Iphone 4 does not mount on Ubuntu after iOS 4.2 upgrade - DBus Error

After I upgraded my iphone to iOS 4.2, I was not longer able to mount it on Ubuntu 10.10. Whenever I got plugged it in, I would get an error message -
DBus error org.freedesktop.DBus.Error.NoReply: Message did not receive a reply (timeout by message bus)


I looked it up and found a workaround, seems like I need to update to a newer version of libimobiledevice.

Here is how I did it-

Unplug the iPhone and execute the following in the terminal window.

sudo add-apt-repository ppa:pmcenery/ppa
sudo apt-get update
sudo apt-get upgrade

sudo apt-get install libimobiledevice-utils


After the above install, plug in the iphone and execute -

idevicepair unpair
idevicepair pair
idevicepair validate



That was it and we are back with Iphone on Ubuntu.

Monday, January 17, 2011

C++ - prime numbers

I was reading about algorithms the other day and came to know of a faster algorithm to find prime numbers. It is called the Sieve of Eratosthenes. When I compared the execution times of this algorithm to the one I coded, the times were remarkably faster. A very simple and impressive algorithm to find prime numbers less than a number n.



Wednesday, December 15, 2010

How to unlock Iphone 4 iOS 4.1 at baseband 2.10.04?

I have an iPhone 4 with iOS 4.1 at baseband 2.10.04. I want to use the iPhone on a different network as I am traveling out of country? Can anyone point me in the right direction?
I will write a how-to tutorial once I can do it on my iPhone 4.

Friday, November 19, 2010

Bouncing Orbs

I recently finished a major milestone for a C++/SDL game development course. It is my first mini-game/animation. It was an awesome programming  experience. It was amazing to learn things like parallax scrolling, creating explosions, save/restore of animation state in Xml(expat). Thank you Dr. Malloy.

Tuesday, November 2, 2010

Python - Writing a traceroute using sockets

I recently learned, how to write a traceroute using socket programming in python. I am sharing it below. I don't take any credit for the code. I may have picked bits and pieces from various different resources on the Internet, as a part of my learning process. It's not very elegant but demonstrates the purpose. Perhaps, some day I can improve it and add few enhancements to it.

#!/usr/bin/python
import sys
import socket

def traceroute(dest_name):
    dest_addr = socket.gethostbyname(dest_name)
    port = 33434
    max_hops = 30
    print dest_name
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    while True:
        print ttl,
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        recv_socket.bind(("", port))
        send_socket.sendto("", (dest_name, port))
        curr_addr = None
        curr_name = None
        try:
            _, curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]

            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name, curr_addr)
        else:
            curr_host = "*"
        print "%d\t%s" % (ttl, curr_host)

        ttl += 1
        if curr_addr == dest_addr or ttl > max_hops:
            break

if __name__ == "__main__":
    traceroute(sys.argv[1])


Can be executed as -

>sudo ./traceroute.py xharpreetx.com