/
WifiReceiver.java
573 lines (508 loc) · 20.8 KB
/
WifiReceiver.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
package net.wigle.wigleandroid.listener;
import static android.location.LocationManager.GPS_PROVIDER;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import net.wigle.wigleandroid.CacheMap;
import net.wigle.wigleandroid.DashboardActivity;
import net.wigle.wigleandroid.DatabaseHelper;
import net.wigle.wigleandroid.ListActivity;
import net.wigle.wigleandroid.Network;
import net.wigle.wigleandroid.NetworkListAdapter;
import net.wigle.wigleandroid.NetworkType;
import net.wigle.wigleandroid.ListActivity.TrailStat;
import org.andnav.osm.util.GeoPoint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.widget.Toast;
public class WifiReceiver extends BroadcastReceiver {
private ListActivity listActivity;
private final DatabaseHelper dbHelper;
private NetworkListAdapter listAdapter;
private SimpleDateFormat timeFormat;
private NumberFormat numberFormat1;
private Handler wifiTimer;
private Location prevGpsLocation;
private long scanRequestTime = Long.MIN_VALUE;
private long lastScanResponseTime = Long.MIN_VALUE;
private long lastWifiUnjamTime = Long.MIN_VALUE;
private int pendingCount = 0;
private long previousTalkTime = System.currentTimeMillis();
private final Set<String> runNetworks = new HashSet<String>();
private long prevNewNetCount;
private long prevScanPeriod;
public static final int SIGNAL_COMPARE = 10;
public static final int CHANNEL_COMPARE = 11;
public static final int CRYPTO_COMPARE = 12;
public static final int FIND_TIME_COMPARE = 13;
public static final int SSID_COMPARE = 14;
// a minute and a half without a scan is probably bad, since max setting is a minute
private static final long LAST_SCAN_TIME_THRESH = 90000L;
private static final long WIFI_UNJAM_PERIOD = 30000L;
private static final Comparator<Network> signalCompare = new Comparator<Network>() {
public int compare( Network a, Network b ) {
return b.getLevel() - a.getLevel();
}
};
private static final Comparator<Network> channelCompare = new Comparator<Network>() {
public int compare( Network a, Network b ) {
return a.getFrequency() - b.getFrequency();
}
};
private static final Comparator<Network> cryptoCompare = new Comparator<Network>() {
public int compare( Network a, Network b ) {
return b.getCrypto() - a.getCrypto();
}
};
private static final Comparator<Network> findTimeCompare = new Comparator<Network>() {
public int compare( Network a, Network b ) {
return (int) (b.getConstructionTime() - a.getConstructionTime());
}
};
private static final Comparator<Network> ssidCompare = new Comparator<Network>() {
public int compare( Network a, Network b ) {
return a.getSsid().compareTo( b.getSsid() );
}
};
public WifiReceiver( final ListActivity listActivity, final DatabaseHelper dbHelper,
final NetworkListAdapter listAdapter ) {
this.listActivity = listActivity;
this.dbHelper = dbHelper;
this.listAdapter = listAdapter;
ListActivity.lameStatic.runNetworks = runNetworks;
// formats for speech
timeFormat = new SimpleDateFormat( "h mm aa" );
numberFormat1 = NumberFormat.getNumberInstance( Locale.US );
if ( numberFormat1 instanceof DecimalFormat ) {
((DecimalFormat) numberFormat1).setMaximumFractionDigits( 1 );
}
}
public void setListActivity( final ListActivity listActivity ) {
this.listActivity = listActivity;
}
public void setListAdapter( final NetworkListAdapter listAdapter ) {
this.listAdapter = listAdapter;
}
public int getRunNetworkCount() {
return runNetworks.size();
}
@Override
public void onReceive( final Context context, final Intent intent ){
lastScanResponseTime = System.currentTimeMillis();
// final long start = System.currentTimeMillis();
final WifiManager wifiManager = (WifiManager) listActivity.getSystemService(Context.WIFI_SERVICE);
final List<ScanResult> results = wifiManager.getScanResults(); // return can be null!
long nonstopScanRequestTime = Long.MIN_VALUE;
final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 );
final long period = getScanPeriod();
if ( period == 0 ) {
// treat as "continuous", so request scan in here
doWifiScan();
nonstopScanRequestTime = System.currentTimeMillis();
}
final long prefPeriod = prefs.getLong(ListActivity.GPS_SCAN_PERIOD, ListActivity.LOCATION_UPDATE_INTERVAL);
long setPeriod = prefPeriod;
if (setPeriod == 0 ){
setPeriod = Math.max(period, ListActivity.LOCATION_UPDATE_INTERVAL);
}
if ( setPeriod != prevScanPeriod && listActivity.isScanning() ) {
// update our location scanning speed
ListActivity.info("setting location updates to: " + setPeriod);
listActivity.setLocationUpdates(setPeriod, 0f);
prevScanPeriod = setPeriod;
}
final boolean showCurrent = prefs.getBoolean( ListActivity.PREF_SHOW_CURRENT, true );
if ( showCurrent ) {
listAdapter.clear();
}
final int preQueueSize = dbHelper.getQueueSize();
final boolean fastMode = dbHelper.isFastMode();
final Location location = listActivity.getGPSListener().getLocation();
final CacheMap<String,Network> networkCache = ListActivity.getNetworkCache();
boolean somethingAdded = false;
int resultSize = 0;
int newForRun = 0;
// can be null on shutdown
if ( results != null ) {
resultSize = results.size();
for ( ScanResult result : results ) {
Network network = networkCache.get( result.BSSID );
if ( network == null ) {
network = new Network( result );
networkCache.put( network.getBssid(), network );
}
else {
// cache hit, just set the level
network.setLevel( result.level );
}
final boolean added = runNetworks.add( result.BSSID );
if ( added ) {
newForRun++;
}
somethingAdded |= added;
// if we're showing current, or this was just added, put on the list
if ( showCurrent || added ) {
listAdapter.add( network );
// load test
// for ( int i = 0; i< 10; i++) {
// listAdapter.add( network );
// }
}
else {
// not showing current, and not a new thing, go find the network and update the level
// this is O(n), ohwell, that's why showCurrent is the default config.
for ( int index = 0; index < listAdapter.getCount(); index++ ) {
final Network testNet = listAdapter.getItem(index);
if ( testNet.getBssid().equals( network.getBssid() ) ) {
testNet.setLevel( result.level );
}
}
}
if ( dbHelper != null ) {
if ( location != null ) {
// if in fast mode, only add new-for-run stuff to the db queue
if ( fastMode && ! added ) {
ListActivity.info( "in fast mode, not adding seen-this-run: " + network.getBssid() );
}
else {
// loop for stress-testing
// for ( int i = 0; i < 10; i++ ) {
dbHelper.addObservation( network, location, added );
// }
}
} else {
// no location
dbHelper.pendingObservation( network, added );
}
}
}
}
// check if there are more "New" nets
final long newNetCount = dbHelper.getNewNetworkCount();
final long newNetDiff = newNetCount - prevNewNetCount;
prevNewNetCount = newNetCount;
if ( ! listActivity.isMuted() ) {
final boolean playRun = prefs.getBoolean( ListActivity.PREF_FOUND_SOUND, true );
final boolean playNew = prefs.getBoolean( ListActivity.PREF_FOUND_NEW_SOUND, true );
if ( newNetDiff > 0 && playNew ) {
listActivity.playNewNetSound();
}
else if ( somethingAdded && playRun ) {
listActivity.playRunNetSound();
}
}
final int sort = prefs.getInt(ListActivity.PREF_LIST_SORT, SIGNAL_COMPARE);
Comparator<Network> comparator = signalCompare;
switch ( sort ) {
case SIGNAL_COMPARE:
comparator = signalCompare;
break;
case CHANNEL_COMPARE:
comparator = channelCompare;
break;
case CRYPTO_COMPARE:
comparator = cryptoCompare;
break;
case FIND_TIME_COMPARE:
comparator = findTimeCompare;
break;
case SSID_COMPARE:
comparator = ssidCompare;
break;
}
listAdapter.sort( comparator );
final long dbNets = dbHelper.getNetworkCount();
final long dbLocs = dbHelper.getLocationCount();
// update stat
listActivity.setNetCountUI();
// set the statics for the map
ListActivity.lameStatic.runNets = runNetworks.size();
ListActivity.lameStatic.newNets = newNetCount;
ListActivity.lameStatic.currNets = resultSize;
ListActivity.lameStatic.preQueueSize = preQueueSize;
ListActivity.lameStatic.dbNets = dbNets;
ListActivity.lameStatic.dbLocs = dbLocs;
if ( newForRun > 0 ) {
if ( location == null ) {
// save for later
pendingCount += newForRun;
}
else {
final GeoPoint geoPoint = new GeoPoint( location );
TrailStat trailStat = ListActivity.lameStatic.trail.get( geoPoint );
if ( trailStat == null ) {
trailStat = new TrailStat();
ListActivity.lameStatic.trail.put( geoPoint, trailStat );
}
trailStat.newForRun += newForRun;
trailStat.newForDB += newNetDiff;
// add any pendings
// don't go crazy
if ( pendingCount > 25 ) {
pendingCount = 25;
}
trailStat.newForRun += pendingCount;
pendingCount = 0;
}
}
// info( savedStats );
// notify
listAdapter.notifyDataSetChanged();
final long now = System.currentTimeMillis();
if ( scanRequestTime <= 0 ) {
// wasn't set, set to now
scanRequestTime = now;
}
final String status = resultSize + " scanned in " + (now - scanRequestTime) + "ms. DB Queue: " + preQueueSize;
listActivity.setStatusUI( status );
// we've shown it, reset it to the nonstop time above, or min_value if nonstop wasn't set.
scanRequestTime = nonstopScanRequestTime;
// do lerp if need be
if ( location == null ) {
if ( prevGpsLocation != null ) {
dbHelper.lastLocation( prevGpsLocation );
// ListActivity.info("set last location for lerping");
}
}
else {
dbHelper.recoverLocations( location );
}
// do distance calcs
if ( location != null && GPS_PROVIDER.equals( location.getProvider() )
&& location.getAccuracy() <= ListActivity.MIN_DISTANCE_ACCURACY ) {
if ( prevGpsLocation != null ) {
float dist = location.distanceTo( prevGpsLocation );
// info( "dist: " + dist );
if ( dist > 0f ) {
final Editor edit = prefs.edit();
edit.putFloat( ListActivity.PREF_DISTANCE_RUN,
dist + prefs.getFloat( ListActivity.PREF_DISTANCE_RUN, 0f ) );
edit.putFloat( ListActivity.PREF_DISTANCE_TOTAL,
dist + prefs.getFloat( ListActivity.PREF_DISTANCE_TOTAL, 0f ) );
edit.commit();
}
}
// set for next time
prevGpsLocation = location;
}
recordCellInfo(location);
final long speechPeriod = prefs.getLong( ListActivity.PREF_SPEECH_PERIOD, ListActivity.DEFAULT_SPEECH_PERIOD );
if ( speechPeriod != 0 && now - previousTalkTime > speechPeriod * 1000L ) {
doAnnouncement( preQueueSize, newNetCount, now );
}
}
private void recordCellInfo(final Location location) {
TelephonyManager tele = (TelephonyManager) listActivity.getSystemService( Context.TELEPHONY_SERVICE );
if ( tele != null ) {
String bssid = null;
NetworkType type = null;
CellLocation cellLocation = tele.getCellLocation();
if ( cellLocation.getClass().getSimpleName().equals("CdmaCellLocation") ) {
try {
final int systemId = (Integer) cellLocation.getClass().getMethod("getSystemId").invoke(cellLocation);
final int networkId = (Integer) cellLocation.getClass().getMethod("getNetworkId").invoke(cellLocation);
final int baseStationId = (Integer) cellLocation.getClass().getMethod("getBaseStationId").invoke(cellLocation);
bssid = systemId + "_" + networkId + "_" + baseStationId;
type = NetworkType.CDMA;
}
catch ( Exception ex ) {
ListActivity.error("cdma reflection exception: " + ex);
}
}
else if ( cellLocation instanceof GsmCellLocation ) {
GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
bssid = tele.getNetworkOperator() + "_" + gsmCellLocation.getLac() + "_" + gsmCellLocation.getCid();
type = NetworkType.CDMA;
}
if ( bssid != null ) {
final String ssid = tele.getNetworkOperatorName();
final String capabilities = tele.getNetworkCountryIso();
int strength = 0;
PhoneState phoneState = listActivity.getPhoneState();
if (phoneState != null) {
strength = phoneState.getStrength();
}
if ( false ) {
ListActivity.info( "bssid: " + bssid );
ListActivity.info( "strength: " + strength );
ListActivity.info( "ssid: " + ssid );
ListActivity.info( "capabilities: " + capabilities );
ListActivity.info( "location: " + location );
}
final CacheMap<String,Network> networkCache = ListActivity.getNetworkCache();
Network network = networkCache.get( bssid );
if ( network == null ) {
network = new Network( bssid, ssid, 0, capabilities, strength, type );
networkCache.put( network.getBssid(), network );
}
//dbHelper.recordCellInfo(location, gsmCellLocation)
}
}
}
private void doAnnouncement( int preQueueSize, long newNetCount, long now ) {
final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 );
StringBuilder builder = new StringBuilder();
if ( listActivity.getGPSListener().getLocation() == null ) {
builder.append( "no gps fix, " );
}
// run, new, queue, miles, time, battery
if ( prefs.getBoolean( ListActivity.PREF_SPEAK_RUN, true ) ) {
builder.append( "run " ).append( runNetworks.size() ).append( ", " );
}
if ( prefs.getBoolean( ListActivity.PREF_SPEAK_NEW, true ) ) {
builder.append( "new " ).append( newNetCount ).append( ", " );
}
if ( preQueueSize > 0 && prefs.getBoolean( ListActivity.PREF_SPEAK_QUEUE, true ) ) {
builder.append( "queue " ).append( preQueueSize ).append( ", " );
}
if ( prefs.getBoolean( ListActivity.PREF_SPEAK_MILES, true ) ) {
final float dist = prefs.getFloat( ListActivity.PREF_DISTANCE_RUN, 0f );
final String distString = DashboardActivity.metersToString(numberFormat1, listActivity, dist);
builder.append( "from " ).append( distString );
}
if ( prefs.getBoolean( ListActivity.PREF_SPEAK_TIME, true ) ) {
String time = timeFormat.format( new Date() );
time = time.replace(" 00", " oh clock");
time = time.replace(" 0", " oh ");
builder.append( time ).append( ", " );
}
final int batteryLevel = listActivity.getBatteryLevelReceiver().getBatteryLevel();
if ( batteryLevel >= 0 && prefs.getBoolean( ListActivity.PREF_SPEAK_BATTERY, true ) ) {
builder.append( "battery " ).append( batteryLevel ).append( " percent, " );
}
ListActivity.info( "speak: " + builder.toString() );
listActivity.speak( builder.toString() );
previousTalkTime = now;
}
public void setupWifiTimer( final boolean turnedWifiOn ) {
ListActivity.info( "create wifi timer" );
if ( wifiTimer == null ) {
wifiTimer = new Handler();
final Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// make sure the app isn't trying to finish
if ( ! listActivity.isFinishing() ) {
// info( "timer start scan" );
doWifiScan();
if ( scanRequestTime <= 0 ) {
scanRequestTime = System.currentTimeMillis();
}
long period = getScanPeriod();
// check if set to "continuous"
if ( period == 0L ) {
// set to default here, as a scan will also be requested on the scan result listener
period = ListActivity.SCAN_DEFAULT;
}
// info("wifitimer: " + period );
wifiTimer.postDelayed( this, period );
}
else {
ListActivity.info( "finishing timer" );
}
}
};
wifiTimer.removeCallbacks( mUpdateTimeTask );
wifiTimer.postDelayed( mUpdateTimeTask, 100 );
if ( turnedWifiOn ) {
ListActivity.info( "not immediately running wifi scan, since it was just turned on"
+ " it will block for a few seconds and fail anyway");
}
else {
ListActivity.info( "start first wifi scan");
// starts scan, sends event when done
final boolean scanOK = doWifiScan();
if ( scanRequestTime <= 0 ) {
scanRequestTime = System.currentTimeMillis();
}
ListActivity.info( "startup finished. wifi scanOK: " + scanOK );
}
}
}
public long getScanPeriod() {
final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 );
String scanPref = ListActivity.PREF_SCAN_PERIOD;
long defaultRate = ListActivity.SCAN_DEFAULT;
// if over 5 mph
final Location location = listActivity.getGPSListener().getLocation();
if ( location != null && location.getSpeed() >= 2.2352f ) {
scanPref = ListActivity.PREF_SCAN_PERIOD_FAST;
defaultRate = ListActivity.SCAN_FAST_DEFAULT;
}
else if ( location == null || location.getSpeed() < 0.1f ) {
scanPref = ListActivity.PREF_SCAN_PERIOD_STILL;
defaultRate = ListActivity.SCAN_STILL_DEFAULT;
}
return prefs.getLong( scanPref, defaultRate );
}
public void scheduleScan() {
wifiTimer.post(new Runnable() {
public void run() {
doWifiScan();
}
});
}
/**
* only call this from a Handler
* @return
*/
private boolean doWifiScan() {
// ListActivity.info("do wifi scan. lastScanTime: " + lastScanResponseTime);
final WifiManager wifiManager = (WifiManager) listActivity.getSystemService(Context.WIFI_SERVICE);
boolean retval = false;
if ( listActivity.isUploading() ) {
ListActivity.info( "uploading, not scanning for now" );
// reset this
lastScanResponseTime = Long.MIN_VALUE;
}
else if (listActivity.isScanning()){
retval = wifiManager.startScan();
final long now = System.currentTimeMillis();
if ( lastScanResponseTime < 0 ) {
// use now, since we made a request
lastScanResponseTime = now;
}
else {
final long sinceLastScan = now - lastScanResponseTime;
if ( sinceLastScan > LAST_SCAN_TIME_THRESH ) {
ListActivity.warn("Time since last scan: " + sinceLastScan + " milliseconds");
if ( lastWifiUnjamTime < 0 || now - lastWifiUnjamTime > WIFI_UNJAM_PERIOD ) {
Toast.makeText( listActivity,
"Wifi appears jammed, Turning off, and then on, WiFi.", Toast.LENGTH_LONG ).show();
wifiManager.setWifiEnabled(false);
wifiManager.setWifiEnabled(true);
lastWifiUnjamTime = now;
listActivity.speak("Warning, latest wifi scan completed "
+ (sinceLastScan / 1000L) + " seconds ago. Restarting wifi.");
}
}
}
}
else {
// scanning is off. since we're the only timer, update the UI
listActivity.setNetCountUI();
listActivity.setLocationUI();
listActivity.setStatusUI( "Scanning Turned Off" );
// keep the scan times from getting huge
scanRequestTime = System.currentTimeMillis();
// reset this
lastScanResponseTime = Long.MIN_VALUE;
}
return retval;
}
}