Java code for Open Remote

This is my current Java implementation of the socket server that OpenRemote talks to via its TCP/IP protocol, and which in turn talks to my Arduino-based transceiver over USB. It uses the RXTX Java library. This allows OpenRemote to get data from my room sensors and energy monitor, and to control my LighWaveRF sockets, and TV etc. (via my Arduino-based IR remote control box).

Note that this is work in progress and it needs cleaning up in lots of ways.

ORControl.java which creates the socket server used by OPenRemote:


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ORControl {
  private static final int MAX_ROOMS = 6;

  private ServerSocket ss;
  private Socket s;
  private InputStream is;
  private OutputStream os;
  private RFControl rfc = new RFControl();
  private Thread inThread = new Thread(new ReadInput());
  private int[] temp = new int[MAX_ROOMS];
  private int[] light = new int[MAX_ROOMS];
  private int voltage = 0;
  private float power = 0;
  private int room;
  private int[] humidity = new int[MAX_ROOMS];
  private boolean socket1On = false, socket2On=false, socket3On = false;
  private long[] occupied = new long[MAX_ROOMS];
  private int reqtemp = 16;
  private boolean heating = false;

  public void run() {
    inThread.setDaemon(true);
    inThread.start();
    try {
      ss = new ServerSocket(50000);
    } catch (IOException e) {
      System.err.println("Failed to create server socket:" + e.getMessage());
      System.exit(1);
    }

    while(true) {			
      try {
        s = ss.accept();
        is = s.getInputStream();
        os = s.getOutputStream();
        String cmd = "";
        do {
          int b = is.read();

          if (b == 13) {
            //System.out.println("cmd: " + cmd);

            if (cmd.equals("tvon")) {
              rfc.sendCmd((byte) 100);
              success();
            } else if (cmd.equals("vthome")) {
              rfc.sendCmd((byte) 101);
              success();
            } else if (cmd.equals("avmute")) {
              rfc.sendCmd((byte) 102);
              success();
            } else if (cmd.equals("avvolup")) {
              rfc.sendCmd((byte) 108);
              success();
            } else if (cmd.equals("avvoldn")) {
              rfc.sendCmd((byte) 109);
              success();
            } else if (cmd.equals("vtmnok")) {
              rfc.sendCmd((byte) 103);
              success();
            } else if (cmd.equals("vtmnup")) {
              rfc.sendCmd((byte) 104);
              success();
            } else if (cmd.equals("vtmndn")) {
              rfc.sendCmd((byte) 105);
              success();
            } else if (cmd.equals("vtmnlt")) {
              rfc.sendCmd((byte) 106);
              success();
            } else if (cmd.equals("vtmnrt")) {
              rfc.sendCmd((byte) 107);
              success();
            } else if (cmd.equals("pushl")) {
              rfc.sendCmd((byte) 120);
              success();
            } else if (cmd.equals("pushr")) {
              rfc.sendCmd((byte) 121);
              success();
            } else if (cmd.equals("sockstat1")) {
              if (socket1On) {
                writeString("on");
              } else {
                writeString("off");
              }
            } else if (cmd.equals("socketon1")) {
              rfc.sendCmd((byte) 240);
              socket1On = true;
              success();;
            } else if (cmd.equals("socketoff1")) {
              System.out.println("Turning socket 1 off");
              rfc.sendCmd((byte) 241);
              socket1On = false;
              success();
            } else if (cmd.equals("sockstat2")) {
              if (socket2On) {
                writeString("on");
              } else {
                writeString("off");
              }
            } else if (cmd.equals("socketon2")) {
              System.out.println("Turn socket 2 on");
              rfc.sendCmd((byte) 242);
              socket2On = true;
              success();
            } else if (cmd.equals("socketoff2")) {
              rfc.sendCmd((byte) 243);
              socket2On = false;
              success();
            } else if (cmd.equals("sockstat3")) {
              if (socket3On) {
                writeString("on");
              } else {
                writeString("off");
              }
            } else if (cmd.equals("socketon3")) {
              rfc.sendCmd((byte) 244);
              socket3On = true;
              success();
            } else if (cmd.equals("socketoff3")) {
              rfc.sendCmd((byte) 245);
              socket3On = false;
              success();
            } else if (cmd.equals("heating")) {
              if (temp[1] < reqtemp) {
                writeString("on");
              } else {
                writeString("off");
              }
            } else if (cmd.equals("heaton")) {
              heating = true;
              success();
            } else if (cmd.equals("heatoff")) {
              heating = false;
              success();
            }  else if (cmd.equals("bright")) {
              System.out.println("*** ITS BRIGHT IN HERE ***");
              success();
            } else if (cmd.equals("cold")) {
              System.out.println("*** ITS COLD OUTSIDE ***");
              success();
            } else if (cmd.equals("vol")) {
              writeInt(50);
            } else if (cmd.equals("beer")) {
              success();
            } else if (cmd.equals("clean")) {
              success();
            } else if (cmd.startsWith("temp")) {
              int n = Integer.parseInt(cmd.substring(4)) - 1;
              writeInt(temp[n]);
            } else if (cmd.equals("reqtemp")) {
              writeInt(reqtemp);
            } else if (cmd.startsWith("humid")) {
              int n = Integer.parseInt(cmd.substring(5)) - 1;
              writeInt(humidity[n]);
            } else if (cmd.startsWith("light")) {
              int n = Integer.parseInt(cmd.substring(5)) - 1;
              writeInt(light[n]);
            } else if (cmd.startsWith("settemp")) {
              reqtemp = Integer.parseInt(cmd.substring(7));
              success();
            } else if (cmd.equals("power")) {
              writeInt((int) power);							
            } else if (cmd.equals("rain")) {
              writeInt(50);
            } else if (cmd.equals("humidity")) {
              writeInt(80);
            } else if (cmd.startsWith("occupied")) {
              int n = Integer.parseInt(cmd.substring(8)) - 1;
              if (System.currentTimeMillis() - occupied[n] = '0' && c2 = 'a' && c2 = '0' && c1 = 'a' && c1 <= 'f')) code += ((10 + c1 - 'a') * 16);

              rfc.sendCmd((byte) code);
              System.out.println("Sending TiVo code " + code);
              success();
            }
            is.close();
            os.close();
            s.close();
            break;

          } else {
            cmd += (char) b;
          }

        } while(true);
      } catch (IOException e) {
        System.out.println("IO error:" + e.getMessage());
      }
    }
  }

  public static void main(String[] args) {
    (new ORControl()).run();
  }

  class ReadInput implements Runnable {
    int i = 0;
    public void run() {
      boolean energy = false;
      int limit = 4;
      for(;;) {
        int b = rfc.readByte();
        System.out.println("Read: " + b);
        if (i == 0) {
          energy = (b == 10);
          room = b-1;
          limit = b + 3; // Temporary. id has 5 bytes
        }
        if (energy && i == 1) {
          power = b  * 50f;
          System.out.println("power = " + power);
          i = 0;
          continue;
        }
        if (i == 4) temp[room] = b;
        else if (i == 3) voltage = b;
        else if (i == 2) light[room] = (int) (b / 2.56);
        else if (i == 1  && b == 1) occupied[room] = System.currentTimeMillis();
        else if (i == 5) {
          humidity[room] = b;
          System.out.println("Humidity = " + humidity[room]);
        }
        if (i++ == limit) i = 0;
      }

    }
  }

  private void writeString(String s) throws IOException {
    os.write(s.getBytes());
  }

  private void success() throws IOException {
    os.write('0');
  }

  private void writeInt(int n) throws IOException {
    String s = Integer.toString(n, 10);
    writeString(s);
  }
}

RFControl.java, which communicates with the transceiver:


import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

public class RFControl {
  private String portName = "COM9";
  private SerialPort serialPort;
  private static final int TIME_OUT = 2000;
  private static final int DATA_RATE = 9600;
  /** Buffered input stream from the port */

  private OutputStream output;
  private InputStream input;

  public RFControl() {
    initialize();
  }

  public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    // iterate through, looking for the port
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum
          .nextElement();
      if (currPortId.getName().equals(portName)) {
        portId = currPortId;
        break;
      }
    }

    if (portId == null) {
      System.err.println("Could not find COM port.");
      return;
    }

    try {
      // open serial port, and use class name for the appName.
      serialPort = (SerialPort) portId
          .open(this.getClass().getName(), TIME_OUT);

      // set port parameters
      serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8,
          SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      // open the streams
      output = serialPort.getOutputStream();
      input = serialPort.getInputStream();

    } catch (Exception e) {
      System.err.println(e.toString());
      System.exit(1);
    }

  }

  public void sendCmd(byte cmd) {
    if (output == null)
      return;
    try {
      output.write(cmd);
      output.flush();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public int readByte() {
    try {
      for (;;) {
        int i = input.read();
        if (i > 0)
          return (i & 0xFF);
      }
    } catch (IOException e) {
      System.err.println("IOException reading from transceiver");
      return 0;
    }
  }
}
Advertisements
This entry was posted in Electronics, Home automation. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s