-
Notifications
You must be signed in to change notification settings - Fork 8
/
ServerDiscovery.java
237 lines (200 loc) · 7.17 KB
/
ServerDiscovery.java
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* LMS-Material-App
*
* Copyright (c) 2020-2023 Craig Drummond <craig.p.drummond@gmail.com>
* MIT license.
*/
package com.craigd.lmsmaterial.app;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
public abstract class ServerDiscovery {
private static final int SERVER_DISCOVERY_TIMEOUT = 1500;
public static class Server implements Comparable<Server> {
public static final int DEFAULT_PORT = 9000;
public String ip = "";
public String name = "";
public int port = DEFAULT_PORT;
private static String getString(JSONObject json, String key) {
try {
return json.getString(key);
} catch (JSONException e) {
return "";
}
}
private static int getPort(JSONObject json) {
try {
return json.getInt("port");
} catch (JSONException e) {
return Server.DEFAULT_PORT;
}
}
public Server(String str) {
Utils.debug("DECODE:"+str);
if (str != null) {
try {
JSONObject json = new JSONObject(str);
ip = getString(json, "ip");
name = getString(json, "name");
port = getPort(json);
} catch (JSONException ignored) {
}
}
}
public Server(String ip, int port, String name) {
this.ip=ip;
this.port=port;
this.name=name;
}
public Server(DatagramPacket pkt) {
ip = pkt.getAddress().getHostAddress();
// Try to get name of server for packet
int pktLen = pkt.getLength();
byte[] bytes = pkt.getData();
// Look for NAME:<Name> in list of key:value pairs
for(int i=1; i < pktLen; ) {
if (i + 5 > pktLen) {
break;
}
// Extract 4 bytes
String key = new String(bytes, i, 4);
i += 4;
int valueLen = bytes[i++] & 0xFF;
if (i + valueLen > pktLen) {
break;
}
if (key.equals("NAME")) {
name = new String(bytes, i, valueLen);
Utils.debug("Name:"+name);
} else if (key.equals("JSON")) {
try {
port = Integer.parseInt(new String(bytes, i, valueLen));
Utils.debug("Port:"+port);
} catch (NumberFormatException ignored) {
}
}
i += valueLen;
}
}
public boolean isEmpty() {
return null==ip || ip.isEmpty();
}
@Override
public int compareTo(@NonNull Server o) {
return null==ip ? (o.ip==null ? 0 : -1) : ip.compareTo(o.ip);
}
public boolean equals(Server o) {
return Objects.equals(ip, o.ip);
}
public String describe() {
if (null==name || name.isEmpty()) {
return address();
}
return name+" ("+address()+")";
}
public String address() {
return ip + (DEFAULT_PORT==port ? "" : (":"+port));
}
public String encode() {
try {
JSONObject json = new JSONObject();
json.put("ip", ip);
json.put("name", name);
json.put("port", port);
return json.toString(0);
} catch (JSONException e) {
return ip;
}
}
}
class DiscoveryRunnable implements Runnable {
private volatile boolean active = false;
private final WifiManager wifiManager;
private final List<Server> servers = new LinkedList<>();
DiscoveryRunnable(WifiManager wifiManager) {
this.wifiManager = wifiManager;
}
@Override
public void run() {
Utils.debug("Discover LMS servers");
active = true;
WifiManager.WifiLock wifiLock;
DatagramSocket socket = null;
wifiLock = wifiManager.createWifiLock(Utils.LOG_TAG);
wifiLock.acquire();
try {
InetAddress broadcastAddress = InetAddress.getByName("255.255.255.255");
socket = new DatagramSocket();
byte[] req = { 'e', 'I', 'P', 'A', 'D', 0, 'N', 'A', 'M', 'E', 0, 'J', 'S', 'O', 'N', 0 };
DatagramPacket reqPkt = new DatagramPacket(req, req.length, broadcastAddress, 3483);
byte[] resp = new byte[256];
DatagramPacket respPkt = new DatagramPacket(resp, resp.length);
socket.setSoTimeout(SERVER_DISCOVERY_TIMEOUT);
socket.send(reqPkt);
for (;;) {
try {
socket.receive(respPkt);
if (resp[0]==(byte)'E') {
Server server = new Server(respPkt);
if (!servers.contains(server)) {
servers.add(server);
if (!discoverAll) {
break; // Stop at first for now...
}
}
}
} catch (IOException e) {
break;
}
}
} catch (Exception ignored) {
} finally {
if (socket != null) {
socket.close();
}
Utils.verbose("Scanning complete, unlocking WiFi");
wifiLock.release();
}
handler.sendMessage(new Message());
active = false;
}
public boolean isActive() {
return active;
}
}
final Context context;
private final boolean discoverAll;
private final Handler handler;
private DiscoveryRunnable runnable;
ServerDiscovery(Context context, boolean discoverAll) {
this.context = context;
this.discoverAll = discoverAll;
handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message unused) {
discoveryFinished(runnable.servers);
}
};
}
public void discover() {
if (runnable!=null && runnable.isActive()) {
return;
}
runnable = new DiscoveryRunnable((WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE));
Thread thread = new Thread(runnable);
thread.start();
}
protected abstract void discoveryFinished(List<Server> servers);
}