package `in`.caresoft.carepulse.connect.net import org.json.JSONObject import java.io.IOException import java.net.HttpURLConnection import java.net.URL class ApiException(val status: Int, message: String) : IOException(message) /** Minimal JSON client for the CarePulse REST API v1 (no third-party HTTP library). */ class Api(private val server: String, private val token: String? = null) { fun pair(code: String, deviceInfo: String, appVersion: String): JSONObject = call("POST", "/api/v1/gateway/pair", JSONObject().put("code", code).put("device_info", deviceInfo).put("app_version", appVersion).put("platform", "android")) fun config(): JSONObject = call("GET", "/api/v1/gateway/config", null) fun readings(body: JSONObject): JSONObject = call("POST", "/api/v1/readings", body) fun heartbeat(body: JSONObject): JSONObject = call("POST", "/api/v1/gateway/heartbeat", body) /** Today's medicine doses for the paired patient. */ fun medications(): JSONObject = call("GET", "/api/v1/medications", null) /** type: taken | skipped | puff */ fun dose(medicationId: Int, type: String, puffs: Int? = null): JSONObject { val ev = JSONObject().put("type", type).put("medication_id", medicationId) .put("at", java.time.OffsetDateTime.now().toString()) puffs?.let { ev.put("puffs", it) } return call("POST", "/api/v1/doses", JSONObject().put("events", org.json.JSONArray().put(ev))) } private fun call(method: String, path: String, body: JSONObject?): JSONObject { val url = URL(server.trimEnd('/') + path) require(url.protocol == "https" || url.host == "10.0.2.2" || url.host == "localhost") { "Server must use https" } val c = url.openConnection() as HttpURLConnection try { c.requestMethod = method c.connectTimeout = 15_000 c.readTimeout = 30_000 c.setRequestProperty("Accept", "application/json") token?.let { c.setRequestProperty("Authorization", "Bearer $it") } if (body != null) { c.doOutput = true c.setRequestProperty("Content-Type", "application/json") c.outputStream.use { it.write(body.toString().toByteArray()) } } val status = c.responseCode val text = (if (status < 400) c.inputStream else c.errorStream)?.bufferedReader()?.use { it.readText() } ?: "{}" val json = runCatching { JSONObject(text) }.getOrElse { JSONObject().put("ok", false).put("error", "Bad response from server") } if (status >= 400) throw ApiException(status, json.optString("error", "Server error $status")) return json } finally { c.disconnect() } } }