Exemplo n.º 1
0
  /**
   * Authenticate with the chosen bridge
   *
   * @param ip, the ip address of the bridge you want to authenticate with
   * @return the username of the hue bridge, that has been placed on the white list
   */
  private String authWithBridge(String ip)
      throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {

    URI uri = new URL("http://" + ip + "/api").toURI();

    DefaultHttpClient client = new DefaultHttpClient();
    HttpUriRequest request = new HttpPost(uri);

    JSONObject obj = new JSONObject();
    try {
      obj.put("devicetype", "OpenRemoteController");
    } catch (JSONException e) {
      logger.error("JSONExceptionn when creating json object", e);
    }

    StringEntity data = new StringEntity(obj.toString(), "UTF-8");

    ((HttpPost) request).setEntity(data);
    String resp = "";
    HttpResponse response = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    request.addHeader("User-Agent", "OpenRemoteController");
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    request.addHeader("Content-Type", "applicaion/json");

    try {
      response = client.execute(request);
      resp = responseHandler.handleResponse(response);
    } catch (ClientProtocolException e) {
      logger.error("ClientProtocolException when executing HTTP method", e);
    } catch (IOException e) {
      logger.error("IOException when executing HTTP method", e);
    } finally {
      try {
        if ((response != null) && (response.getEntity() != null)) {
          response.getEntity().consumeContent();
        }
      } catch (IOException ignored) {
      }
      client.getConnectionManager().shutdown();
    }

    JSONObject jsonResponse = null;
    String jsonUsername = "";
    try {
      jsonResponse = new JSONArray(resp.toString()).getJSONObject(0).getJSONObject("success");
      jsonUsername = jsonResponse.getString("username");
    } catch (JSONException e) {
      logger.error("JSONException when reading returned json", e);
    }
    return jsonUsername;
  }
Exemplo n.º 2
0
  /**
   * Returns a logger instance registered with a global java.util.logging LogManager.
   *
   * <p>This instance provides additional convenience API on top of the default
   * java.util.logging.Logger API to make it easier to switch implementations between JUL and Log4j.
   *
   * @param name A log category name. This should always be a subcategory of {@link
   *     Constants#CONTROLLER_ROOT_LOG_CATEGORY}.
   * @return A JUL Logger subclass with additional convenience API for logging.
   */
  public static Logger getLogger(String name) {

    // Sanity check and warn of suspicious use pattern...

    if (!name.startsWith(Constants.CONTROLLER_ROOT_LOG_CATEGORY)) {
      java.util.logging.Logger.getLogger("")
          .warning(
              "Log category '"
                  + name
                  + "' is not using parent log category "
                  + Constants.CONTROLLER_ROOT_LOG_CATEGORY
                  + ". The logging behavior not be "
                  + "what was expected.");
    }

    Logger l = new Logger(name);

    logManager.addLogger(l);

    try {
      return (Logger) logManager.getLogger(name);
    } catch (ClassCastException e) {
      System.err.println(
          "\n\n"
              + "---------------------------------------------------------------------------------\n\n"
              + "  An incompatible logger was already associated "
              + "  with category '"
              + name
              + "'.\n\n"
              + "  Logging to this category is unlikely to work as intended.\n\n"
              + "---------------------------------------------------------------------------------\n\n");

      // The logging is unlikely to work but return a valid reference anyway to avoid
      // NPE's and such...

      l.addHandler(new ConsoleHandler());

      return l;
    }
  }
Exemplo n.º 3
0
  /**
   * Start authenticating with the chosen Hue Bridge, and save it to disk if everything is ok
   *
   * @param id Hue Bridge ID
   * @param ip Internal ip address of the local Hue Bridge
   * @param mac Mac address of the local Hue Bridge
   */
  public String setChosenBridge(String id, String ip, String mac)
      throws MalformedURLException, UnsupportedEncodingException, JSONException,
          URISyntaxException {
    Bridge chosenBridge = new Bridge(id, ip, mac);

    String username = authWithBridge(ip);
    if (username != "") {
      chosenBridge.setUsername(username);
      saveUsernameToDisk(chosenBridge);
    } else {
      logger.info("Username is empty, not saving to disk");
    }
    return username;
  }
  private Set<Integer> parseStatusSensorIDsStrToSet(String unParsedSensorIDs) {
    String[] parsedSensorIDs =
        unParsedSensorIDs.split(Constants.STATUS_POLLING_SENSOR_IDS_SEPARATOR);
    Set<Integer> statusSensorIDs = new HashSet<Integer>();

    for (String statusSensorID : parsedSensorIDs) {
      try {
        statusSensorIDs.add(Integer.parseInt(statusSensorID));
      } catch (NumberFormatException e) {
        log.warn("Sensor ID = {0} is not a valid integer ID. Skipping...", statusSensorID);
      }
    }

    return statusSensorIDs;
  }
/** CommandBuilder subclass for Lagarto command */
public class LagartoCommandBuilder implements CommandBuilder {

  public static final String LAGARTO_PROTOCOL_LOG_CATEGORY =
      Constants.CONTROLLER_PROTOCOL_LOG_CATEGORY + "lagarto";
  private static final Logger logger = Logger.getLogger(LAGARTO_PROTOCOL_LOG_CATEGORY);

  public static ControllerConfiguration controllerConfig;

  /** Class constructor */
  public LagartoCommandBuilder() {}

  /** {@inheritDoc} */
  @SuppressWarnings("unchecked")
  public Command build(Element element) {
    List<Element> propertyEles = element.getChildren("property", element.getNamespace());
    String networkName = null;
    String epId = null;
    String epValue = null;

    // read values from config xml
    for (Element ele : propertyEles) {
      String elementName = ele.getAttributeValue(CommandBuilder.XML_ATTRIBUTENAME_NAME);
      String elementValue = ele.getAttributeValue(CommandBuilder.XML_ATTRIBUTENAME_VALUE);
      if ("network".equals(elementName)) networkName = elementValue;
      else if ("epid".equals(elementName)) epId = elementValue;
      else if ("value".equals(elementName))
        epValue = CommandUtil.parseStringWithParam(element, elementValue);
    }

    LagartoCommand cmd = new LagartoCommand(networkName, epId, epValue);

    return cmd;
  }

  /** Get controller configuration */
  public ControllerConfiguration getConfiguration() {
    return controllerConfig;
  }

  /** Set controller configuration */
  public void setConfiguration(ControllerConfiguration configuration) {
    controllerConfig = configuration;
  }
}
Exemplo n.º 6
0
  /**
   * Save the connected bridge to disk
   *
   * @param bridge, {@link Bridge} object that needs to be saved
   */
  private void saveUsernameToDisk(Bridge bridge) throws JSONException {
    try {

      String content = bridge.bridgeToJson().toString();
      File file = new File(BRIDGEFILE);

      if (!file.exists()) {
        file.createNewFile();
      }
      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(content);
      bw.close();
      System.out.println("Bridge saved to Disk");

    } catch (IOException e) {
      logger.error("IOException when saving hue bridge info to disk", e);
    }
  }
Exemplo n.º 7
0
/**
 * {@link BridgeFinder} is used to find active Hue Bridges in the local network. It can return a
 * list of {@link Bridge}. It is also used to authenticate with a bridge.
 *
 * @author TASS Technology Solutions - www.tass.nl
 */
public class BridgeFinder {

  private static String BRIDGEFILE = "../webapps/controller/WEB-INF/classes/huebridge.json";

  private static Logger logger =
      Logger.getLogger(HueBridgeCommandBuilder.HUEBRIDGE_PROTOCOL_LOG_CATEGORY);

  /** @return an ArrayList of {@link Bridge} found in the network */
  public ArrayList<Bridge> getBridges() throws IOException, JSONException {
    String json = discoverLocalBridge();
    return convertJsonToBridge(json);
  }

  /**
   * Call to the meethue website to get all local Hue bridges in the network
   *
   * @return JSON string with information about the detected Hue bridges
   */
  private String discoverLocalBridge() throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpUriRequest request = new HttpGet("http://www.meethue.com/api/nupnp");
    String resp = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    resp = client.execute(request, responseHandler);
    return resp;
  }

  /**
   * Create objects of the data from discoverLocalBridge()
   *
   * @param json, the json string with all local brides from {@link #discoverLocalBridge()}
   * @return Arraylist of {@link Bridge} objects
   */
  private ArrayList<Bridge> convertJsonToBridge(String json) throws JSONException {
    ArrayList<Bridge> bridges = new ArrayList<Bridge>();
    JSONArray arr = new JSONArray(json);
    for (int i = 0; i < arr.length(); i++) {
      JSONObject jsonBridge = arr.getJSONObject(i);
      bridges.add(
          new Bridge(
              jsonBridge.getString("id"),
              jsonBridge.getString("internalipaddress"),
              jsonBridge.getString("macaddress")));
    }
    return bridges;
  }

  /**
   * Start authenticating with the chosen Hue Bridge, and save it to disk if everything is ok
   *
   * @param id Hue Bridge ID
   * @param ip Internal ip address of the local Hue Bridge
   * @param mac Mac address of the local Hue Bridge
   */
  public String setChosenBridge(String id, String ip, String mac)
      throws MalformedURLException, UnsupportedEncodingException, JSONException,
          URISyntaxException {
    Bridge chosenBridge = new Bridge(id, ip, mac);

    String username = authWithBridge(ip);
    if (username != "") {
      chosenBridge.setUsername(username);
      saveUsernameToDisk(chosenBridge);
    } else {
      logger.info("Username is empty, not saving to disk");
    }
    return username;
  }

  /**
   * Save the connected bridge to disk
   *
   * @param bridge, {@link Bridge} object that needs to be saved
   */
  private void saveUsernameToDisk(Bridge bridge) throws JSONException {
    try {

      String content = bridge.bridgeToJson().toString();
      File file = new File(BRIDGEFILE);

      if (!file.exists()) {
        file.createNewFile();
      }
      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(content);
      bw.close();
      System.out.println("Bridge saved to Disk");

    } catch (IOException e) {
      logger.error("IOException when saving hue bridge info to disk", e);
    }
  }

  /**
   * Authenticate with the chosen bridge
   *
   * @param ip, the ip address of the bridge you want to authenticate with
   * @return the username of the hue bridge, that has been placed on the white list
   */
  private String authWithBridge(String ip)
      throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {

    URI uri = new URL("http://" + ip + "/api").toURI();

    DefaultHttpClient client = new DefaultHttpClient();
    HttpUriRequest request = new HttpPost(uri);

    JSONObject obj = new JSONObject();
    try {
      obj.put("devicetype", "OpenRemoteController");
    } catch (JSONException e) {
      logger.error("JSONExceptionn when creating json object", e);
    }

    StringEntity data = new StringEntity(obj.toString(), "UTF-8");

    ((HttpPost) request).setEntity(data);
    String resp = "";
    HttpResponse response = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    request.addHeader("User-Agent", "OpenRemoteController");
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    request.addHeader("Content-Type", "applicaion/json");

    try {
      response = client.execute(request);
      resp = responseHandler.handleResponse(response);
    } catch (ClientProtocolException e) {
      logger.error("ClientProtocolException when executing HTTP method", e);
    } catch (IOException e) {
      logger.error("IOException when executing HTTP method", e);
    } finally {
      try {
        if ((response != null) && (response.getEntity() != null)) {
          response.getEntity().consumeContent();
        }
      } catch (IOException ignored) {
      }
      client.getConnectionManager().shutdown();
    }

    JSONObject jsonResponse = null;
    String jsonUsername = "";
    try {
      jsonResponse = new JSONArray(resp.toString()).getJSONObject(0).getJSONObject("success");
      jsonUsername = jsonResponse.getString("username");
    } catch (JSONException e) {
      logger.error("JSONException when reading returned json", e);
    }
    return jsonUsername;
  }

  public Bridge getSavedBridge() {
    Bridge bridge;
    File file = new File(BRIDGEFILE);
    StringBuilder json = new StringBuilder();
    try {
      if (!file.exists()) {
        return null;
      }
      FileReader fr = new FileReader(file.getAbsolutePath());
      BufferedReader br = new BufferedReader(fr);
      String currentLine = null;

      while ((currentLine = br.readLine()) != null) {
        json.append(currentLine);
      }
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    try {
      JSONObject jo = new JSONObject(json.toString());
      bridge =
          new Bridge(jo.getString("id"), jo.getString("internalip"), jo.getString("macaddres"));
      bridge.setUsername(jo.getString("username"));
    } catch (JSONException e) {
      e.printStackTrace();
      return null;
    }
    return bridge;
  }
}
/**
 * TODO
 *
 * @author Handy.Wang 2009-10-15
 * @author <a href="mailto:[email protected]">Juha Lindfors</a>
 */
public class StatusCommandServiceImpl implements StatusCommandService {
  // Class Members --------------------------------------------------------------------------------

  private static final Logger log = Logger.getLogger(Constants.XML_PARSER_LOG_CATEGORY);

  // Instance Fields ------------------------------------------------------------------------------

  private StatusCache statusCache;
  private Deployer deployer;

  // Constructors ---------------------------------------------------------------------------------

  public StatusCommandServiceImpl(Deployer deployer, StatusCache statusCache) {
    this.deployer = deployer;
    this.statusCache = statusCache;
  }

  // Implements StatusCommandService --------------------------------------------------------------

  @Override
  public String readFromCache(String unParsedSensorIDs) {
    if (deployer.isPaused()) {
      throw new ControllerXMLChangedException("The content of controller.xml had changed.");
    }

    Set<Integer> statusSensorIDs = parseStatusSensorIDsStrToSet(unParsedSensorIDs);
    Map<Integer, String> latestStatuses = statusCache.queryStatus(statusSensorIDs);

    StringBuffer sb = new StringBuffer();
    sb.append(Constants.STATUS_XML_HEADER);
    Set<Integer> sensorIDs = latestStatuses.keySet();

    for (Integer sensorID : sensorIDs) {
      sb.append("<")
          .append(Constants.STATUS_XML_STATUS_RESULT_ELEMENT_NAME)
          .append(" ")
          .append(Constants.STATUS_XML_STATUS_RESULT_ELEMENT_SENSOR_IDENTITY)
          .append("=\"")
          .append(sensorID)
          .append("\">");

      sb.append(latestStatuses.get(sensorID));
      sb.append("</");
      sb.append(Constants.STATUS_XML_STATUS_RESULT_ELEMENT_NAME + ">\n");
      sb.append("\n");
    }

    sb.append(Constants.STATUS_XML_TAIL);

    return sb.toString();
  }

  // Private Instance Methods ---------------------------------------------------------------------

  private Set<Integer> parseStatusSensorIDsStrToSet(String unParsedSensorIDs) {
    String[] parsedSensorIDs =
        unParsedSensorIDs.split(Constants.STATUS_POLLING_SENSOR_IDS_SEPARATOR);
    Set<Integer> statusSensorIDs = new HashSet<Integer>();

    for (String statusSensorID : parsedSensorIDs) {
      try {
        statusSensorIDs.add(Integer.parseInt(statusSensorID));
      } catch (NumberFormatException e) {
        log.warn("Sensor ID = {0} is not a valid integer ID. Skipping...", statusSensorID);
      }
    }

    return statusSensorIDs;
  }
}
/** @author Marcus */
public class RussoundCommand implements EventListener, ExecutableCommand {

  // Class Members --------------------------------------------------------------------------------
  private static final Logger logger =
      Logger.getLogger(RussoundCommandBuilder.RUSSOUND_PROTOCOL_LOG_CATEGORY);

  // Instance Fields ------------------------------------------------------------------------------
  private String controller;
  private String zone;
  private RussCmdEnum command;
  private String paramValue;
  private RussoundClient commClient;

  // Constructor ---------------------------------------------------------------------
  public RussoundCommand(
      String controller,
      String zone,
      RussCmdEnum command,
      String paramValue,
      RussoundClient commClient) {
    this.controller = controller;
    this.zone = zone;
    this.command = command;
    this.paramValue = paramValue;
    this.commClient = commClient;
  }

  @Override
  public void send() {
    switch (command) {
      case ALL_ON:
        commClient.setAllOnOffPower(1);
        break;
      case ALL_OFF:
        commClient.setAllOnOffPower(0);
        break;
      case POWER_OFF:
        commClient.setPower(controller, zone, 0);
        break;
      case POWER_ON:
        commClient.setPower(controller, zone, 1);
        break;
      case SET_VOLUME:
        commClient.setVolume(controller, zone, paramValue);
        break;
      case VOL_UP:
        commClient.setVolumeUp(controller, zone);
        break;
      case VOL_DOWN:
        commClient.setVolumeDown(controller, zone);
        break;
      case SELECT_SOURCE1:
        commClient.setSource(controller, zone, "1");
        break;
      case SELECT_SOURCE2:
        commClient.setSource(controller, zone, "2");
        break;
      case SELECT_SOURCE3:
        commClient.setSource(controller, zone, "3");
        break;
      case SELECT_SOURCE4:
        commClient.setSource(controller, zone, "4");
        break;
      case SELECT_SOURCE5:
        commClient.setSource(controller, zone, "5");
        break;
      case SELECT_SOURCE6:
        commClient.setSource(controller, zone, "6");
        break;
      case SELECT_SOURCE7:
        commClient.setSource(controller, zone, "7");
        break;
      case SELECT_SOURCE8:
        commClient.setSource(controller, zone, "8");
        break;
      case SET_SOURCE:
        commClient.setSource(controller, zone, paramValue);
        break;
      case SET_LOUDNESS_OFF:
        commClient.setSettings(controller, zone, command, "0");
        break;
      case SET_LOUDNESS_ON:
        commClient.setSettings(controller, zone, command, "1");
        break;
      case SET_PARTYMODE_OFF:
        commClient.setSettings(controller, zone, command, "0");
        break;
      case SET_PARTYMODE_ON:
        commClient.setSettings(controller, zone, command, "1");
        break;
      case SET_BASS_LEVEL:
        commClient.setSettings(controller, zone, command, paramValue);
        break;
      case SET_TREBLE_LEVEL:
        commClient.setSettings(controller, zone, command, paramValue);
        break;
      case SET_BALANCE_LEVEL:
        commClient.setSettings(controller, zone, command, paramValue);
        break;
      case SET_TURNON_VOLUME:
        commClient.setSettings(controller, zone, command, paramValue);
        break;
    }

    // Give it some time before requesting the changed status
    try {
      Thread.sleep(300);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Request new status after sending a command
    if ((command == RussCmdEnum.ALL_OFF) || (command == RussCmdEnum.ALL_OFF)) {
      // Wait a little longer after the "ALL" commands since the russound has more todo
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      commClient.updateAllZones();
    } else {
      commClient.requestStatus(controller, zone);
    }
  }

  @Override
  public void setSensor(Sensor sensor) {
    logger.debug("*** setSensor called as part of EventListener init *** sensor is: " + sensor);
    commClient.addSensor(controller, zone, command, sensor);
  }

  @Override
  public void stop(Sensor sensor) {
    commClient.removeSensor(controller, zone, command, sensor);
  }
}
Exemplo n.º 10
0
 @Override
 public void setSensor(Sensor sensor) {
   logger.debug("*** setSensor called as part of EventListener init *** sensor is: " + sensor);
   commClient.addSensor(controller, zone, command, sensor);
 }