Search in sources :

Example 1 with Network

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

the class DatabaseHelper method getNetwork.

public Network getNetwork(final String bssid) {
    // check cache
    Network retval = MainActivity.getNetworkCache().get(bssid);
    if (retval == null) {
        try {
            checkDB();
            final String[] args = new String[] { bssid };
            final Cursor cursor = db.rawQuery("select ssid,frequency,capabilities,type,lastlat,lastlon,bestlat,bestlon FROM " + NETWORK_TABLE + " WHERE bssid = ?", args);
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                final String ssid = cursor.getString(0);
                final int frequency = cursor.getInt(1);
                final String capabilities = cursor.getString(2);
                final float lastlat = cursor.getFloat(4);
                final float lastlon = cursor.getFloat(5);
                final float bestlat = cursor.getFloat(6);
                final float bestlon = cursor.getFloat(7);
                final NetworkType type = NetworkType.typeForCode(cursor.getString(3));
                retval = new Network(bssid, ssid, frequency, capabilities, 0, type);
                if (bestlat != 0 && bestlon != 0) {
                    retval.setLatLng(new LatLng(bestlat, bestlon));
                } else {
                    retval.setLatLng(new LatLng(lastlat, lastlon));
                }
                MainActivity.getNetworkCache().put(bssid, retval);
            }
            cursor.close();
        } catch (DBException ex) {
            deathDialog("getNetwork", ex);
        }
    }
    return retval;
}
Also used : NetworkType(net.wigle.wigleandroid.model.NetworkType) Network(net.wigle.wigleandroid.model.Network) LatLng(com.google.android.gms.maps.model.LatLng) Cursor(android.database.Cursor)

Example 2 with Network

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

the class ObservationUploader method writeFileWithCursor.

/**
 * (lifted directly from FileUploaderTask)
 * @param fos
 * @param bundle
 * @param countStats
 * @param cursor
 * @return
 * @throws IOException
 * @throws PackageManager.NameNotFoundException
 * @throws InterruptedException
 */
@SuppressLint("SimpleDateFormat")
private long writeFileWithCursor(final OutputStream fos, final Bundle bundle, final ObservationUploader.CountStats countStats, final Cursor cursor) throws IOException, PackageManager.NameNotFoundException, InterruptedException {
    final SharedPreferences prefs = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
    long maxId = prefs.getLong(ListFragment.PREF_DB_MARKER, 0L);
    final long start = System.currentTimeMillis();
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    countStats.lineCount = 0;
    final int total = cursor.getCount();
    long fileWriteMillis = 0;
    long netMillis = 0;
    sendBundledMessage(Status.WRITING.ordinal(), bundle);
    final PackageManager pm = context.getPackageManager();
    final PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
    // name, version, header
    final String header = "WigleWifi-1.4" + ",appRelease=" + pi.versionName + ",model=" + android.os.Build.MODEL + ",release=" + android.os.Build.VERSION.RELEASE + ",device=" + android.os.Build.DEVICE + ",display=" + android.os.Build.DISPLAY + ",board=" + android.os.Build.BOARD + ",brand=" + android.os.Build.BRAND + "\n" + "MAC,SSID,AuthMode,FirstSeen,Channel,RSSI,CurrentLatitude,CurrentLongitude,AltitudeMeters,AccuracyMeters,Type\n";
    writeFos(fos, header);
    // assume header is all byte per char
    countStats.byteCount = header.length();
    if (total > 0) {
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        // this ensures hasArray() is true
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        final CharsetEncoder encoder = Charset.forName(MainActivity.ENCODING).newEncoder();
        // don't stop when a goofy character is found
        encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
        final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
        // no commas in the comma-separated file
        numberFormat.setGroupingUsed(false);
        if (numberFormat instanceof DecimalFormat) {
            final DecimalFormat dc = (DecimalFormat) numberFormat;
            dc.setMaximumFractionDigits(16);
        }
        final StringBuffer stringBuffer = new StringBuffer();
        final FieldPosition fp = new FieldPosition(NumberFormat.INTEGER_FIELD);
        final Date date = new Date();
        // loop!
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            if (wasInterrupted()) {
                throw new InterruptedException("we were interrupted");
            }
            // _id,bssid,level,lat,lon,time
            final long id = cursor.getLong(0);
            if (id > maxId) {
                maxId = id;
            }
            final String bssid = cursor.getString(1);
            final long netStart = System.currentTimeMillis();
            final Network network = dbHelper.getNetwork(bssid);
            netMillis += System.currentTimeMillis() - netStart;
            if (network == null) {
                // weird condition, skipping
                MainActivity.error("network not in database: " + bssid);
                continue;
            }
            countStats.lineCount++;
            String ssid = network.getSsid();
            if (ssid.contains(COMMA)) {
                // comma isn't a legal ssid character, but just in case
                ssid = ssid.replaceAll(COMMA, "_");
            }
            // ListActivity.debug("writing network: " + ssid );
            // reset the buffers
            charBuffer.clear();
            byteBuffer.clear();
            // fill in the line
            try {
                charBuffer.append(network.getBssid());
                charBuffer.append(COMMA);
                // ssid can be unicode
                charBuffer.append(ssid);
                charBuffer.append(COMMA);
                charBuffer.append(network.getCapabilities());
                charBuffer.append(COMMA);
                date.setTime(cursor.getLong(7));
                singleCopyDateFormat(dateFormat, stringBuffer, charBuffer, fp, date);
                charBuffer.append(COMMA);
                Integer channel = network.getChannel();
                if (channel == null) {
                    channel = network.getFrequency();
                }
                singleCopyNumberFormat(numberFormat, stringBuffer, charBuffer, fp, channel);
                charBuffer.append(COMMA);
                singleCopyNumberFormat(numberFormat, stringBuffer, charBuffer, fp, cursor.getInt(2));
                charBuffer.append(COMMA);
                singleCopyNumberFormat(numberFormat, stringBuffer, charBuffer, fp, cursor.getDouble(3));
                charBuffer.append(COMMA);
                singleCopyNumberFormat(numberFormat, stringBuffer, charBuffer, fp, cursor.getDouble(4));
                charBuffer.append(COMMA);
                singleCopyNumberFormat(numberFormat, stringBuffer, charBuffer, fp, cursor.getDouble(5));
                charBuffer.append(COMMA);
                singleCopyNumberFormat(numberFormat, stringBuffer, charBuffer, fp, cursor.getDouble(6));
                charBuffer.append(COMMA);
                charBuffer.append(network.getType().name());
                charBuffer.append(NEWLINE);
            } catch (BufferOverflowException ex) {
                MainActivity.info("buffer overflow: " + ex, ex);
                // double the buffer
                charBuffer = CharBuffer.allocate(charBuffer.capacity() * 2);
                byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
                // try again
                cursor.moveToPrevious();
                continue;
            }
            // tell the encoder to stop here and to start at the beginning
            charBuffer.flip();
            // do the encoding
            encoder.reset();
            encoder.encode(charBuffer, byteBuffer, true);
            try {
                encoder.flush(byteBuffer);
            } catch (IllegalStateException ex) {
                MainActivity.error("exception flushing: " + ex, ex);
                continue;
            }
            // byteBuffer = encoder.encode( charBuffer );  (old way)
            // figure out where in the byteBuffer to stop
            final int end = byteBuffer.position();
            final int offset = byteBuffer.arrayOffset();
            // if ( end == 0 ) {
            // if doing the encode without giving a long-term byteBuffer (old way), the output
            // byteBuffer position is zero, and the limit and capacity are how long to write for.
            // end = byteBuffer.limit();
            // }
            // MainActivity.info("buffer: arrayOffset: " + byteBuffer.arrayOffset() + " limit: "
            // + byteBuffer.limit()
            // + " capacity: " + byteBuffer.capacity() + " pos: " + byteBuffer.position() +
            // " end: " + end
            // + " result: " + result );
            final long writeStart = System.currentTimeMillis();
            fos.write(byteBuffer.array(), offset, end + offset);
            fileWriteMillis += System.currentTimeMillis() - writeStart;
            countStats.byteCount += end;
            // update UI
            final int percentDone = (countStats.lineCount * 1000) / total;
            sendPercentTimesTen(percentDone, bundle);
        }
    }
    MainActivity.info("wrote file in: " + (System.currentTimeMillis() - start) + "ms. fileWriteMillis: " + fileWriteMillis + " netmillis: " + netMillis);
    return maxId;
}
Also used : SharedPreferences(android.content.SharedPreferences) PackageInfo(android.content.pm.PackageInfo) DecimalFormat(java.text.DecimalFormat) CharBuffer(java.nio.CharBuffer) FieldPosition(java.text.FieldPosition) ByteBuffer(java.nio.ByteBuffer) CharsetEncoder(java.nio.charset.CharsetEncoder) SuppressLint(android.annotation.SuppressLint) Date(java.util.Date) PackageManager(android.content.pm.PackageManager) Network(net.wigle.wigleandroid.model.Network) BufferOverflowException(java.nio.BufferOverflowException) SimpleDateFormat(java.text.SimpleDateFormat) NumberFormat(java.text.NumberFormat) SuppressLint(android.annotation.SuppressLint)

Example 3 with Network

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

the class DBResultActivity method setupQuery.

@SuppressLint("HandlerLeak")
private void setupQuery(final QueryArgs queryArgs) {
    final Address address = queryArgs.getAddress();
    // what runs on the gui thread
    final Handler handler = new Handler() {

        @Override
        public void handleMessage(final Message msg) {
            final TextView tv = (TextView) findViewById(R.id.dbstatus);
            if (msg.what == MSG_QUERY_DONE) {
                tv.setText(getString(R.string.status_success));
                listAdapter.clear();
                boolean first = true;
                for (final Network network : resultList) {
                    listAdapter.add(network);
                    if (address == null && first) {
                        final LatLng center = MappingFragment.getCenter(DBResultActivity.this, network.getLatLng(), null);
                        MainActivity.info("set center: " + center + " network: " + network.getSsid() + " point: " + network.getLatLng());
                        mapView.getMapAsync(new OnMapReadyCallback() {

                            @Override
                            public void onMapReady(final GoogleMap googleMap) {
                                final CameraPosition cameraPosition = new CameraPosition.Builder().target(center).zoom(DEFAULT_ZOOM).build();
                                googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                            }
                        });
                        first = false;
                    }
                    if (network.getLatLng() != null && mapRender != null) {
                        mapRender.addItem(network);
                    }
                }
                resultList.clear();
            }
        }
    };
    String sql = "SELECT bssid,lastlat,lastlon FROM " + DatabaseHelper.NETWORK_TABLE + " WHERE 1=1 ";
    final String ssid = queryArgs.getSSID();
    final String bssid = queryArgs.getBSSID();
    boolean limit = false;
    if (ssid != null && !"".equals(ssid)) {
        sql += " AND ssid like " + DatabaseUtils.sqlEscapeString(ssid);
        limit = true;
    }
    if (bssid != null && !"".equals(bssid)) {
        sql += " AND bssid like " + DatabaseUtils.sqlEscapeString(bssid);
        limit = true;
    }
    if (address != null) {
        final double diff = 0.1d;
        final double lat = address.getLatitude();
        final double lon = address.getLongitude();
        sql += " AND lastlat > '" + (lat - diff) + "' AND lastlat < '" + (lat + diff) + "'";
        sql += " AND lastlon > '" + (lon - diff) + "' AND lastlon < '" + (lon + diff) + "'";
    }
    if (limit) {
        sql += " LIMIT " + LIMIT;
    }
    final TreeMap<Float, String> top = new TreeMap<>();
    final float[] results = new float[1];
    final long[] count = new long[1];
    final QueryThread.Request request = new QueryThread.Request(sql, new QueryThread.ResultHandler() {

        @Override
        public boolean handleRow(final Cursor cursor) {
            final String bssid = cursor.getString(0);
            final float lat = cursor.getFloat(1);
            final float lon = cursor.getFloat(2);
            count[0]++;
            if (address == null) {
                top.put((float) count[0], bssid);
            } else {
                Location.distanceBetween(lat, lon, address.getLatitude(), address.getLongitude(), results);
                final float meters = results[0];
                if (top.size() <= LIMIT) {
                    putWithBackoff(top, bssid, meters);
                } else {
                    Float last = top.lastKey();
                    if (meters < last) {
                        top.remove(last);
                        putWithBackoff(top, bssid, meters);
                    }
                }
            }
            return true;
        }

        @Override
        public void complete() {
            for (final String bssid : top.values()) {
                final Network network = ListFragment.lameStatic.dbHelper.getNetwork(bssid);
                resultList.add(network);
                final LatLng point = network.getLatLng();
                if (point != null) {
                    obsMap.put(point, 0);
                }
            }
            handler.sendEmptyMessage(MSG_QUERY_DONE);
            if (mapView != null) {
                // force a redraw
                mapView.postInvalidate();
            }
        }
    });
    // queue it up
    ListFragment.lameStatic.dbHelper.addToQueue(request);
}
Also used : Address(android.location.Address) Message(android.os.Message) Handler(android.os.Handler) OnMapReadyCallback(com.google.android.gms.maps.OnMapReadyCallback) TreeMap(java.util.TreeMap) Cursor(android.database.Cursor) CameraPosition(com.google.android.gms.maps.model.CameraPosition) GoogleMap(com.google.android.gms.maps.GoogleMap) Network(net.wigle.wigleandroid.model.Network) QueryThread(net.wigle.wigleandroid.background.QueryThread) TextView(android.widget.TextView) LatLng(com.google.android.gms.maps.model.LatLng) SuppressLint(android.annotation.SuppressLint)

Example 4 with Network

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

the class MapRender method addLatestNetworks.

private void addLatestNetworks() {
    // add items
    int cached = 0;
    int added = 0;
    final Collection<Network> nets = MainActivity.getNetworkCache().values();
    for (final Network network : nets) {
        cached++;
        if (okForMapTab(network)) {
            added++;
            mClusterManager.addItem(network);
        }
    }
    MainActivity.info("MapRender cached: " + cached + " added: " + added);
    networkCount.getAndAdd(added);
    mClusterManager.cluster();
}
Also used : Network(net.wigle.wigleandroid.model.Network) SuppressLint(android.annotation.SuppressLint)

Example 5 with Network

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

the class NetworkListAdapter method getView.

@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    // long start = System.currentTimeMillis();
    View row;
    if (null == convertView) {
        row = mInflater.inflate(R.layout.row, parent, false);
    } else {
        row = convertView;
    }
    Network network;
    try {
        network = getItem(position);
    } catch (final IndexOutOfBoundsException ex) {
        // yes, this happened to someone
        MainActivity.info("index out of bounds: " + position + " ex: " + ex);
        return row;
    }
    // info( "listing net: " + network.getBssid() );
    final ImageView ico = (ImageView) row.findViewById(R.id.wepicon);
    ico.setImageResource(getImage(network));
    TextView tv = (TextView) row.findViewById(R.id.ssid);
    tv.setText(network.getSsid() + " ");
    tv = (TextView) row.findViewById(R.id.oui);
    final String ouiString = network.getOui(ListFragment.lameStatic.oui);
    final String sep = ouiString.length() > 0 ? " - " : "";
    tv.setText(ouiString + sep);
    tv = (TextView) row.findViewById(R.id.time);
    tv.setText(getConstructionTime(format, network));
    tv = (TextView) row.findViewById(R.id.level_string);
    final int level = network.getLevel();
    tv.setTextColor(getSignalColor(level));
    tv.setText(Integer.toString(level));
    tv = (TextView) row.findViewById(R.id.detail);
    String det = network.getDetail();
    tv.setText(det);
    return row;
}
Also used : Network(net.wigle.wigleandroid.model.Network) TextView(android.widget.TextView) ImageView(android.widget.ImageView) ImageView(android.widget.ImageView) TextView(android.widget.TextView) View(android.view.View)

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