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

Related Posts Plugin for WordPress, Blogger...