Search in sources :

Example 6 with Network

use of net.wigle.wigleandroid.model.Network in project wigle-wifi-wardriving by wiglenet.

the class DatabaseHelper method addObservation.

@SuppressWarnings("deprecation")
private void addObservation(final DBUpdate update, final int drainSize) throws DBException {
    checkDB();
    if (insertNetwork == null || insertLocation == null || updateNetwork == null || updateNetworkMetadata == null) {
        MainActivity.warn("A stored procedure is null, not adding observation");
        return;
    }
    final Network network = update.network;
    final Location location = update.location;
    final String bssid = network.getBssid();
    final String[] bssidArgs = new String[] { bssid };
    long lasttime = 0;
    double lastlat = 0;
    double lastlon = 0;
    int bestlevel = 0;
    double bestlat = 0;
    double bestlon = 0;
    boolean isNew = false;
    // first try cache
    final CachedLocation prevWrittenLocation = previousWrittenLocationsCache.get(bssid);
    if (prevWrittenLocation != null) {
        // cache hit!
        lasttime = prevWrittenLocation.location.getTime();
        lastlat = prevWrittenLocation.location.getLatitude();
        lastlon = prevWrittenLocation.location.getLongitude();
        bestlevel = prevWrittenLocation.bestlevel;
        bestlat = prevWrittenLocation.bestlat;
        bestlon = prevWrittenLocation.bestlon;
    // MainActivity.info( "db cache hit. bssid: " + network.getBssid() );
    } else {
        // cache miss, get the last values from the db, if any
        long start = System.currentTimeMillis();
        // SELECT: can't precompile, as it has more than 1 result value
        final Cursor cursor = db.rawQuery("SELECT lasttime,lastlat,lastlon,bestlevel,bestlat,bestlon FROM network WHERE bssid = ?", bssidArgs);
        logTime(start, "db network queried " + bssid);
        if (cursor.getCount() == 0) {
            insertNetwork.bindString(1, bssid);
            insertNetwork.bindString(2, network.getSsid());
            insertNetwork.bindLong(3, network.getFrequency());
            insertNetwork.bindString(4, network.getCapabilities());
            insertNetwork.bindLong(5, location.getTime());
            insertNetwork.bindDouble(6, location.getLatitude());
            insertNetwork.bindDouble(7, location.getLongitude());
            insertNetwork.bindString(8, network.getType().getCode());
            insertNetwork.bindLong(9, network.getLevel());
            insertNetwork.bindDouble(10, location.getLatitude());
            insertNetwork.bindDouble(11, location.getLongitude());
            start = System.currentTimeMillis();
            // INSERT
            insertNetwork.execute();
            logTime(start, "db network inserted: " + bssid + " drainSize: " + drainSize);
            // update the count
            networkCount.incrementAndGet();
            isNew = true;
            final Network cacheNetwork = MainActivity.getNetworkCache().get(bssid);
            if (cacheNetwork != null) {
                cacheNetwork.setIsNew();
                MainActivity.updateNetworkOnMap(network);
            }
        // to make sure this new network's location is written
        // don't update stack lasttime,lastlat,lastlon variables
        } else {
            // MainActivity.info("db using cursor values: " + network.getBssid() );
            cursor.moveToFirst();
            lasttime = cursor.getLong(0);
            lastlat = cursor.getDouble(1);
            lastlon = cursor.getDouble(2);
            bestlevel = cursor.getInt(3);
            bestlat = cursor.getDouble(4);
            bestlon = cursor.getDouble(5);
        }
        try {
            cursor.close();
        } catch (NoSuchElementException ex) {
            // weird error cropping up
            MainActivity.info("the weird close-cursor exception: " + ex);
        }
    }
    if (isNew) {
        newNetworkCount.incrementAndGet();
        if (NetworkType.WIFI.equals(network.getType())) {
            newWifiCount.incrementAndGet();
        } else {
            newCellCount.incrementAndGet();
        }
    }
    final boolean fastMode = isFastMode();
    final long now = System.currentTimeMillis();
    final double latDiff = Math.abs(lastlat - location.getLatitude());
    final double lonDiff = Math.abs(lastlon - location.getLongitude());
    final boolean levelChange = bestlevel <= (update.level - LEVEL_CHANGE);
    final boolean smallChange = latDiff > SMALL_LATLON_CHANGE || lonDiff > SMALL_LATLON_CHANGE;
    final boolean mediumChange = latDiff > MEDIUM_LATLON_CHANGE || lonDiff > MEDIUM_LATLON_CHANGE;
    final boolean bigChange = latDiff > BIG_LATLON_CHANGE || lonDiff > BIG_LATLON_CHANGE;
    // MainActivity.info( "lasttime: " + lasttime + " now: " + now + " ssid: " + network.getSsid()
    // + " lastlat: " + lastlat + " lat: " + location.getLatitude()
    // + " lastlon: " + lastlon + " lon: " + location.getLongitude() );
    final boolean smallLocDelay = now - lasttime > SMALL_LOC_DELAY;
    final boolean changeWorthy = mediumChange || (smallLocDelay && smallChange) || levelChange;
    final boolean blank = location.getLatitude() == 0 && location.getLongitude() == 0 && location.getAltitude() == 0 && location.getAccuracy() == 0 && update.level == 0;
    /**
     * ALIBI: +/-infinite lat/long, 0 timestamp data (even with high accuracy) is gigo
     */
    final boolean likelyJunk = Double.isInfinite(location.getLatitude()) || Double.isInfinite(location.getLongitude()) || location.getTime() == 0L;
    if (!blank && (isNew || bigChange || (!fastMode && changeWorthy))) {
        // MainActivity.info("inserting loc: " + network.getSsid() );
        insertLocation.bindString(1, bssid);
        // make sure to use the update's level, network's is mutable...
        insertLocation.bindLong(2, update.level);
        insertLocation.bindDouble(3, location.getLatitude());
        insertLocation.bindDouble(4, location.getLongitude());
        insertLocation.bindDouble(5, location.getAltitude());
        insertLocation.bindDouble(6, location.getAccuracy());
        insertLocation.bindLong(7, location.getTime());
        if (db.isDbLockedByOtherThreads()) {
            // this is kinda lame, make this better
            MainActivity.error("db locked by another thread, waiting to loc insert. bssid: " + bssid + " drainSize: " + drainSize);
            MainActivity.sleep(1000L);
        }
        long start = System.currentTimeMillis();
        // INSERT
        insertLocation.execute();
        logTime(start, "db location inserted: " + bssid + " drainSize: " + drainSize);
        // update the count
        locationCount.incrementAndGet();
        // update the cache
        CachedLocation cached = new CachedLocation();
        cached.location = location;
        cached.bestlevel = update.level;
        cached.bestlat = location.getLatitude();
        cached.bestlon = location.getLongitude();
        previousWrittenLocationsCache.put(bssid, cached);
        if (!isNew) {
            // update the network with the lasttime,lastlat,lastlon
            updateNetwork.bindLong(1, location.getTime());
            updateNetwork.bindDouble(2, location.getLatitude());
            updateNetwork.bindDouble(3, location.getLongitude());
            updateNetwork.bindString(4, bssid);
            if (db.isDbLockedByOtherThreads()) {
                // this is kinda lame, make this better
                MainActivity.error("db locked by another thread, waiting to net update. bssid: " + bssid + " drainSize: " + drainSize);
                MainActivity.sleep(1000L);
            }
            start = System.currentTimeMillis();
            // UPDATE
            updateNetwork.execute();
            logTime(start, "db network updated");
            boolean newBest = (bestlevel == 0 || update.level > bestlevel) && // https://github.com/wiglenet/wigle-wifi-wardriving/issues/82
            !likelyJunk;
            // MainActivity.info("META testing network: " + bssid + " newBest: " + newBest + " updatelevel: " + update.level + " bestlevel: " + bestlevel);
            if (newBest) {
                bestlevel = update.level;
                bestlat = location.getLatitude();
                bestlon = location.getLongitude();
            }
            if (smallLocDelay || newBest) {
                // MainActivity.info("META updating network: " + bssid + " newBest: " + newBest + " updatelevel: " + update.level + " bestlevel: " + bestlevel);
                updateNetworkMetadata.bindLong(1, bestlevel);
                updateNetworkMetadata.bindDouble(2, bestlat);
                updateNetworkMetadata.bindDouble(3, bestlon);
                updateNetworkMetadata.bindString(4, network.getSsid());
                updateNetworkMetadata.bindLong(5, network.getFrequency());
                updateNetworkMetadata.bindString(6, network.getCapabilities());
                updateNetworkMetadata.bindString(7, bssid);
                start = System.currentTimeMillis();
                updateNetworkMetadata.execute();
                logTime(start, "db network metadata updated");
            }
        }
    }
// else {
// MainActivity.info( "db network not changeworthy: " + bssid );
// }
}
Also used : Network(net.wigle.wigleandroid.model.Network) Cursor(android.database.Cursor) NoSuchElementException(java.util.NoSuchElementException) Location(android.location.Location)

Example 7 with Network

use of net.wigle.wigleandroid.model.Network in project wigle-wifi-wardriving by wiglenet.

the class ListFragment method setupListAdapter.

public static void setupListAdapter(final ListView listView, final FragmentActivity activity, final NetworkListAdapter listAdapter, final boolean isDbResult) {
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) {
            final Network network = (Network) parent.getItemAtPosition(position);
            MainActivity.getNetworkCache().put(network.getBssid(), network);
            final Intent intent = new Intent(activity, NetworkActivity.class);
            intent.putExtra(NETWORK_EXTRA_BSSID, network.getBssid());
            intent.putExtra(NETWORK_EXTRA_IS_DB_RESULT, isDbResult);
            activity.startActivity(intent);
        }
    });
}
Also used : Network(net.wigle.wigleandroid.model.Network) AdapterView(android.widget.AdapterView) Intent(android.content.Intent) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ListView(android.widget.ListView)

Example 8 with Network

use of net.wigle.wigleandroid.model.Network in project wigle-wifi-wardriving by wiglenet.

the class WifiReceiver method onReceive.

@SuppressWarnings("ConstantConditions")
@Override
public void onReceive(final Context context, final Intent intent) {
    scanInFlight = false;
    final long now = System.currentTimeMillis();
    lastScanResponseTime = now;
    // final long start = now;
    final WifiManager wifiManager = (WifiManager) mainActivity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    List<ScanResult> results = null;
    try {
        // return can be null!
        results = wifiManager.getScanResults();
    } catch (final SecurityException ex) {
        MainActivity.info("security exception getting scan results: " + ex, ex);
    } catch (final Exception ex) {
        // ignore, happens on some vm's
        MainActivity.info("exception getting scan results: " + ex, ex);
    }
    long nonstopScanRequestTime = Long.MIN_VALUE;
    final SharedPreferences prefs = mainActivity.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
    final long period = getScanPeriod();
    if (period == 0) {
        // treat as "continuous", so request scan in here
        doWifiScan();
        nonstopScanRequestTime = now;
    }
    final long setPeriod = mainActivity.getLocationSetPeriod();
    if (setPeriod != prevScanPeriod && mainActivity.isScanning()) {
        // update our location scanning speed
        MainActivity.info("setting location updates to: " + setPeriod);
        mainActivity.setLocationUpdates(setPeriod, 0f);
        prevScanPeriod = setPeriod;
    }
    // have the gps listener to a self-check, in case it isn't getting updates anymore
    final GPSListener gpsListener = mainActivity.getGPSListener();
    Location location = null;
    if (gpsListener != null) {
        final long gpsTimeout = prefs.getLong(ListFragment.PREF_GPS_TIMEOUT, GPSListener.GPS_TIMEOUT_DEFAULT);
        final long netLocTimeout = prefs.getLong(ListFragment.PREF_NET_LOC_TIMEOUT, GPSListener.NET_LOC_TIMEOUT_DEFAULT);
        gpsListener.checkLocationOK(gpsTimeout, netLocTimeout);
        location = gpsListener.getLocation();
    }
    // save the location every minute, for later runs, or viewing map during loss of location.
    if (now - lastSaveLocationTime > 60000L && location != null) {
        mainActivity.getGPSListener().saveLocation();
        lastSaveLocationTime = now;
    }
    if (location != null) {
        lastHaveLocationTime = now;
    }
    // + " lastHaveLocationTime: " + lastHaveLocationTime);
    if (now - lastHaveLocationTime > 30000L) {
        // no location in a while, make sure we're subscribed to updates
        MainActivity.info("no location for a while, setting location update period: " + setPeriod);
        mainActivity.setLocationUpdates(setPeriod, 0f);
        // don't do this until another period has passed
        lastHaveLocationTime = now;
    }
    final boolean showCurrent = prefs.getBoolean(ListFragment.PREF_SHOW_CURRENT, true);
    if (showCurrent && listAdapter != null) {
        listAdapter.clear();
    }
    final int preQueueSize = dbHelper.getQueueSize();
    final boolean fastMode = dbHelper.isFastMode();
    final ConcurrentLinkedHashMap<String, Network> networkCache = MainActivity.getNetworkCache();
    boolean somethingAdded = false;
    int resultSize = 0;
    int newWifiForRun = 0;
    final boolean ssidSpeak = prefs.getBoolean(ListFragment.PREF_SPEAK_SSID, false) && !mainActivity.isMuted();
    // TODO: should we memoize the ssidMatcher in the MainActivity state as well?
    final Matcher ssidMatcher = FilterMatcher.getSsidFilterMatcher(prefs, ListFragment.FILTER_PREF_PREFIX);
    final Matcher bssidMatcher = mainActivity.getBssidFilterMatcher(ListFragment.PREF_EXCLUDE_DISPLAY_ADDRS);
    final Matcher bssidDbMatcher = mainActivity.getBssidFilterMatcher(ListFragment.PREF_EXCLUDE_LOG_ADDRS);
    // 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) {
                newWifiForRun++;
                if (ssidSpeak) {
                    ssidSpeaker.add(network.getSsid());
                }
            }
            somethingAdded |= added;
            if (location != null && (added || network.getLatLng() == null)) {
                // set the LatLng for mapping
                final LatLng LatLng = new LatLng(location.getLatitude(), location.getLongitude());
                network.setLatLng(LatLng);
                MainActivity.addNetworkToMap(network);
            }
            // if we're showing current, or this was just added, put on the list
            if (showCurrent || added) {
                if (FilterMatcher.isOk(ssidMatcher, bssidMatcher, prefs, ListFragment.FILTER_PREF_PREFIX, network)) {
                    if (listAdapter != null) {
                        listAdapter.add(network);
                    }
                }
            // load test
            // for ( int i = 0; i< 10; i++) {
            // listAdapter.add( network );
            // }
            } else if (listAdapter != null) {
                // 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 (location != null) {
                // if in fast mode, only add new-for-run stuff to the db queue
                if (fastMode && !added) {
                    MainActivity.info("in fast mode, not adding seen-this-run: " + network.getBssid());
                } else {
                    // loop for stress-testing
                    // for ( int i = 0; i < 10; i++ ) {
                    boolean matches = false;
                    if (bssidDbMatcher != null) {
                        bssidDbMatcher.reset(network.getBssid());
                        matches = bssidDbMatcher.find();
                    }
                    if (!matches) {
                        dbHelper.addObservation(network, location, added);
                    }
                // }
                }
            } else {
                // no location
                boolean matches = false;
                if (bssidDbMatcher != null) {
                    bssidDbMatcher.reset(network.getBssid());
                    matches = bssidDbMatcher.find();
                }
                if (!matches) {
                    dbHelper.pendingObservation(network, added);
                }
            }
        }
    }
    // check if there are more "New" nets
    final long newNetCount = dbHelper.getNewNetworkCount();
    final long newWifiCount = dbHelper.getNewWifiCount();
    final long newNetDiff = newWifiCount - prevNewNetCount;
    prevNewNetCount = newWifiCount;
    // check for "New" cell towers
    final long newCellCount = dbHelper.getNewCellCount();
    if (!mainActivity.isMuted()) {
        final boolean playRun = prefs.getBoolean(ListFragment.PREF_FOUND_SOUND, true);
        final boolean playNew = prefs.getBoolean(ListFragment.PREF_FOUND_NEW_SOUND, true);
        if (newNetDiff > 0 && playNew) {
            mainActivity.playNewNetSound();
        } else if (somethingAdded && playRun) {
            mainActivity.playRunNetSound();
        }
    }
    if (mainActivity.getPhoneState().isPhoneActive()) {
        // a phone call is active, make sure we aren't speaking anything
        mainActivity.interruptSpeak();
    }
    // check cell tower info
    final int preCellForRun = runNetworks.size();
    int newCellForRun = 0;
    final Network cellNetwork = recordCellInfo(location);
    if (cellNetwork != null) {
        resultSize++;
        if (showCurrent && listAdapter != null && FilterMatcher.isOk(ssidMatcher, bssidMatcher, prefs, ListFragment.FILTER_PREF_PREFIX, cellNetwork)) {
            listAdapter.add(cellNetwork);
        }
        if (runNetworks.size() > preCellForRun) {
            newCellForRun++;
        }
    }
    final int sort = prefs.getInt(ListFragment.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;
    }
    if (listAdapter != null) {
        listAdapter.sort(comparator);
    }
    final long dbNets = dbHelper.getNetworkCount();
    final long dbLocs = dbHelper.getLocationCount();
    // update stat
    mainActivity.setNetCountUI();
    // set the statics for the map
    ListFragment.lameStatic.runNets = runNetworks.size();
    ListFragment.lameStatic.newNets = newNetCount;
    ListFragment.lameStatic.newWifi = newWifiCount;
    ListFragment.lameStatic.newCells = newCellCount;
    ListFragment.lameStatic.currNets = resultSize;
    ListFragment.lameStatic.preQueueSize = preQueueSize;
    ListFragment.lameStatic.dbNets = dbNets;
    ListFragment.lameStatic.dbLocs = dbLocs;
    // and will show up on map
    if (newWifiForRun > 0 || newCellForRun > 0 || ListFragment.lameStatic.networkCache.isEmpty()) {
        if (location == null) {
            // save for later
            pendingWifiCount += newWifiForRun;
            pendingCellCount += newCellForRun;
        // MainActivity.info("pendingCellCount: " + pendingCellCount);
        } else {
            // don't go crazy
            if (pendingWifiCount > 25) {
                pendingWifiCount = 25;
            }
            pendingWifiCount = 0;
            if (pendingCellCount > 25) {
                pendingCellCount = 25;
            }
            pendingCellCount = 0;
        }
    }
    // notify
    if (listAdapter != null) {
        listAdapter.notifyDataSetChanged();
    }
    if (scanRequestTime <= 0) {
        // wasn't set, set to now
        scanRequestTime = now;
    }
    final String status = resultSize + " " + mainActivity.getString(R.string.scanned_in) + " " + (now - scanRequestTime) + mainActivity.getString(R.string.ms_short) + ". " + mainActivity.getString(R.string.dash_db_queue) + " " + preQueueSize;
    mainActivity.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);
        // MainActivity.info("set last location for lerping");
        }
    } else {
        dbHelper.recoverLocations(location);
    }
    // do distance calcs
    if (location != null && GPS_PROVIDER.equals(location.getProvider()) && location.getAccuracy() <= ListFragment.MIN_DISTANCE_ACCURACY) {
        if (prevGpsLocation != null) {
            float dist = location.distanceTo(prevGpsLocation);
            // info( "dist: " + dist );
            if (dist > 0f) {
                final Editor edit = prefs.edit();
                edit.putFloat(ListFragment.PREF_DISTANCE_RUN, dist + prefs.getFloat(ListFragment.PREF_DISTANCE_RUN, 0f));
                edit.putFloat(ListFragment.PREF_DISTANCE_TOTAL, dist + prefs.getFloat(ListFragment.PREF_DISTANCE_TOTAL, 0f));
                edit.apply();
            }
        }
        // set for next time
        prevGpsLocation = location;
    }
    if (somethingAdded && ssidSpeak) {
        ssidSpeaker.speak();
    }
    final long speechPeriod = prefs.getLong(ListFragment.PREF_SPEECH_PERIOD, MainActivity.DEFAULT_SPEECH_PERIOD);
    if (speechPeriod != 0 && now - previousTalkTime > speechPeriod * 1000L) {
        doAnnouncement(preQueueSize, newWifiCount, newCellCount, now);
    }
}
Also used : WifiManager(android.net.wifi.WifiManager) ScanResult(android.net.wifi.ScanResult) SharedPreferences(android.content.SharedPreferences) FilterMatcher(net.wigle.wigleandroid.FilterMatcher) Matcher(java.util.regex.Matcher) Network(net.wigle.wigleandroid.model.Network) LatLng(com.google.android.gms.maps.model.LatLng) Editor(android.content.SharedPreferences.Editor) GsmCellLocation(android.telephony.gsm.GsmCellLocation) CellLocation(android.telephony.CellLocation) Location(android.location.Location)

Example 9 with Network

use of net.wigle.wigleandroid.model.Network in project wigle-wifi-wardriving by wiglenet.

the class WifiReceiver method recordCellInfo.

private Network recordCellInfo(final Location location) {
    TelephonyManager tele = (TelephonyManager) mainActivity.getSystemService(Context.TELEPHONY_SERVICE);
    Network network = null;
    if (tele != null) {
        /*
      List<NeighboringCellInfo> list = tele.getNeighboringCellInfo();
      for (final NeighboringCellInfo cell : list ) {
        MainActivity.info("neigh cell: " + cell + " class: " + cell.getClass().getCanonicalName() );
        MainActivity.info("cid: " + cell.getCid());

        // api level 5!!!!
        MainActivity.info("lac: " + cell.getLac() );
        MainActivity.info("psc: " + cell.getPsc() );
        MainActivity.info("net type: " + cell.getNetworkType() );
        MainActivity.info("nettypename: " + getNetworkTypeName() );
      }
      */
        String bssid = null;
        NetworkType type = null;
        CellLocation cellLocation = null;
        try {
            cellLocation = tele.getCellLocation();
        } catch (NullPointerException ex) {
        // bug in Archos7 can NPE there, just ignore
        } catch (final SecurityException ex) {
            MainActivity.info("Security exception tele.getCellLocation: " + ex);
        }
        // noinspection StatementWithEmptyBody
        if (cellLocation == null) {
        // ignore
        } else 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);
                if (systemId > 0 && networkId >= 0 && baseStationId >= 0) {
                    bssid = systemId + "_" + networkId + "_" + baseStationId;
                    type = NetworkType.CDMA;
                }
            } catch (Exception ex) {
                MainActivity.error("cdma reflection exception: " + ex);
            }
        } else if (cellLocation instanceof GsmCellLocation) {
            GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
            if (gsmCellLocation.getLac() >= 0 && gsmCellLocation.getCid() >= 0) {
                bssid = tele.getNetworkOperator() + "_" + gsmCellLocation.getLac() + "_" + gsmCellLocation.getCid();
                type = NetworkType.GSM;
            }
        }
        if (bssid != null) {
            final String ssid = tele.getNetworkOperatorName();
            final String networkType = getNetworkTypeName();
            final String capabilities = networkType + ";" + tele.getNetworkCountryIso();
            int strength = 0;
            PhoneState phoneState = mainActivity.getPhoneState();
            if (phoneState != null) {
                strength = phoneState.getStrength();
            }
            if (NetworkType.GSM.equals(type)) {
                strength = gsmRssiMagicDecoderRing(strength);
            }
            // MainActivity.info( "bssid: " + bssid );
            // MainActivity.info( "strength: " + strength );
            // MainActivity.info( "ssid: " + ssid );
            // MainActivity.info( "capabilities: " + capabilities );
            // MainActivity.info( "networkType: " + networkType );
            // MainActivity.info( "location: " + location );
            final ConcurrentLinkedHashMap<String, Network> networkCache = MainActivity.getNetworkCache();
            final boolean newForRun = runNetworks.add(bssid);
            network = networkCache.get(bssid);
            if (network == null) {
                network = new Network(bssid, ssid, 0, capabilities, strength, type);
                networkCache.put(network.getBssid(), network);
            } else {
                network.setLevel(strength);
            }
            if (location != null && (newForRun || network.getLatLng() == null)) {
                // set the LatLng for mapping
                final LatLng LatLng = new LatLng(location.getLatitude(), location.getLongitude());
                network.setLatLng(LatLng);
            }
            if (location != null) {
                dbHelper.addObservation(network, location, newForRun);
            }
        }
    }
    return network;
}
Also used : GsmCellLocation(android.telephony.gsm.GsmCellLocation) CellLocation(android.telephony.CellLocation) TelephonyManager(android.telephony.TelephonyManager) NetworkType(net.wigle.wigleandroid.model.NetworkType) Network(net.wigle.wigleandroid.model.Network) GsmCellLocation(android.telephony.gsm.GsmCellLocation) LatLng(com.google.android.gms.maps.model.LatLng)

Example 10 with Network

use of net.wigle.wigleandroid.model.Network in project wigle-wifi-wardriving by wiglenet.

the class ObservationImporter method getResultString.

@Override
protected String getResultString(final BufferedReader reader) throws IOException, InterruptedException {
    Bundle bundle = new Bundle();
    try {
        JsonFactory f = new MappingJsonFactory();
        JsonParser jp = f.createParser(reader);
        JsonToken current;
        current = jp.nextToken();
        if (current != JsonToken.START_OBJECT) {
            System.out.println("Error: root should be object: quiting.");
            return null;
        }
        Integer total = 0;
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            current = jp.nextToken();
            if (fieldName.equals("success")) {
                if (current.isBoolean()) {
                    if (current == JsonToken.VALUE_TRUE) {
                        MainActivity.info("successful load");
                    } else {
                        MainActivity.error("MyObserved success: false");
                        status = Status.EXCEPTION;
                        bundle.putString(BackgroundGuiHandler.ERROR, "ERROR: success: false");
                    }
                }
            } else if (fieldName.equals("count")) {
                total = jp.getIntValue();
                MainActivity.info("received " + total + " observations");
                if (total > 0) {
                    status = Status.SUCCESS;
                }
            } else if (fieldName.equals("results")) {
                if (current == JsonToken.START_ARRAY) {
                    // For each of the records in the array
                    int i = 0;
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        String netId = jp.getValueAsString();
                        // DEBUG: MainActivity.info(netId);
                        final String ssid = "";
                        final int frequency = 0;
                        final String capabilities = "";
                        final int level = 0;
                        final Network network = new Network(netId, ssid, frequency, capabilities, level, NetworkType.WIFI);
                        final Location location = new Location("wigle");
                        final boolean newForRun = true;
                        ListFragment.lameStatic.dbHelper.blockingAddObservation(network, location, newForRun);
                        if ((i % 1000) == 0) {
                            MainActivity.info("lineCount: " + i + " of " + total);
                        }
                        if (total == 0) {
                            total = 1;
                        }
                        final int percentDone = (i * 1000) / total;
                        sendPercentTimesTen(percentDone, bundle);
                        i++;
                    }
                } else {
                    System.out.println("Error: records should be an array: skipping.");
                    jp.skipChildren();
                }
            } else {
                System.out.println("Unprocessed property: " + fieldName);
                jp.skipChildren();
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        status = Status.EXCEPTION;
        bundle.putString(BackgroundGuiHandler.ERROR, "Connection problem: " + e);
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        status = Status.EXCEPTION;
        bundle.putString(BackgroundGuiHandler.ERROR, "ERROR: " + e + " (from " + e.getCause() + ")");
        return status.toString();
    } finally {
        if (status == null) {
            status = Status.FAIL;
        }
        try {
            listener.requestComplete(null, false);
        } catch (WiGLEAuthException waex) {
            MainActivity.error("Unable to download data - authorization failed");
            status = Status.BAD_LOGIN;
        }
    }
    return status.toString();
}
Also used : MappingJsonFactory(com.fasterxml.jackson.databind.MappingJsonFactory) Bundle(android.os.Bundle) MappingJsonFactory(com.fasterxml.jackson.databind.MappingJsonFactory) JsonFactory(com.fasterxml.jackson.core.JsonFactory) IOException(java.io.IOException) WiGLEAuthException(net.wigle.wigleandroid.WiGLEAuthException) WiGLEAuthException(net.wigle.wigleandroid.WiGLEAuthException) Network(net.wigle.wigleandroid.model.Network) JsonToken(com.fasterxml.jackson.core.JsonToken) JsonParser(com.fasterxml.jackson.core.JsonParser) Location(android.location.Location)

Aggregations

Network (net.wigle.wigleandroid.model.Network)10 LatLng (com.google.android.gms.maps.model.LatLng)4 SuppressLint (android.annotation.SuppressLint)3 Cursor (android.database.Cursor)3 Location (android.location.Location)3 TextView (android.widget.TextView)3 SharedPreferences (android.content.SharedPreferences)2 CellLocation (android.telephony.CellLocation)2 GsmCellLocation (android.telephony.gsm.GsmCellLocation)2 View (android.view.View)2 NetworkType (net.wigle.wigleandroid.model.NetworkType)2 Intent (android.content.Intent)1 Editor (android.content.SharedPreferences.Editor)1 PackageInfo (android.content.pm.PackageInfo)1 PackageManager (android.content.pm.PackageManager)1 Address (android.location.Address)1 ScanResult (android.net.wifi.ScanResult)1 WifiManager (android.net.wifi.WifiManager)1 Bundle (android.os.Bundle)1 Handler (android.os.Handler)1