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; }
/** * 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); } }