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






raja P Web Developer

3 comments:

  1. brillant piece of information, I had come to know about your web-page from my friend hardkik, chennai,i have read atleast 9 posts of yours by now, and let me tell you, your webpage gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts, once again hats off to you! Thanx a million once again, Regards, Education India

    ReplyDelete
  2. PBX is ideal for small business and entrepreneurs. It gives a professional image and make sure that you don't miss a single call. Few months back, I decided to buy PBX from Telcan. You can get more information here: PBX

    ReplyDelete
  3. There are a lot to choose from when it comes to Business Phone Service providers. There's tough competition among the providers out there. It's your task to single one out from the rest!

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...