Skip to content

Commit 62a1e47

Browse files
committed
Restart SSE connection in listenForItemChange() when not alive
When restarting openHAB existing SSE connections may look like they are still intact to the client, but no further events are received. Thus restart a connection when no ALIVE events are received anymore. Signed-off-by: mueller-ma <mueller-ma@users.noreply.github.com>
1 parent 8801699 commit 62a1e47

1 file changed

Lines changed: 26 additions & 3 deletions

File tree

mobile/src/main/java/org/openhab/habdroid/util/ItemClient.kt

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ import javax.xml.parsers.DocumentBuilderFactory
2020
import javax.xml.parsers.ParserConfigurationException
2121
import kotlin.time.Duration.Companion.seconds
2222
import kotlinx.coroutines.CoroutineScope
23+
import kotlinx.coroutines.Job
2324
import kotlinx.coroutines.delay
2425
import kotlinx.coroutines.isActive
26+
import kotlinx.coroutines.launch
2527
import org.json.JSONArray
2628
import org.json.JSONException
2729
import org.json.JSONObject
@@ -119,10 +121,33 @@ object ItemClient {
119121
)
120122
var eventSubscription = createSubscription()
121123

124+
suspend fun restartSubscription() {
125+
try {
126+
eventSubscription.cancel()
127+
} catch (e: Exception) {
128+
Log.e(TAG, "Error cancelling SSE subscription for item $item", e)
129+
}
130+
delay(5.seconds)
131+
eventSubscription = createSubscription()
132+
}
133+
134+
var watchdogJob: Job? = null
135+
136+
fun resetAliveWatchdog() {
137+
watchdogJob?.cancel()
138+
watchdogJob = scope.launch {
139+
delay(30.seconds) // ALIVE event is sent every 10 seconds
140+
Log.d(TAG, "No events received for item $item, restarting subscription")
141+
restartSubscription()
142+
}
143+
}
144+
resetAliveWatchdog()
145+
122146
try {
123147
while (scope.isActive) {
124148
try {
125149
val event = JSONObject(eventSubscription.getNextEvent())
150+
resetAliveWatchdog()
126151
if (event.optString("type") == "ALIVE") {
127152
Log.d(TAG, "Got ALIVE event for item $item")
128153
continue
@@ -144,9 +169,7 @@ object ItemClient {
144169
Log.e(TAG, "Failed parsing JSON of state change event for item $item", e)
145170
} catch (e: HttpClient.SseFailureException) {
146171
Log.e(TAG, "SSE failure for item $item", e)
147-
eventSubscription.cancel()
148-
delay(5.seconds)
149-
eventSubscription = createSubscription()
172+
restartSubscription()
150173
}
151174
}
152175
} finally {

0 commit comments

Comments
 (0)