-
Notifications
You must be signed in to change notification settings - Fork 3
/
UdpServerThread.java
344 lines (306 loc) · 8.8 KB
/
UdpServerThread.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package com.jenxsol.wakemesleepme.server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.LinkedBlockingQueue;
import android.os.Handler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jenxsol.wakemesleepme.consts.Iface;
import com.jenxsol.wakemesleepme.consts.Packets;
import com.jenxsol.wakemesleepme.models.WrappedPacket;
import com.jenxsol.wakemesleepme.server.UdpServer.EventPacketReceived;
import com.jenxsol.wakemesleepme.server.UdpServer.EventServerStarted;
import com.jenxsol.wakemesleepme.server.UdpServer.EventServerStopped;
import com.jenxsol.wakemesleepme.ui.fragments.LoggingFragment.EventLogOutput;
import com.jenxsol.wakemesleepme.utils.QLog;
import com.jenxsol.wakemesleepme.utils.WiFiSupport;
import de.greenrobot.event.EventBus;
class UdpServerThread extends Thread implements Iface, Packets, OnDataReceivedListener
{
private static final EventBus sBus = EventBus.getDefault();
// Send queue
private final LinkedBlockingQueue<DatagramPacket> mPacketSendQueue = new LinkedBlockingQueue<DatagramPacket>();
private boolean mIsStarted = false;
private boolean mIsFinished = false;
private boolean mIsRunning = false;
private boolean run = true;
private InetAddress mBroadcastAddress = null;
private DatagramSocket mSocket;
private UdpListenThread mListenerThread;
public UdpServerThread(Handler handler)
{
}
/**
* True on success
*
* @return
*/
private boolean init()
{
if (!WiFiSupport.isWiFiConnected())
{
QLog.d("WiFi Off");
sBus.post(new EventLogOutput("WiFi Off, Do nothing. sorry!"));
// TODO send sticky event
return false;
}
try
{
mBroadcastAddress = WiFiSupport.getBroadcastAddress();
// QLog.d("WiFi Broadcast address: " + mBroadcastAddress.getHostAddress());
mSocket = new DatagramSocket(UDP_PORT_ANDROID);
mSocket.setBroadcast(true);
mListenerThread = new UdpListenThread(mSocket, this);
sBus.post(new EventLogOutput("UDP Server bound to: "
+ mSocket.getLocalAddress().getHostAddress() + ":" + UDP_PORT_ANDROID));
return true;
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
@Override
public void run()
{
mIsStarted = true;
if (!init())
{
finished();
return;
}
started();
while (run)
{
mIsRunning = true;
run = work();
}
finished();
}
private static final Gson mGson = new GsonBuilder().create();
/**
* @see com.jenxsol.wakemesleepme.server.OnDataReceivedListener#onDataReceived(java.net.DatagramPacket)
*/
@Override
public void onDataReceived(DatagramPacket packet)
{
sBus.post(new EventLogOutput("Received Packet: " + packet.getAddress().getHostAddress()
+ " Message: " + new String(packet.getData())));
WrappedPacket wp = new WrappedPacket();
wp.setIpAddress(packet.getAddress().getHostAddress());
wp.setTime(System.currentTimeMillis());
wp.setPacket(packet);
sBus.post(new EventPacketReceived(wp));
}
/**
* Does actual work or waits in here
*
* @return false if we finished do work
*/
protected boolean work()
{
// Check state before doing work
if (mSocket == null)
return false;
if (!mSocket.isBound())
return false;
if (mSocket.isClosed())
return false;
try
{
return sendPacket(mPacketSendQueue.take());
}
catch (InterruptedException e)
{
return false;
}
}
/**
* Add a packet to the send queue. This will add the address and port to the packet
*
* @param data
* @param length
* @return true if added to the queue.. does not mean the packet has been sent tho!
*/
boolean addPacketToSend(byte[] data, int length)
{
if (data == null || length == 0)
return false;
return mPacketSendQueue.add(createDatagramPacket(data, length));
}
/**
* Add a datagram packet to be server, pre-formatted
*
* @param packet
* @return
*/
boolean addPacketToSend(DatagramPacket packet)
{
if (packet == null)
return false;
return mPacketSendQueue.add(createDatagramPacket(packet));
}
/**
* Stop the server don't use {@link #stop()} doesn't work!
*/
void stopServer()
{
run = false;
mPacketSendQueue.clear();
interrupt();
}
boolean isStarted()
{
return mIsStarted;
}
boolean isRunning()
{
return mIsRunning;
}
boolean isFinished()
{
return mIsFinished;
}
/**
* Creates a broadcast packet for this device
*
* @param data
* @param length
* @return
*/
private DatagramPacket createDatagramPacket(byte[] data, int length)
{
if (mBroadcastAddress == null)
return null;
final DatagramPacket p = new DatagramPacket(data, length, mBroadcastAddress,
UDP_PORT_DESKTOP);
return p;
}
/**
* Makes sure you packet has an address and port set, defaults to udp desktop port and broadcast
* address
*
* @param p
* @return populated packet
*/
private DatagramPacket createDatagramPacket(DatagramPacket p)
{
if (p == null)
return p;
if (p.getAddress() == null)
p.setAddress(mBroadcastAddress);
if (p.getPort() == 0)
p.setPort(UDP_PORT_DESKTOP);
return p;
}
/**
* Internal method to send packets
*
* @param packet
* @return
*/
private boolean sendPacket(final DatagramPacket packet)
{
if (mSocket == null)
return false;
try
{
mSocket.send(packet);
sBus.post(new EventLogOutput("UDP Packet \" " + new String(packet.getData())
+ " \" sent to: " + mBroadcastAddress.getHostAddress() + ":"
+ packet.getPort()));
QLog.d("Packet: " + packet + " Sent.");
return true;
}
catch (IOException e)
{
QLog.w("Error Sending Packet", e);
stopServer();
}
return false;
}
/**
* Interal state and event saying the server is running.
*/
private void started()
{
sBus.postSticky(new EventServerStarted());
}
private void shutdown()
{
if (mSocket != null)
{
mSocket.close();
mListenerThread.run = false;
mListenerThread.interrupt();
mListenerThread = null;
sBus.post(new EventLogOutput("UDP Server closed"));
QLog.d("UDP Socket Closed");
}
}
/**
* Set the thread state to finished
*/
private void finished()
{
shutdown();
mIsRunning = false;
mIsFinished = true;
sBus.removeStickyEvent(EventServerStarted.class);
sBus.post(new EventServerStopped());
}
static final class UdpListenThread extends Thread
{
private OnDataReceivedListener mListener;
private DatagramSocket mSocket;
private boolean run = false;
private UdpListenThread(final DatagramSocket socket, final OnDataReceivedListener listener)
{
mSocket = socket;
mListener = listener;
if (mSocket == null || mSocket.isClosed())
{
return;
}
run = true;
sBus.post(new EventLogOutput("Start listening"));
start();
}
/**
* @see java.lang.Thread#run()
*/
@Override
public void run()
{
while (run)
{
run = listen();
}
}
private boolean listen()
{
// Empty data
final byte[] message = new byte[1500];
final DatagramPacket emptyPacket = new DatagramPacket(message, message.length);
try
{
mSocket.receive(emptyPacket);
mListener.onDataReceived(emptyPacket);
return true;
}
catch (IOException e)
{
QLog.w("UDP Receive error", e);
return false;
}
}
}
}