NSCv3: Connect to new alarm socket.io

This commit is contained in:
Milos Kozak 2023-01-24 22:32:07 +01:00
parent 89ad9e21dd
commit e7225ce602
3 changed files with 100 additions and 115 deletions

View file

@ -4,7 +4,6 @@ import dagger.android.HasAndroidInjector
import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.notifications.Notification
import info.nightscout.interfaces.nsclient.NSAlarm import info.nightscout.interfaces.nsclient.NSAlarm
import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.ActivePlugin
import info.nightscout.interfaces.profile.DefaultValueHelper
import info.nightscout.plugins.R import info.nightscout.plugins.R
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
@ -21,7 +20,6 @@ class NotificationWithAction constructor(
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rh: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
init { init {
@ -66,7 +64,7 @@ class NotificationWithAction constructor(
aapsLogger.debug(LTag.NOTIFICATION, "Notification text is: $text") aapsLogger.debug(LTag.NOTIFICATION, "Notification text is: $text")
val msToSnooze = sp.getInt(info.nightscout.core.utils.R.string.key_ns_alarm_stale_data_value, 15) * 60 * 1000L val msToSnooze = sp.getInt(info.nightscout.core.utils.R.string.key_ns_alarm_stale_data_value, 15) * 60 * 1000L
aapsLogger.debug(LTag.NOTIFICATION, "snooze nsalarm_staledatavalue in minutes is ${T.msecs(msToSnooze).mins()} currentTimeMillis is: ${System.currentTimeMillis()}") aapsLogger.debug(LTag.NOTIFICATION, "snooze nsalarm_staledatavalue in minutes is ${T.msecs(msToSnooze).mins()} currentTimeMillis is: ${System.currentTimeMillis()}")
sp.putLong(info.nightscout.core.utils.R.string.key_snoozed_to, System.currentTimeMillis() + msToSnooze) sp.putLong(rh.gs(info.nightscout.core.utils.R.string.key_snoozed_to) + nsAlarm.level(), System.currentTimeMillis() + msToSnooze)
} }
} }

View file

@ -646,7 +646,7 @@ class NSClientService : DaggerService() {
private fun handleAlarm(alarm: JSONObject) { private fun handleAlarm(alarm: JSONObject) {
val defaultVal = config.NSCLIENT val defaultVal = config.NSCLIENT
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, defaultVal)) { if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, defaultVal)) {
val snoozedTo = sp.getLong(info.nightscout.core.utils.R.string.key_snoozed_to, 0L) val snoozedTo = sp.getLong(rh.gs(info.nightscout.core.utils.R.string.key_snoozed_to) + alarm.optString("level"), 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val nsAlarm = NSAlarm(alarm) val nsAlarm = NSAlarm(alarm)
uiInteraction.addNotificationWithAction(injector, nsAlarm) uiInteraction.addNotificationWithAction(injector, nsAlarm)
@ -659,7 +659,7 @@ class NSClientService : DaggerService() {
private fun handleUrgentAlarm(alarm: JSONObject) { private fun handleUrgentAlarm(alarm: JSONObject) {
val defaultVal = config.NSCLIENT val defaultVal = config.NSCLIENT
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, defaultVal)) { if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, defaultVal)) {
val snoozedTo = sp.getLong(info.nightscout.core.utils.R.string.key_snoozed_to, 0L) val snoozedTo = sp.getLong(rh.gs(info.nightscout.core.utils.R.string.key_snoozed_to) + alarm.optString("level"), 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val nsAlarm = NSAlarm(alarm) val nsAlarm = NSAlarm(alarm)
uiInteraction.addNotificationWithAction(injector, nsAlarm) uiInteraction.addNotificationWithAction(injector, nsAlarm)

View file

@ -35,7 +35,6 @@ import info.nightscout.interfaces.sync.NsClient
import info.nightscout.interfaces.sync.Sync import info.nightscout.interfaces.sync.Sync
import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.ui.UiInteraction
import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.interfaces.utils.HtmlHelper
import info.nightscout.interfaces.utils.JsonHelper
import info.nightscout.interfaces.workflow.WorkerClasses import info.nightscout.interfaces.workflow.WorkerClasses
import info.nightscout.plugins.sync.R import info.nightscout.plugins.sync.R
import info.nightscout.plugins.sync.nsShared.NSClientFragment import info.nightscout.plugins.sync.nsShared.NSClientFragment
@ -192,9 +191,9 @@ class NSClientV3Plugin @Inject constructor(
.toObservable(EventNSConnectivityOptionChanged::class.java) .toObservable(EventNSConnectivityOptionChanged::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ev -> .subscribe({ ev ->
rxBus.send(EventNSClientNewLog("● CONNECTIVITY CHANGE", ev.blockingReason)) rxBus.send(EventNSClientNewLog("● CONNECTIVITY", ev.blockingReason))
setClient("CONNECTIVITY_CHANGE") setClient("CONNECTIVITY")
if (isAllowed) executeLoop("CONNECTIVITY_CHANGE", forceNew = false) if (isAllowed) executeLoop("CONNECTIVITY", forceNew = false)
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
@ -269,7 +268,8 @@ class NSClientV3Plugin @Inject constructor(
override fun onStop() { override fun onStop() {
handler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
disposable.clear() disposable.clear()
socket?.disconnect() storageSocket?.disconnect()
alarmSocket?.disconnect()
super.onStop() super.onStop()
} }
@ -300,8 +300,10 @@ class NSClientV3Plugin @Inject constructor(
context = context, context = context,
logging = true logging = true
) )
if (wsConnected) if (wsConnected) {
socket?.disconnect() storageSocket?.disconnect()
alarmSocket?.disconnect()
}
SystemClock.sleep(2000) SystemClock.sleep(2000)
initializeWebSockets(reason) initializeWebSockets(reason)
rxBus.send(EventSWSyncStatus(status)) rxBus.send(EventSWSyncStatus(status))
@ -310,32 +312,36 @@ class NSClientV3Plugin @Inject constructor(
/********************** /**********************
WS code WS code
**********************/ **********************/
private var connectCounter = 0 private var storageSocket: Socket? = null
private var socket: Socket? = null private var alarmSocket: Socket? = null
var wsConnected = false var wsConnected = false
internal var initialLoadFinished = false internal var initialLoadFinished = false
private fun initializeWebSockets(reason: String) { private fun initializeWebSockets(reason: String) {
if (!sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_use_ws, true)) return if (!sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_use_ws, true)) return
val url = sp.getString(info.nightscout.core.utils.R.string.key_nsclientinternal_url, "").lowercase().replace(Regex("/$"), "") + "/storage" if (sp.getString(info.nightscout.core.utils.R.string.key_nsclientinternal_url, "").isEmpty()) return
val urlStorage = sp.getString(info.nightscout.core.utils.R.string.key_nsclientinternal_url, "").lowercase().replace(Regex("/$"), "") + "/storage"
val urlAlarm = sp.getString(info.nightscout.core.utils.R.string.key_nsclientinternal_url, "").lowercase().replace(Regex("/$"), "") + "/alarm"
if (!isAllowed) { if (!isAllowed) {
rxBus.send(EventNSClientNewLog("● WS", blockingReason)) rxBus.send(EventNSClientNewLog("● WS", blockingReason))
} else if (sp.getBoolean(R.string.key_ns_paused, false)) { } else if (sp.getBoolean(R.string.key_ns_paused, false)) {
rxBus.send(EventNSClientNewLog("● WS", "paused")) rxBus.send(EventNSClientNewLog("● WS", "paused"))
} else if (url != "") { } else {
try { try {
//rxBus.send(EventNSClientStatus("Connecting ...")) // java io.client doesn't support multiplexing. create 2 sockets
val opt = IO.Options().also { storageSocket = IO.socket(urlStorage).also { socket ->
it.forceNew = true socket.on(Socket.EVENT_CONNECT, onConnectStorage)
//it.webSocketFactory = nsAndroidClient. socket.on(Socket.EVENT_DISCONNECT, onDisconnectStorage)
} rxBus.send(EventNSClientNewLog("► WS", "do connect storage $reason"))
socket = IO.socket(url, opt).also { socket ->
socket.on(Socket.EVENT_CONNECT, onConnect)
socket.on(Socket.EVENT_DISCONNECT, onDisconnect)
rxBus.send(EventNSClientNewLog("► WS", "do connect $reason"))
socket.connect() socket.connect()
socket.on("create", onDataCreateUpdate) socket.on("create", onDataCreateUpdate)
socket.on("update", onDataCreateUpdate) socket.on("update", onDataCreateUpdate)
socket.on("delete", onDataDelete) socket.on("delete", onDataDelete)
}
alarmSocket = IO.socket(urlAlarm).also { socket ->
socket.on(Socket.EVENT_CONNECT, onConnectAlarms)
socket.on(Socket.EVENT_DISCONNECT, onDisconnectAlarm)
rxBus.send(EventNSClientNewLog("► WS", "do connect alarm $reason"))
socket.connect()
socket.on("announcement", onAnnouncement) socket.on("announcement", onAnnouncement)
socket.on("alarm", onAlarm) socket.on("alarm", onAlarm)
socket.on("urgent_alarm", onUrgentAlarm) socket.on("urgent_alarm", onUrgentAlarm)
@ -346,22 +352,19 @@ class NSClientV3Plugin @Inject constructor(
} catch (e: RuntimeException) { } catch (e: RuntimeException) {
rxBus.send(EventNSClientNewLog("● WS", "RuntimeException")) rxBus.send(EventNSClientNewLog("● WS", "RuntimeException"))
} }
} else {
rxBus.send(EventNSClientNewLog("● WS", "No NS URL specified"))
} }
} }
private val onConnect = Emitter.Listener { private val onConnectStorage = Emitter.Listener {
connectCounter++ val socketId = storageSocket?.id() ?: "NULL"
val socketId = socket?.id() ?: "NULL" rxBus.send(EventNSClientNewLog("◄ WS", "connected storage ID: $socketId"))
rxBus.send(EventNSClientNewLog("◄ WS", "connect #$connectCounter event. ID: $socketId")) if (storageSocket != null) {
if (socket != null) {
val authMessage = JSONObject().also { val authMessage = JSONObject().also {
it.put("accessToken", sp.getString(R.string.key_ns_client_token, "")) it.put("accessToken", sp.getString(R.string.key_ns_client_token, ""))
it.put("collections", JSONArray(arrayOf<String>("devicestatus", "entries", "profile", "treatments", "foods", "settings"))) it.put("collections", JSONArray(arrayOf("devicestatus", "entries", "profile", "treatments", "foods", "settings")))
} }
rxBus.send(EventNSClientNewLog("► WS", "requesting auth")) rxBus.send(EventNSClientNewLog("► WS", "requesting auth for storage"))
socket?.emit("subscribe", authMessage, Ack { args -> storageSocket?.emit("subscribe", authMessage, Ack { args ->
val response = args[0] as JSONObject val response = args[0] as JSONObject
wsConnected = if (response.optBoolean("success")) { wsConnected = if (response.optBoolean("success")) {
rxBus.send(EventNSClientNewLog("◄ WS", "Subscribed for: ${response.optString("collections")}")) rxBus.send(EventNSClientNewLog("◄ WS", "Subscribed for: ${response.optString("collections")}"))
@ -374,12 +377,39 @@ class NSClientV3Plugin @Inject constructor(
} }
} }
private val onDisconnect = Emitter.Listener { args -> private val onConnectAlarms = Emitter.Listener {
aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: ${args[0]}") val socketId = alarmSocket?.id() ?: "NULL"
rxBus.send(EventNSClientNewLog("◄ WS", "disconnect event")) rxBus.send(EventNSClientNewLog("◄ WS", "connected alarms ID: $socketId"))
if (alarmSocket != null) {
val authMessage = JSONObject().also {
it.put("accessToken", sp.getString(R.string.key_ns_client_token, ""))
}
rxBus.send(EventNSClientNewLog("► WS", "requesting auth for alarms"))
alarmSocket?.emit("subscribe", authMessage, Ack { args ->
val response = args[0] as JSONObject
wsConnected = if (response.optBoolean("success")) {
rxBus.send(EventNSClientNewLog("◄ WS", response.optString("message")))
true
} else {
rxBus.send(EventNSClientNewLog("◄ WS", "Auth failed"))
false
}
})
}
}
private val onDisconnectStorage = Emitter.Listener { args ->
aapsLogger.debug(LTag.NSCLIENT, "disconnect storage reason: ${args[0]}")
rxBus.send(EventNSClientNewLog("◄ WS", "disconnect storage event"))
wsConnected = false wsConnected = false
initialLoadFinished = false initialLoadFinished = false
socket = null storageSocket = null
}
private val onDisconnectAlarm = Emitter.Listener { args ->
aapsLogger.debug(LTag.NSCLIENT, "disconnect alarm reason: ${args[0]}")
rxBus.send(EventNSClientNewLog("◄ WS", "disconnect alarm event"))
alarmSocket = null
} }
private val onDataCreateUpdate = Emitter.Listener { args -> private val onDataCreateUpdate = Emitter.Listener { args ->
@ -454,13 +484,11 @@ class NSClientV3Plugin @Inject constructor(
"key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da" "key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da"
} }
*/ */
val data: JSONObject val data = args[0] as JSONObject
try { rxBus.send(EventNSClientNewLog("◄ ANNOUNCEMENT", data.optString("message")))
data = args[0] as JSONObject aapsLogger.debug(LTag.NSCLIENT, data.toString())
handleAnnouncement(data) if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_announcements, config.NSCLIENT))
} catch (e: Exception) { uiInteraction.addNotificationWithAction(injector, NSAlarm(data))
aapsLogger.error("Unhandled exception", e)
}
} }
private val onAlarm = Emitter.Listener { args -> private val onAlarm = Emitter.Listener { args ->
@ -477,23 +505,27 @@ class NSClientV3Plugin @Inject constructor(
"key":"simplealarms_1" "key":"simplealarms_1"
} }
*/ */
val data: JSONObject val data = args[0] as JSONObject
try { rxBus.send(EventNSClientNewLog("◄ ALARM", data.optString("message")))
data = args[0] as JSONObject aapsLogger.debug(LTag.NSCLIENT, data.toString())
handleAlarm(data) if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, config.NSCLIENT)) {
} catch (e: Exception) { val snoozedTo = sp.getLong(rh.gs(info.nightscout.core.utils.R.string.key_snoozed_to) + data.optString("level"), 0L)
aapsLogger.error("Unhandled exception", e) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo)
uiInteraction.addNotificationWithAction(injector, NSAlarm(data))
} }
} }
private val onUrgentAlarm = Emitter.Listener { args: Array<Any> -> private val onUrgentAlarm = Emitter.Listener { args: Array<Any> ->
val data: JSONObject val data = args[0] as JSONObject
try { rxBus.send(EventNSClientNewLog("◄ URGENT ALARM", data.optString("message")))
data = args[0] as JSONObject aapsLogger.debug(LTag.NSCLIENT, data.toString())
handleUrgentAlarm(data) if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, config.NSCLIENT)) {
} catch (e: Exception) { val snoozedTo = sp.getLong(rh.gs(info.nightscout.core.utils.R.string.key_snoozed_to) + data.optString("level"), 0L)
aapsLogger.error("Unhandled exception", e) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo)
uiInteraction.addNotificationWithAction(injector, NSAlarm(data))
} }
} }
private val onClearAlarm = Emitter.Listener { args -> private val onClearAlarm = Emitter.Listener { args ->
/* /*
@ -504,52 +536,21 @@ class NSClientV3Plugin @Inject constructor(
"group":"default" "group":"default"
} }
*/ */
val data: JSONObject val data = args[0] as JSONObject
try { rxBus.send(EventNSClientNewLog("◄ CLEARALARM", data.optString("title")))
data = args[0] as JSONObject aapsLogger.debug(LTag.NSCLIENT, data.toString())
rxBus.send(EventNSClientNewLog("CLEARALARM", "received")) rxBus.send(EventDismissNotification(Notification.NS_ALARM))
rxBus.send(EventDismissNotification(Notification.NS_ALARM)) rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM))
rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM))
aapsLogger.debug(LTag.NSCLIENT, data.toString())
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
}
} }
private fun handleAnnouncement(announcement: JSONObject) { override fun handleClearAlarm(originalAlarm: NSAlarm, silenceTimeInMilliseconds: Long) {
val defaultVal = config.NSCLIENT if (!isEnabled()) return
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_announcements, defaultVal)) { if (!sp.getBoolean(R.string.key_ns_upload, true)) {
val nsAlarm = NSAlarm(announcement) aapsLogger.debug(LTag.NSCLIENT, "Upload disabled. Message dropped")
uiInteraction.addNotificationWithAction(injector, nsAlarm) return
rxBus.send(EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(announcement, "message", "received")))
aapsLogger.debug(LTag.NSCLIENT, announcement.toString())
}
}
private fun handleAlarm(alarm: JSONObject) {
val defaultVal = config.NSCLIENT
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, defaultVal)) {
val snoozedTo = sp.getLong(info.nightscout.core.utils.R.string.key_snoozed_to, 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val nsAlarm = NSAlarm(alarm)
uiInteraction.addNotificationWithAction(injector, nsAlarm)
}
rxBus.send(EventNSClientNewLog("ALARM", JsonHelper.safeGetString(alarm, "message", "received")))
aapsLogger.debug(LTag.NSCLIENT, alarm.toString())
}
}
private fun handleUrgentAlarm(alarm: JSONObject) {
val defaultVal = config.NSCLIENT
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_alarms, defaultVal)) {
val snoozedTo = sp.getLong(info.nightscout.core.utils.R.string.key_snoozed_to, 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val nsAlarm = NSAlarm(alarm)
uiInteraction.addNotificationWithAction(injector, nsAlarm)
}
rxBus.send(EventNSClientNewLog("URGENTALARM", JsonHelper.safeGetString(alarm, "message", "received")))
aapsLogger.debug(LTag.NSCLIENT, alarm.toString())
} }
alarmSocket?.emit("ack", originalAlarm.level(), originalAlarm.group(), silenceTimeInMilliseconds)
rxBus.send(EventNSClientNewLog("► ALARMACK ", "${originalAlarm.level()} ${originalAlarm.group()} $silenceTimeInMilliseconds"))
} }
/********************** /**********************
@ -596,20 +597,6 @@ class NSClientV3Plugin @Inject constructor(
override val address: String get() = sp.getString(info.nightscout.core.utils.R.string.key_nsclientinternal_url, "") override val address: String get() = sp.getString(info.nightscout.core.utils.R.string.key_nsclientinternal_url, "")
override fun handleClearAlarm(originalAlarm: NSAlarm, silenceTimeInMilliseconds: Long) {
if (!isEnabled()) return
if (!sp.getBoolean(R.string.key_ns_upload, true)) {
aapsLogger.debug(LTag.NSCLIENT, "Upload disabled. Message dropped")
return
}
// nsClientService?.sendAlarmAck(
// AlarmAck().also { ack ->
// ack.level = originalAlarm.level()
// ack.group = originalAlarm.group()
// ack.silenceTime = silenceTimeInMilliseconds
// })
}
override fun isFirstLoad(collection: NsClient.Collection) = override fun isFirstLoad(collection: NsClient.Collection) =
when (collection) { when (collection) {
NsClient.Collection.ENTRIES -> lastLoadedSrvModified.collections.entries == 0L NsClient.Collection.ENTRIES -> lastLoadedSrvModified.collections.entries == 0L