programming Home Automation Using Java


Every programmer  will be more eager to work in project related to hardware and its related challenging tasks .After a lot a lot research on internet related to home automation i here by found a suitable solution for home automation..Due this article you will be able to control you entire home or any electrical devices using java programs.
Java Program
// Comment

package it.cicolella.usb4relaybrd;

import it.freedomotic.api.EventTemplate;
import it.freedomotic.api.Protocol;
import it.freedomotic.app.Freedomotic;
import it.freedomotic.exceptions.UnableToExecuteException;
import it.freedomotic.model.ds.Tuples;
import it.freedomotic.reactions.Command;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ftdi.*;
import it.freedomotic.events.ProtocolRead;

public class Usb4RelayBrd extends Protocol {

    final int POLLING_WAIT;
    private static Map<String, FTDevice> boards;
    private int relayStatus = 0;
    private int relayBitStatus[] = {-1, -1, -1, -1};
    List<FTDevice> fTDevices;
    Map<String, String> boardsAddressAlias = new HashMap<String, String>();

    public Usb4RelayBrd() {
        //every plugin needs a name and a manifest XML file
        super("USB4RelayBrd", "/it.cicolella.usb4relaybrd/usb4relaybrd-manifest.xml");
        POLLING_WAIT = configuration.getIntProperty("time-between-reads", 1000);
        //POLLING_WAIT is the value of the property "time-between-reads" or 2000 millisecs,
        //default value if the property does not exist in the manifest
        setPollingWait(POLLING_WAIT); //millisecs interval between hardware device status reads
        // load the list of boards address alias
        boardsAddressAlias = configuration.getTuples().getTuple(0);
    }

    @Override
    protected void onShowGui() {
        /**
         * uncomment the line below to add a GUI to this plugin the GUI can be
         * started with a right-click on plugin list on the desktop frontend
         * (it.freedomotic.jfrontend plugin)
         */
        //bindGuiToPlugin(new HelloWorldGui(this));
    }

    @Override
    protected void onHideGui() {
        //implement here what to do when the this plugin GUI is closed
        //for example you can change the plugin description
        setDescription("My GUI is now hidden");
    }

    @Override
    protected void onRun() {
        int result = 0;
        String relayStatusValue = null;
        //at the end of this method the system waits POLLINGTIME 
        //before calling it again. The result is this log message is printed
        //every 2 seconds (2000 millisecs)
        for (FTDevice fTDevice : fTDevices) {
            result = readFromFTDevice(fTDevice);
            //System.out.println("Received status " + result); //FOR DEBUG
            // if relays status changed
            if (!(result == relayStatus)) {
                //System.out.println("Relay status changed"); //FOR DEBUG
                relayStatus = result; // update the stored relays status
                if ((result & 2) == 0) {
                    //System.out.println("Relay 1 is OFF"); //FOR DEBUG
                    relayBitStatus[0] = 0;
                    sendEvent("R1", "relay.status", "0");
                } else {
                    //System.out.println("Relay 1 is ON"); //FOR DEBUG
                    relayBitStatus[0] = 1;
                    sendEvent("R1", "relay.status", "1");
                }
                if ((result & 8) == 0) {
                    //System.out.println("Relay 2 is OFF"); //FOR DEBUG
                    relayBitStatus[1] = 0;
                    sendEvent("R2", "relay.status", "0");
                } else {
                    //System.out.println("Relay 2 is ON"); //FOR DEBUG
                    relayBitStatus[1] = 1;
                    sendEvent("R2", "relay.status", "1");
                }
                if ((result & 32) == 0) {
                    //System.out.println("Relay 3 is OFF"); // FOR DEBUG
                    relayBitStatus[2] = 0;
                    sendEvent("R3", "relay.status", "0");
                } else {
                    //System.out.println("Relay 3 is ON"); // FOR DEBUG
                    relayBitStatus[2] = 1;
                    sendEvent("R3", "relay.status", "1");
                }
                if ((result & 128) == 0) {
                    //System.out.println("Relay 4 is OFF"); //FOR DEBUG
                    relayBitStatus[3] = 0;
                    sendEvent("R4", "relay.status", "0");
                } else {
                    //System.out.println("Relay 4 is ON"); //FOR DEBUG
                    relayBitStatus[3] = 1;
                    sendEvent("R4", "relay.status", "1");
                }
            }
        }
    }

    @Override
    protected void onStart() {
        loadDevices();
        Freedomotic.logger.info("Usb4RelayBrd plugin started");
        setDescription("Usb4RelayBrd started");
    }

    @Override
    protected void onStop() {
        for (FTDevice fTDevice : fTDevices) {
            try {
                fTDevice.close();
            } catch (FTD2XXException ex) {
                Freedomotic.logger.severe("Usb4RelayBrd FTD2XX exception " + ex.toString());
            }
            // clear the boards list
            fTDevices = null;
            Freedomotic.logger.info("Usb4RelayBrd plugin stopped");
            setDescription("Usb4RelayBrd stopped");
        }
    }

    @Override
    protected void onCommand(Command c) throws IOException, UnableToExecuteException {
        Integer newStatus = 0;
        String binaryString = null;
        Integer address = 0;
        Integer pos = 0;
        char status;
        FTDevice usb4Relay = fTDevices.get(0);
        if (c.getProperty("control").equalsIgnoreCase("ALLON")) {
            usb4Relay.write(255); // switch ON all relays
            System.out.println("All Relays ON");
        } else if (c.getProperty("control").equalsIgnoreCase("ALLOFF")) {
            usb4Relay.write(0); // switch OFF all relays
            System.out.println("All Relays OFF");
        } else {
            // retrieve the relay number 
            address = Integer.valueOf(c.getProperty("address").substring(1, c.getProperty("address").length()));
            newStatus = readFromFTDevice(usb4Relay);
            // convert the integer relayStatus into a binary string 
            binaryString = Integer.toBinaryString(relayStatus);
            // Integer.toBinaryString removes leading 0 so the first is added if needed 
            if(binaryString.length()<8)
                binaryString = "0"+binaryString;
            //System.out.println("Stringa binaria " + binaryString);
            // revert the string 
            StringBuffer reverse = new StringBuffer(binaryString).reverse();
            if (c.getProperty("control").equalsIgnoreCase("ON")) {
                status = '1';
            } else {
                status = '0';
            }
            // detect from the relay number which bit must be changed 
            switch (address) {
                case 1:
                    pos = 1;
                    break;
                case 2:
                    pos = 3;
                    break;
                case 3:
                    pos = 5;
                    break;
                case 4:
                    pos = 7;
                    break;
            }
            // change the bit mapped to the relay
            reverse.setCharAt(pos, status);
            // revert the string for decimal convertion
            String reverseModified = new StringBuffer(reverse.toString()).reverse().toString();
            // write on the serial the new relays status 
            usb4Relay.write(Integer.parseInt(reverseModified, 2));
        }
        usb4Relay = null;
    }

    @Override
    protected boolean canExecute(Command c) {
        //don't mind this method for now
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void onEvent(EventTemplate event) {
        //don't mind this method for now
        throw new UnsupportedOperationException("Not supported yet.");
    }

    // load devices connected
    private void loadDevices() {
        //boards = new HashMap(); // not used now
        try {
            fTDevices = FTDevice.getDevices();
            for (FTDevice fTDevice : fTDevices) {
                //boards.put(fTDevice.getDevSerialNumber(), fTDevice);
                // open the device
                fTDevice.open();
                // 170 represents in decimal the pins mask 1,3,5,7 
                int mask = 170;
                // set Asynchronous BitBangMode and output pins mask
                fTDevice.setBitMode((byte) mask, BitModes.BITMODE_ASYNC_BITBANG);
                // set baudate
                fTDevice.setBaudRate(921600);
                // set serial line parameters
                fTDevice.setDataCharacteristics(WordLength.BITS_8, StopBits.STOP_BITS_1, Parity.PARITY_NONE);
            }
        } catch (FTD2XXException ex) {
            Freedomotic.logger.severe("Usb4RelayBrd FTD2XX exception " + ex.toString());
        }
        if (fTDevices.size() == 0) {
            this.stop();
            setDescription("Usb4RelayBrd stopped. No board detected");
        }
    }

// this method sends a freedomotic event every time a relay status changes
    private void sendEvent(String objectAddress, String eventProperty, String eventValue) {
        ProtocolRead event = new ProtocolRead(this, "usb4relaybrd", objectAddress);
        event.addProperty(eventProperty, eventValue);
        //publish the event on the messaging bus
        this.notifyEvent(event);
    }

    // this method reads a byte from an FTDevice and converts it to integer
    private int readFromFTDevice(FTDevice usb4Relay) {
        int readValue = 0;
        byte[] received = new byte[1];
        try {
            usb4Relay.purgeBuffer(true, true);
            usb4Relay.purgeBuffer(true, true);
            usb4Relay.read(received, 0, 1);
            readValue = (int) received[0] & 0xff; //mask the sign bit
        } catch (FTD2XXException ex) {
            Freedomotic.logger.severe("Usb4RelayBrd FTD2XX exception " + ex.toString());
        }
        return (readValue);
    }

    // this method retrieve a key from value in a hashmap
    // NOT USED
    public static Object getKeyFromValue(Map hm, Object value) {
        for (Object o : hm.keySet()) {
            if (hm.get(o).equals(value)) {
                return o;
            }
        }
        return null;
    }
}







JAVA API Free download Click here


Hard Ware Device Details 
 
Buy Device from Denkovi Assembly Electronics ltd.

USB relay module (board) with 4 relays RAS-05-15. You may control directly 220V / 120V eletrical devices with your PC usb port. It is fully powered by the USB port. Suitable for home automation applications and USB remote control.
  • Code: DAE-CB/Ro4-USB
  • Manufacturer: Denkovi Assembly Electronics ltd.
  • Weight: 0.075 Kgs
Price: Rs.1,538.76  



Features
  • Relays: 4 x RAS-05-15.
  • Relay parameters: 5V / 72mA, 15A/24VDC (120VAC), 10A/250VAC
  • PCB parameters: FR4 / 1.5mm / two layers / metalized holes / HAL / white stamp / solder mask / еxtra PCB openings for better voltage isolation / doubled high voltage tracks
  • Power supply: from USB port
  • Current consumption: 400 mA
  • Chip: FT245RL. 
  • Power led: Yes
  • Relay leds: Yes
  • Size: 77mm x 56mm x 17mm
  • Supported by DRM softwareYes
  • Software examples - here

Advantages:
  • High quality
  • Low cost
  • No extra power supply
  • Free software with many functions
  • Control electrical devices according weekday/date/time
  • Create timers or pulses with our software

Applications:
  • Home automation
  • Robotics
  • Alarms
  • Timers
  • Open doors and windows via PC
  • Aquariums applications

Additional information:
Each such device is shown as separate virtual com port (VCP) on your PC. The relay board outputs are controlled by FT245RL. It has 8 bit data output register (this device use only 4 of them). When data is sent to the register the outputs are set. If you are software developer - be sure "Synchronous Bit-Bang Mode" is selected! FTDI provides Bit-Bang Mode documentation. See this. The board can not be controlled directly via COM port - you need to download our DRM Software to control the device. The unit can not work without PC. Only one such device can be supplyed from single USB port. If you want to supply many such devices you need USB HUB with extra power supply. 

Relay output characteristics: 
Type  DAE-CB/Ro4-USB
Relay type  RAS-05-15
Relay outputs count  4
Contact type  NO, NC
Current consumption5 VDCmA72
Switching parameters
24 VDC
120 VAC
250 VAC
A
A
A
15
15
10

Phisical characteristics: 
Type  DAE-CB/Ro4-USB
Dimensions
Width
Height
Length
mm
mm
mm
77
17
56
Weight gr75
PCB
FR4
Height
Layers
Metalized holes
HAL
White stamp
Solder mask
Extra PCB openings
Solder mask
 
mm
 
 
 
 
 
 
 
Yes
1.5
2
Yes
Yes
Yes
Yes
Yes
Yes
Mounting holes diameterinner sidemm3.5
Leds
Relays (green)
USB ON (red)
 
Yes
Yes
USB port terminal Yes

How to connect inductive loads

Mechanical view


DRM Software 
Denkovi Relay Manager (DRM) is universal software for controling all kinds of Denkovi USB, VCP and SNMP relay boards

DRM Software will hep you to save money for expensive softwares and time in programming. It allows you to switch ON/OFF your devices at particular date and time, turn ON/OFF the relays with pulses or control them via specific sequence. If you have one of our relay boards from this list you may turn your PC in powerful automation tool.
Denkovi Relay Manager Software (DRM Software)
DRM Software image - control mode for USB Four Channel Relay Board






Unknown Web Developer

Programming USB system with the JSR-80 API



The normal procedure for accessing a USB device with the JSR-80 API is as follows:
  1. Bootstrap by getting the appropriate UsbServices from the UsbHostManager.
  2. Access the root hub through the UsbServices. The root hub is considered as a UsbHub in the application.
  3. Obtain a list of the UsbDevices that are connected to the root hub. Traverse through all the lower-level hubs to find the appropriate UsbDevice.
  4. Interact with the UsbDevice directly with a control message (UsbControlIrp), or claim a UsbInterface from the appropriate UsbConfiguration of the UsbDevice and perform I/O with theUsbEndpoint available on the UsbInterface.
  5. If a UsbEndpoint is used to perform I/O, open the UsbPipe associated with it. Both upstream data (from the USB device to the host computer) and downstream data (from the host computer to the USB device) can be submitted either synchronously or asynchronously through the UsbPipe.
  6. Close the UsbPipe and release the appropriate UsbInterface when the application no longer needs access to the UsbDevice.  

Obtaining the content of the USB system with the JSR-80 API



// Comment
import javax.usb.*;
import java.util.List;
 
public class TraverseUSB
{
        public static void main(String argv[])
        {
          try
          {
              // Access the system USB services, and access to the root 
              // hub. Then traverse through the root hub.
              UsbServices services = UsbHostManager.getUsbServices();
              UsbHub rootHub = services.getRootUsbHub();
              traverse(rootHub);
          } catch (Exception e) {}
        }
 
        public static void traverse(UsbDevice device)
        {
          if (device.isUsbHub())
          {   
             // This is a USB Hub, traverse through the hub.
             List attachedDevices = 
                 ((UsbHub) device).getAttachedUsbDevices();
             for (int i=0; i<attachedDevices.size(); i++)
             {
               traverse((UsbDevice) attachedDevices.get(i));
             }
          }
          else
          {
             // This is a USB function, not a hub.
             // Do something.
          }
        }
}


Unknown Web Developer

Programming USB devices from Java applications using jUSB


Click here Java USB Api Download 


The jUSB API includes the following packages:
  • usb.core: This package is the core part of the jUSB API. It allows Java applications to access USB devices from USB hosts.
  • usb.linux: This package contains a Linux implementation of a usb.core.Host object, bootstrapping support, and other classes leveraging Linux USB support. This implementation accesses the USB devices through the virtual USB device file system (usbdevfs).
  • usb.windows: This package has a Windows implementation of a usb.core.Host object, bootstrapping support, and other classes leveraging Windows USB support. This implementation is still in its very early stage.
  • usb.remote: This package is a remote version of the usb.core API. It includes an RMI proxy and a daemon application, which allow Java applications to access USB devices on a remote computer.
  • usb.util: This package provides some useful utilities to download firmware to USB devices, dump the content of the USB system into XML, and convert a USB device with only bulk I/O into a socket.
  • usb.devices: This optional package collects Java code to access a variety of USB devices with the jUSB API, including Kodak digital cameras and Rio 500 MP3 Players. These APIs were specially written to simplify the process of accessing the designated USB devices and cannot be used to access other devices. The APIs were built upon the usb.core APIs, and they will work on any operating system where jUSB is supported.
  • usb.view: This optional package provides a simple USB tree browser based on Swing. It is a very good example program illustrating the use of the jUSB API.
Although the implementation of the usb.core.Host object varies from operating system to operating system, a Java programmer needs to understand only the usb.core package to start developing applications with the jUSB APIs. 


// Comment
import usb.core.*;
 
public class ListUSB
{
    public static void main(String[] args)
    {
        try
        {
            // Bootstrap by getting the USB Host from the HostFactory.
            Host   host = HostFactory.getHost();
 
            // Obtain a list of the USB buses available on the Host.
            Bus[]  bus  = host.getBusses();
            int    total_bus = bus.length;
 
            // Traverse through all the USB buses.
            for (int i=0; i<total_bus; i++)
            {
                // Access the root hub on the USB bus and obtain the
                // number of USB ports available on the root hub.
                Device root = bus[i].getRootHub();
                int total_port = root.getNumPorts();
 
                // Traverse through all the USB ports available on the 
                // root hub. It should be mentioned that the numbering 
                // starts from 1, not 0.
                for (int j=1; j<=total_port; j++)
                {
                    // Obtain the Device connected to the port.
                    Device device = root.getChild(j);
                     if (device != null)
   {
       // Obtain the current Configuration of the device and the number of 
       // Interfaces available under the current Configuration.
       Configuration config = device.getConfiguration();
       int total_interface = config.getNumInterfaces();
 
       // Traverse through the Interfaces
       for (int k=0; k<total_interface; k++)
       {
           // Access the currently Interface and obtain the number of 
           // endpoints available on the Interface. 
           Interface itf = config.getInterface(k, 0);
           int total_ep  = itf.getNumEndpoints();
 
           // Traverse through all the endpoints.
           for (int l=0; l<total_ep; l++)
           {
               // Access the endpoint, and obtain its I/O type.
               Endpoint ep = itf.getEndpoint(l);
               String io_type = ep.getType();
               boolean input  = ep.isInput();
 
               // If the endpoint is an input endpoint, obtain its
               // InputStream and read in data.
               if (input)
               {
                   InputStream in;
                   in = ep.getInputStream();
                   // Read in data here
                   in.close();
               }
               // If the Endpoint is and output Endpoint, obtain its 
               // OutputStream and write out data.
               else
               {
                   OutputStream out;
                   out = ep.getOutputStream();
                   // Write out data here.
                   out.close();
               }
           }
       }
    }
                }
            }
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
 


Unknown Web Developer

Hash Map Example using Generic


In this Sample program you can get know how to use hash map by Generic
HashMapSample.java
// Comment

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
*
* @author allinalljava.blogspot.com
*/
public class HashMapSample {
public static void main (String [] args)
{

Map<String, Object> m = new HashMap<String, Object>();//In the has map has both object of a class and string.
Employee<String ,Double> e = new Employee<String ,Double> ("ram", 50000.0);
m.put ("123", e);
e = new Employee<String ,Double> ("ganes", 30000.0);
m.put ("456", e);
Employee<String ,String> total = new Employee<String ,String> ("Generic"," Example");
m.put ("This is Sample ", total);
Set entries = m.entrySet ();
Iterator iter = entries.iterator ();
while (iter.hasNext ())
{
Map.Entry me = (Map.Entry) iter.next ();
System.out.print (me.getKey () + " ");
e = (Employee<String, Double>) me.getValue ();
System.out.println (e.getName () + " " + e.getSalary ());
}
System.out.println ("Map size = " + m.size ());
System.out.println ("Empty: " + m.isEmpty ());
m.clear ();
System.out.println ("Map size = "+ m.size ());
System.out.println ("Empty: " + m.isEmpty ());
}
}


Employee.java
//Comment

/*
* To change this template, choose Tools | Templates

* and open the template in the editor.
*/


/**
*
* @author allinalljava.blogspot.com
*/
import java.util.*;
class Employee<T,R>
{
private T name;

private R salary;

Employee (T t, R r){
this.name = t;
this.salary = r;
}
public R getSalary() {
    return salary;
}
public void setSalary(R salary) {
    this.salary = salary;

}
public T getName() {
    return name;
}
public void setName(T name) {
    this.name = name;
}


}



Output 123
 ram 50000.0
This is Sample Generic Example
456 ganes 30000.0
Map size = 3
 Empty: false
Map size = 0
Empty: true
Unknown Web Developer

Hash Map Example using iteration



To use Hash Map using Java

// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;

importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Set;

/**
 *
 * @author allinalljava.blogspot.com
 */
public class HashMapSample {
public static void main (String [] args)
{
Map m = new HashMap ();
Employee e = new Employee ("ram", 50000.0);
m.put ("123", e);
e = new Employee ("ganes", 30000.0);
m.put ("456", e);
e = new Employee ("rajesh", 49750.0);
m.put ("758", e);
Set entries = m.entrySet ();
Iterator iter = entries.iterator ();
while (iter.hasNext ())
{
Map.Entry me = (Map.Entry) iter.next ();
System.out.print (me.getKey () + " ");
e = (Employee) me.getValue ();
System.out.println (e.getName () + " " + e.getSalary ());
}
System.out.println ("Map size = " + m.size ());
System.out.println ("Empty: " + m.isEmpty ());
m.clear ();
System.out.println ("Map size = "+ m.size ());
System.out.println ("Empty: " + m.isEmpty ());
}
}


Employee.java

// Comment

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.allinalljava;

/**
 *
 * @author allinalljava.blogspot.com
 */
import java.util.*;
class Employee
{
private String name;
private double salary;
Employee (String name, double salary)
{
this.name = name;
this.salary = salary;
}
String getName ()
{
return name;
}
double getSalary ()
{
return salary;
}
}

Output

123 ram 50000.0
456 ganes 30000.0
758 rajesh 49750.0
Map size = 3
Empty: false
Map size = 0
Empty: true
Unknown Web Developer

Mother Board Driver for Tamil Nadu Government free Laptop (Lenovo B460)



Free  Laptop distributed by Tamil Nadu  Government contains several features. Education wise all the e-book content available in Laptop.Due to this students can improve their technical skills level. It is properly categorized based on the students level for all arts, polytechnic and engineering student first year syllabus eBook’s (such as Engineering Drawing ,Math, Communication Skills ,Botany , Zoology ,Computer Science Material is Also Available .Students those who are not get their laptop can copy these contents from the laptop those who have already got. It may improve you lot at beginning of college days.

Things to do After Getting Free Laptop

             Mother board Drive for Lenovo B460 is available in your laptop  c: drive itself. After getting laptop the Student have to make its back up in CD  or Pen drive. Better  by external portable DVD Drive for the laptop .It will use full for you in many way .For installing you OS. Laptop itself contains Two OS (BOSS as Linux OS, Windows). Important thing that all student while using pen drive for copying any data better use BOSS operating system and please check files whether there is any unwanted file in that folder or not. This may help you to avoid virus from your system. Don’t use laptop with low charge or by plugging with power after battery is full. It might make your battery weak. When battery reach 20 % plug charger and when it 100% just unplug it. It make your laptop life long. Better buy USB Keyboard and mouse for  typing and other mouse handling it makes you more convenient .It will accept all type of internet facility. Tamil Nadu government has done a great job for the student to improve  education level. For any doubt related laptop just comment here.

Free Download Mother Board Drivers ForTN Govt Laptops

 Download all Model Tamil Nadu Government free laptop Mother Board Drivers From this Links.
Unknown Web Developer

Synchronization Using Bit Stuffing


To write a C program to perform the  BIT STUFFING using linux enviroinment.


  Step1: Start the program.
  Step2: Get the messages and check the message for five repeated “1” value.
  Step3: If it is true then add “0” as next value.
  Step4: Print the sending messages one by one.
  Step5: Stop the program.

Source code 


// Comment
#include<stdio.h>
#include<string.h>
main()
{
char b[30]={0,0},c[30]={0,0},a[40]="01111110",e[40]="01111110";
int i,j=0,cnt=0,n;
printf("enter the string");
scanf("%s",b);
n=strlen(b);
for(i=0;i<n;i++)
{
c[j]=b[i];
if(b[i]='1')
cnt++;
else
cnt=0;
if(cnt==5)
{
c[++j]='0';
cnt=0;
}
j++;	
}
printf("after bit stuffing \n");
strcat(a,c);
strcat(a,e);
printf("%s",a);
}


Output

[t03it    @localhostt03it   ]$ cc bitstuff.c
[t03it    @localhostt03it   ]$./a.out
enter the string 111111
after bit stuffing
01111110111110101111110
 
Unknown Web Developer

Cyclic Redundency Check in linux


To write a C program to perform the  CRC computation using linux environment

Step1: Start the program.
Step2: Declare the variables and array of values.
Step3: Get the bits of data of the original values.
Step4: Get the divisor binary values for the original data.
Step5: By using for loop perform the process of CRC.
Step6: Finally the sending data’ s are printed.
Step7: Stop the program.

Source Code
 
// Comment
#include<stdio.h>
#include<string.h>
void xor(char a[10],char b[10],int len)
{
int i;
for(i=1;i<len;i++)
{
if(a[i]==b[i])
a[i-1]='0';
else
a[i-1]='1';
}
a[i]='\0';
}
main()
{
char a1[10],a2[10],t1[10],t2[10],t[5],res[15],c[15];
int n,len,tn,i;
printf("enter input string");
scanf("%s",a1);
printf("enter divisor");
scanf("%s",a2);
n=strlen(a1);
len=strlen(a2);
strcpy(res,a1);
for(i=0;i<len-1;i++)
{
c[i]='0';
}
c[i]='\0';
strcat(a1,c);

tn=strlen(a1);
strcpy(t1,a2);
for(i=0;i<len;i++)
{
t2[i]='0';
}
t2[i]='\0';
strncpy(t,a1,len);
for(i=len;i<=tn;i++)
{
xor(t,a2,len);
len=strlen(a2);
strcpy(res,a1);
for(i=n;i<n+len-1;i++)
{
a1[i]='0';
}
a1[i]='\0';
tn=strlen(a1);
strcpy(t1,a2);
for(i=0;i<len;i++)
{
t2[i]='0';
}
t2[i]='\0';
strncpy(t,a1,len);
for(i=len;i<=tn;i++)
{
xor(t,a2,len);
if(t[0]=='1')
strcpy(a2,t2);
else

strcpy(a2,t2);
t[len-1]=a1[i];
t[len]='\0';
}
strcat(res,t);
printf("the result is%s\n",res);
}
}






Output  
[t03it    @localhostt03it   ]$ cc crc.c
[t03it    @localhostt03it   ]$./a.out
enter input string 111011111
enter divisor 1101
the result is 111011111000000

Unknown Web Developer

Stock Market Using Corba


To write a program to develop a middle-ware component for retrieving Stock Market Exchange information using CORBA.

  • Creating a module which contains a set of interface program and save it as a SimpleStocks.idl makes sure that module and interface name is different.
  • Next declare the implementation file with ImplBase concept & contains details about stock maintenance.
  • Create a server program  that initialize the ORB name the server object & bind the server object with the implementation file now server is ready.
  • Create a client program by initialize the ORB. Make sure the name of server object and client object declared resembles the frame.
  • Then provide the input to the client program and obtain the suitable output corresponding to it.

Compile & Execution Steps:

  • idlj -fall -oldImplBase SimpleStocks.idl
  • javac StockMarketImpl.java SimpleStocks\*.java
  • javac StockMarket server.java SimpleStocks\*.java
  • javac StockMarket client.java SimpleStocks\*.java
  • start orbd -ORBInitialPort 1050
  • start java StockMarket Server -ORBInitialPort 1050
  • java StockMarket client -ORBInitialPort 1050 50.
Source code

Simplestock.idl
// Comment
module Simplestock
{
interface stockmarket
{
float get_price(in string symbol);
};
};


stockmarketimpl.java
// Comment
import org.omg.CORBA.*;
import simplestocks.*;
public class stockmarketimpl extends _stockmarketImplBase
{
 public float get_price(String symbol)
  {
  float price=0;
  for(int i=0;i<symbol.length();i++)
  {
   price+=(int)symbol.charAt(i);
  }
   price/=5;
   return price;
  }
   public stockmarketimpl()
  {
   super();
  }
 }


Stockmarketserv.java
// Comment
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import simplestocks.*;
public class stockmarketserv
{
 public static void main(String args[])
 {
  try
  {
     ORB orb=ORB.init(args,null);
     stockmarketimpl stockmarketimpl=new stockmarketimpl();
     orb.connect(stockmarketimpl);
     org.omg.CORBA.Object objRef=orb.resolve_initial_references("NameService");
     NamingContext ncRef=NamingContextHelper.narrow(objRef);
     NameComponent nc=new NameComponent("NASDAQ"," ");
     NameComponent path[]={nc};
     ncRef.rebind(path,stockmarketimpl);
     System.out.println("Stockmarket server is ready");
     Thread.currentThread().join();
    }
    catch(Exception e)
    {
     e.printStackTrace();
    }
   }
  }


stockmarketcli.java
// Comment
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import simplestocks.*;
public class stockmarketcli
{
 public static void main(String args[])
 {
  try
  {
   ORB orb=ORB.init(args,null);
   NamingContext ncRef=NamingContextHelper.narrow(orb.resolve_initial_references("NameService"));
   NameComponent path[]={new NameComponent("NASDAQ"," ")};
   stockmarket market=stockmarketHelper.narrow(ncRef.resolve(path));
   System.out.println("Rate of the company is"+market.get_price(args[2]));
   }
   catch(Exception e)
   {
    e.printStackTrace();
    }
   }
  }

Output Screen
 
Unknown Web Developer

Weather Forecast Information Using CORBA


To develop the application program in CORBA to illustrate the temperature server.

  •  Creating a module which contains a set of interface program and save it as a Simple Temperature.idl makes sure that module and interface name is different.
  • Next declare the implementation file with IMPL Base concepts & contains details about temperature display.
  • Create a server program that initialize the ORB name the server object &bind the server object with the implementation file.
  • Now server is ready.
  • Create a client program by initialize the ORB. make sure the name of the server object and client object declared reassembles the fram.
  • Then provide the input to the client program and obtain the suitable output corresponding to it.
Compile & Execution Steps


  •    idlj -fall -oldImplBase SimpleTemperature.idl
  •    javac Temperatureimpl.java SimpleTemperature\*.java
  •    javac Temperatureserver.java SimpleTemperature\*.java
  •     javac Temperatureclient.java SimpleTemperature\*.java
  •       start orbd -ORBInitialPort 1050
  •      start java Temperature server -ORBInitialport 1050
  •       server is ready.
  •   java Temperature client -ORBInitialport 1050 30
 
SimpleTemperature.idl

// Comment
module SimpleTemperature
{
interface Temperature
{
string get_tmp(in float a);
};
}; 

Temperatureimpl.java

// Comment

import org.omg.CORBA.*;
import SimpleTemperature.*;
public class Temperatureimpl extends _TemperatureImplBase
{
public String get_tmp(float a)
{
String c;
if (a<0)
c="----------Too cool----------";
else if(a<=10)
c="----------cool----------";
else if(a<=20)
c="----------MODERATE----------";
else if(a<=30)
c="----------HOT----------";
else
c="----------TOO HOT----------";
return c;
}

public Temperatureimpl()
{
super();
}
}

Temperatureserver.java

// Comment
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import SimpleTemperature.*;
public class Temperatureserver
{
public static void main(String args[])
{
try
{
ORB orb=ORB.init(args,null);
Temperatureimpl temperatureImpl=new Temperatureimpl();
orb. connect(temperatureImpl);
org.omg.CORBA.Object objRef=orb.resolve_initial_references("NameService");
NamingContext ncRef=NamingContextHelper.narrow(objRef);
NameComponent nc=new NameComponent("NASDAQ","");
NameComponent path[]={nc};
ncRef.rebind(path,temperatureImpl);
System.out.println("Temperature SERVER is Ready");
Thread.currentThread().join();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Temperatureclient.java

// Comment
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import SimpleTemperature.*;
public class Temperatureclient
{
public static void main(String args[])
{
try
{
float e=Float.parseFloat(args[2]);
ORB orb=ORB.init(args,null);
NamingContext ncRef=NamingContextHelper.narrow(orb.resolve_initial_references("NameService"));
NameComponent path[]={new NameComponent("NASDAQ","")};
Temperature tempr=TemperatureHelper.narrow(ncRef.resolve(path));
System.out.println("\t\t Weather Casting");
System.out.println("\t\t_ _ _ _ _ _ _ _ _ _ _ _");
System.out.println("Input is:"+e);
System.out.println("WEATHER is:"+tempr.get_tmp(e));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}


Output Screen
Unknown Web Developer

Download Files From Various Servers Using RMI


To Create  a program to download files from various servers using RMI

  •   Define the interface.
  • Interface must extend Remote
  •   All methods must throw an exception Remote Exception individually
  • Implement the interface.
  •  Create a server program.
  • Create a Client Program.
  •  Generate stubs and skeletons using rmic tool.
  • Start the server.
  •   Start the client.
  • Once the process is over stop the client and server respectively.
fileinterface.java

// Comment
import java.rmi.*;
public interface fileinterface extends Remote
{
public byte[]download file(String s)throws RemoteException;
}

fileimplement.java

// Comment
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileimplement extends UnicastRemoteObject implements fileinterface
{
private String name;
public fileimplement(String s)throws RemoteException
{
super();
name=s;
}
public byte[]downloadfile(String fn)                                       
{
try
{
File fi=new File(fn);
byte buf[]=new byte[(int)fi.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(fn));
bis.read(buf ,0,buf.length);                                                                                                                                                                                                                                            
bis.close();
return(buf);
}
catch(Exception ee)
{
System.out.println("Error:"+ee.getMessage());
ee.printStackTrace();
return(null) ;
}}
}


fileserver.java

// Comment
import java.rmi.*;
import java.io.*;
import java.net.*;
import java.rmi.registry.*;
public class fileserver
{
public static void main(String arg[])
{
try
{
fileimplement fi=new fileimplement("fileserver");
Registry reg=LocateRegistry.createRegistry(5000);
reg.rebind("fileserver",fi);
System.out.println("server is ready");
}
catch(Exception e)
{
System.out.println(" "+e.getMessage());
e.printStackTrace();
}
}
}


fileclient.java

import java.net.*;
import java.rmi.*;
import java.io.*;
public class fileclient
{
    public static void main(String[] args)   
 {
       try{
                //  InetAddress addr=InetAddress.getLocalHost();
          // String address=addr.toString().substring(addr.toString().indexOf("/")+1);
         //  String url="rmi://"+ address + "/fileserver";
           fileinterface f1=(fileinterface)Naming.lookup("rmi://localhost:5000/fileserver");
           byte[] data=f1.downloadfile(args[0]);
           File ff=new File("f1.txt");
           BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(ff.getName()));
           bos.write(data,0,data.length);
           bos.flush();
           bos.close();}
           catch(Exception e){
                      System.out.println(" "+e.getMessage());
           e.printStackTrace();           }
}
}
 

Output Screen


 
Unknown Web Developer

RemoteMethod Invocation (RMI) using Java


To illustrate the concept of remote control invocation by performing the display message "Hello World"


  • Create a remote interface extending the java.rmi remote interface each remote method interfaces throws a java.rmi remote exception.
  • Define a class that implements that interface of the remote object extending the class java rmi unicust remote object.
  • create a server program that register all remote server objects naming rebind() method is used to bind (ie) to assign name to the remote server object.
  • Compile all the four java file using javac.
  • Run the stub compile (rmic compiler) using command rmic filename.
  • Start rmi registry.
  • Run the server program.
  • Run the client program in seperate command prompt using the command applet viewer filename client java.  
Program


Hello.java

// Comment
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}


HelloImpl.java
// Comment
import java.rmi.*;
import java.rmi.server.*;
public class HelloImpl extends UnicastRemoteObject
implements Hello {
public HelloImpl() throws RemoteException {
}
public String sayHello() throws RemoteException{
return "Hello World!";
}
}


Helloserver.java

// Comment
import java.rmi.*;
import java.rmi.registry.*;
public class Helloserver
{
public static void main(String args[]) {
try {
HelloImpl obj=new HelloImpl();
Registry reg=LocateRegistry.createRegistry(5000);
reg.rebind("Helloserver",obj);
System.out.println("Server Starts........");
String ab[]=reg.list();
System.out.println("The Remote Object Available Are:");
for(int i=0;i<ab.length;i++)
System.out.println(ab[i]);
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}


Helloclient.java

// Comment
import java.rmi.*;
public class Helloclient
{
public static void main(String args[])
{
String str="";
Hello obj=null;
try {
obj=(Hello)Naming.lookup("rmi://localhost:5000/Helloserver");
System.out.println(str);
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}
Ouput Window 

Unknown Web Developer

Retouch Print facility in Java



In this article you can get a great idea about how to use the various output statements in Java. While you print a statement, there resides several transaction between the Program and the JVM(Java Virtual Machine).In Java , all are byte based streams for reading input and showing result as output.In order to understand Java I/0 , you have to know how java deals with various integers, characters,bytes and other primitive data types. Most important thing is that to analyze  transformation of data types from one to another 

// Comment
package allinalljava;

/**
 *
 * @author Sabari Raja
 */
public class SamplePrintf {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.print("Welcome to Java Again");
        System.out.write(10);
        System.out.printf("%d%c",100,'%');
        System.out.write(9);
        System.out.print("pure coffee");
        System.out.println("\ntaste me again");
    }
}


In the above program, I have shown various possible ways of printing output streams. Here print(“ “) is normal operation like printing a sample text. While write(int) is some thing different. Its converts numeric value to byte. Usually write(9) is similar to using ‘\t’. Printf(“%d”,value) this method of printing is similar to printf in C. From release of Jdk 5.0, we have this facility of using printf. Println is for printing the statement with end of line. Main use to start newline.


Output
Welcome to Java Again
100%     pure coffee
taste me again
Unknown Web Developer

Related Posts Plugin for WordPress, Blogger...