Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package alexaactions; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.util.*; /** * * @author Paul Cifarelli */ public class SmartThingsTemperatureDevices { private final SmartThingsAgent agent; private final JSONParser parser; private final String path; private String tempScale; SmartThingsTemperatureDevices(SmartThingsAgent sa) { agent = sa; parser = new JSONParser(); path = "temps"; String jsonScale = agent.get(path + "/units"); Object obj = null; JSONObject jobj = null; try { obj = (Object) parser.parse(jsonScale); jobj = (JSONObject) obj; } catch (ParseException ex) { Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex); System.out.println("defaulting to F scale"); tempScale = "F"; } tempScale = (String) jobj.get("units"); } String getById(String id) { String device = agent.getById(path, id); if (device == null) { return null; } JSONObject obj = null; try { obj = (JSONObject) parser.parse(device); } catch (ParseException ex) { Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex); return null; } if (obj != null) { return getJson((String) obj.get("value"), tempScale); } return null; } String getByLabel(String label) { String device = agent.getByLabel(path, label); if (device == null) { return null; } JSONObject obj = null; try { obj = (JSONObject) parser.parse(device); } catch (ParseException ex) { Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex); } if (obj != null) { return getJson((String) obj.get("value"), tempScale); } return null; } String get(String idorlabel) { String result = getById(idorlabel); if (result == null) { return getByLabel(idorlabel); } return result; } private String getJson(String value, String units) { JSONObject jobj = new JSONObject(); jobj.put("temp", value); jobj.put("units", units); return jobj.toJSONString(); } }