-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNetworkScreenViewModel.kt
More file actions
219 lines (186 loc) · 9.92 KB
/
NetworkScreenViewModel.kt
File metadata and controls
219 lines (186 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package com.greybox.projectmesh.viewModel
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.greybox.projectmesh.DeviceStatusManager
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.delay
import org.kodein.di.DI
import com.greybox.projectmesh.server.AppServer
import com.ustadmobile.meshrabiya.ext.addressToByteArray
import com.ustadmobile.meshrabiya.vnet.AndroidVirtualNode
import com.ustadmobile.meshrabiya.vnet.VirtualNode
import com.ustadmobile.meshrabiya.vnet.wifi.state.WifiStationState
import com.greybox.projectmesh.testing.TestDeviceEntry
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.kodein.di.instance
import java.net.InetAddress
import com.greybox.projectmesh.GlobalApp
import com.greybox.projectmesh.testing.TestDeviceService
import kotlinx.coroutines.withTimeoutOrNull
data class NetworkScreenModel(
val connectingInProgressSsid: String? = null,
val allNodes: Map<Int, VirtualNode.LastOriginatorMessage> = emptyMap(),
)
class NetworkScreenViewModel(di:DI, savedStateHandle: SavedStateHandle): ViewModel() {
// _uiState will be updated whenever there is a change in the UI state
private val _uiState = MutableStateFlow(NetworkScreenModel())
// uiState is a read-only property that shows the current UI state
val uiState: Flow<NetworkScreenModel> = _uiState.asStateFlow()
// di is used to get the AndroidVirtualNode instance
private val node: AndroidVirtualNode by di.instance()
private val appServer: AppServer by di.instance()
// launch a coroutine
init {
viewModelScope.launch {
//create test device entry
val testEntry = TestDeviceEntry.createTestEntry()
var previousNodes = emptySet<Int>()
node.state.collect { nodeState ->
// Get current nodes from this state update
val currentNodes = nodeState.originatorMessages.keys
// Check for nodes that disappeared (disconnected)
val disconnectedNodes = previousNodes - currentNodes
// For each disconnected node, notify DeviceStatusManager
disconnectedNodes.forEach { nodeAddress ->
val ipAddress =
InetAddress.getByAddress(nodeAddress.addressToByteArray()).hostAddress
DeviceStatusManager.handleNetworkDisconnect(ipAddress)
Log.d("NetworkScreenViewModel", "Detected disconnection of node: $ipAddress")
}
// Update previous nodes for next comparison
previousNodes = currentNodes
// Combine real nodes with test device
val allNodesWithTest = nodeState.originatorMessages.toMutableMap()
allNodesWithTest[testEntry.first] = testEntry.second
Log.d("NetworkScreenViewModel", "Updating nodes. Count: ${allNodesWithTest.size}")
Log.d("NetworkScreenViewModel", "Test device address: ${testEntry.first}")
Log.d("NetworkScreenViewModel", "All nodes: ${allNodesWithTest.keys}")
// update the UI state with the new state
_uiState.update { prev ->
prev.copy(
// update all nodes
allNodes = allNodesWithTest,
// update the ssid of the connecting station
connectingInProgressSsid =
if (nodeState.wifiState.wifiStationState.status == WifiStationState.Status.CONNECTING) {
nodeState.wifiState.wifiStationState.config?.ssid
} else {
null
}
)
}
//just mark nodes as online initially - DeviceStatusManager will verify
allNodesWithTest.forEach { (addressInt, _) ->
val ipAddress =
InetAddress.getByAddress(addressInt.addressToByteArray()).hostAddress
// Update with verified=false to let the manager handle verification
DeviceStatusManager.updateDeviceStatus(ipAddress, true, verified = false)
}
}
}
/*
THIS LOGIC SHOULDNT BE NEEDED ANY MORE IF DEVICE STATUS MANAGER WORKS
viewModelScope.launch {
while (true) {
try {
//get all connected users
val connectedUsers = GlobalApp.GlobalUserRepo.userRepository.getAllConnectedUsers()
val onlineDevices = DeviceStatusManager.getOnlineDevices()
for (user in connectedUsers) {
user.address?.let { ipStr ->
try {
//skip test devices:
if (ipStr == TestDeviceService.TEST_DEVICE_IP) {
// Online test device should always be online
DeviceStatusManager.updateDeviceStatus(ipStr, true)
}
if (ipStr == TestDeviceService.TEST_DEVICE_IP_OFFLINE) {
// Offline test device should always be offline
DeviceStatusManager.updateDeviceStatus(ipStr, false)
}else{
val addr = InetAddress.getByName(ipStr)
val isReachable = withTimeoutOrNull(3000) {
addr.isReachable(2000) // 2 second timeout
} ?: false
if (!isReachable) {
// Device is not reachable at basic network level
throw Exception("Device is not reachable")
}
//ping user by requesting online info to update status
appServer.requestRemoteUserInfo(addr)
//Update central status manager to show device as online
DeviceStatusManager.updateDeviceStatus(ipStr, true)
Log.d("NetworkScreenViewModel", "Pinged user: ${user.name} at $ipStr")
}
} catch (e: Exception) {
//if ping fails, mark user as offline
GlobalApp.GlobalUserRepo.conversationRepository.updateUserStatus(
userUuid = user.uuid,
isOnline = false,
userAddress = null
)
//update central status manager to show device as offline
DeviceStatusManager.updateDeviceStatus(ipStr, false)
Log.d("NetworkScreenViewModel", "User ${user.name} appears to be offline")
}
}
}
//check any online devices that may not be in the users list
//i.e.: devices marked online but not properly registered as users
for (deviceIp in onlineDevices) {
if (connectedUsers.any { it.address == deviceIp } ||
deviceIp == TestDeviceService.TEST_DEVICE_IP ||
deviceIp == TestDeviceService.TEST_DEVICE_IP_OFFLINE) continue
// Skip devices we already checked in the user loop
if (connectedUsers.any { it.address == deviceIp }) continue
// Skip test device - it's handled differently
if (deviceIp == TestDeviceService.TEST_DEVICE_IP) continue
try {
val addr = InetAddress.getByName(deviceIp)
val isReachable = withTimeoutOrNull(3000) {
addr.isReachable(2000)
} ?: false
if (!isReachable) {
Log.d(
"NetworkScreenViewModel",
"Marking device $deviceIp as offline - not reachable"
)
DeviceStatusManager.updateDeviceStatus(deviceIp, false)
}
}catch (e: Exception){
Log.d("NetworkScreenViewModel", "Error checking device $deviceIp: ${e.message}")
DeviceStatusManager.updateDeviceStatus(deviceIp, false)
}
}
}catch (e: Exception) {
Log.e("NetworkScreenViewModel", "Error during periodic ping", e)
}
//wait for 30 secs before next ming
delay(30000)
}
}
*/
}
fun onNodeSelected(ipAddress: String) {
viewModelScope.launch {
try {
val addr = InetAddress.getByName(ipAddress)
appServer.requestRemoteUserInfo(addr)
appServer.pushUserInfoTo(addr)
} catch (e: Exception) {
Log.e("NetworkScreenViewModel", "Failed to request user info for $ipAddress", e)
}
}
}
fun getDeviceName(wifiAddress: Int) {
viewModelScope.launch {
val inetAddress = InetAddress.getByAddress(wifiAddress.addressToByteArray())
appServer.sendDeviceName(inetAddress)
}
}
}