Code Monkey home page Code Monkey logo

noise-snr-collector's People

Contributors

sanal-cem avatar

Stargazers

 avatar

Watchers

 avatar  avatar

noise-snr-collector's Issues

Inserting data into MYSQL database with HTTP GET from Android app with PHP

Save that file into a working PHP server which could connect to the applications MYSQL database.

   $username = $_GET['username'];
   $password = $_GET['password'];
   $ROUTENUM = $_GET['ROUTENUM'];
   $SNR = $_GET['SNR'];
   $LOC_X = $_GET['LOC_X'];
   $LOC_Y = $_GET['LOC_Y'];
   $SDATE = $_GET['SDATE'];
   $STIME = $_GET['STIME'];
   $TABLE = $_GET['TABLE'];

$con = mysqli_connect("connection_string", "$username", "$password", "database_name");

  if (mysqli_connect_errno($con)) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   if (mysqli_query($con, "INSERT INTO $TABLE (ROUTENUM, SNR, LOC_X, LOC_Y, SDATE, STIME) VALUES('$ROUTENUM', '$SNR', '$LOC_X', '$LOC_Y', '$SDATE', '$STIME')")) {
      echo "New record created successfully";
   }
   mysqli_close($con);

Listening Mobile-Cell Signal in different phone brands

  • To listen cell signal, SignalStrength object is not enough. In Listening Mobile Cell signal link, listening cell signal for many phone brands is told. Some brands like Huawei do not let us to listen signal properties easily. That should be a security precaution. The functions return 0 or -1 when they are called.
    In Huawei, below results returned;
signalStrength.getCdmaDbm() = -1
signalStrength.getGsmSignalStrength() = 0
signalStrength.getEvdoDbm() = -1

I found an easy way to listen signal from different phone brands.

  1. Decode the SignalStrength object.
@Override
    public void onSignalStrengthsChanged(SignalStrength signalStrength) {
String ss = signalStrength.toString();
       // That ss string contains 16 different objects in Huawei and these objects change from brand to brand. Object number also changes.
  1. Seperate the string using the spaces as below:
    String[] s = ss.split(" ");
  2. Assign as below:
    networkSignal = Double.parseDouble(parts[1]);

Route Creation on users tap

User would create a route from his/her location to his/her destination with tapping the screen. If both users location and destination are on road, the route will be created. A seperate google maps API key should be used. The key should not be restricted. Below is the code.

    @Override
    public void onMapReady(GoogleMap map) {
    ...
    addRoute();
    }
    // get users location
    private void addRoute() {
        GPSTracker gpsTObj = new GPSTracker(this);
        lat = gpsTObj.getLatitude();
        lon = gpsTObj.getLongitude();

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            // listens map clicks
            @Override
            public void onMapClick(LatLng arg0) {

                // get location of SNR data.
                LatLng here = new LatLng(lat, lon);
                mMap.addMarker(new MarkerOptions().position(here).title("Here"));

                LatLng dest = new LatLng(arg0.latitude, arg0.longitude);
                mMap.addMarker(new MarkerOptions().position(dest).title("Destination"));

                //Define list to get all latlng for the route
                List<LatLng> path = new ArrayList<>();

                //Execute Directions API request
                GeoApiContext context = new GeoApiContext.Builder()
                        .apiKey("AIzaSyDx2KozXbBaNYXSD7MdE9twW4KwKyiEoMk")
                        .build();
                DirectionsApiRequest req = DirectionsApi.getDirections(context, "lat, lon", "arg0.latitude, arg0.longitude");
                try {
                    DirectionsResult res = req.await();

                    //Loop through legs and steps to get encoded polylines of each step
                    if (res.routes != null && res.routes.length > 0) {
                        DirectionsRoute route = res.routes[0];

                        if (route.legs !=null) {
                            for(int i=0; i<route.legs.length; i++) {
                                DirectionsLeg leg = route.legs[i];
                                if (leg.steps != null) {
                                    for (int j=0; j<leg.steps.length;j++){
                                        DirectionsStep step = leg.steps[j];
                                        if (step.steps != null && step.steps.length >0) {
                                            for (int k=0; k<step.steps.length;k++){
                                                DirectionsStep step1 = step.steps[k];
                                                EncodedPolyline points1 = step1.polyline;
                                                if (points1 != null) {
                                                    //Decode polyline and add points to list of route coordinates
                                                    List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
                                                    for (com.google.maps.model.LatLng coord1 : coords1) {
                                                        path.add(new LatLng(coord1.lat, coord1.lng));
                                                    }
                                                }
                                            }
                                        } else {
                                            EncodedPolyline points = step.polyline;
                                            if (points != null) {
                                                //Decode polyline and add points to list of route coordinates
                                                List<com.google.maps.model.LatLng> coords = points.decodePath();
                                                for (com.google.maps.model.LatLng coord : coords) {
                                                    path.add(new LatLng(coord.lat, coord.lng));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch(Exception ex) {
                    ex.getLocalizedMessage();
                }

                //Draw the polyline
                if (path.size() > 0) {
                    PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
                    mMap.addPolyline(opts);
                }

                mMap.getUiSettings().setZoomControlsEnabled(true);

                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(here, 6));
            }
        });
    }

Analyzing Cell-Mobile signal in different phone brands

Reading signal from some phone brands, SignalStrength functions do not work properly. They return 0 or -1. Checking SignalStrength functions should be done. If these functions return 0 or -1, SignalStrength string could be read and splitted. Splitting SignalStrength and reading signal data from Huawei Honor 6 is below.

private void analyzeCellHuawei(SignalStrength ssH) {
        String ssignal = ssH.toString();
        String[] parts = ssignal.split(" ");
        if(ssH.getCdmaDbm() == -1 && ssH.getGsmSignalStrength() == 0 && ssH.getEvdoDbm() == -1  ) {
            if (!parts[1].toString().equals("0") || !parts[2].toString().equals("0") || !parts[3].toString().equals("0")) {
                Global.myNetwork_Signal = Double.parseDouble(parts[3]) + 0.0;
                Global.SNR = Double.parseDouble(parts[7]) + 0.0;
            } else {
                Global.myNetwork_Signal = Double.parseDouble(parts[12]) + 0.0;
                Global.SNR = Double.parseDouble(parts[11]) + 0.0;
            }
        }
        else {
            analyzeCellGeneral(ssH);
        }
    }
    private void analyzeCellGeneral(SignalStrength ssG) {
        if (ssG.isGsm()) {
            if (ssG.getGsmSignalStrength() != 99)
                Global.myNetwork_Signal = ssG.getGsmSignalStrength() * 2 - 113.0;
            else
                Global.myNetwork_Signal = ssG.getGsmSignalStrength() + 0.0;
        } else {
            Global.myNetwork_Signal = ssG.getCdmaDbm() + 0.0;
        }
        Global.SNR = ssG.getEvdoSnr() + 0.0;
    }

Below is the SignalStrength string.

part[0] = "Signalstrength:"  _ignore this, it's just the title_
parts[1] = GsmSignalStrength
parts[2] = GsmBitErrorRate
parts[3] = CdmaDbm
parts[4] = CdmaEcio
parts[5] = EvdoDbm
parts[6] = EvdoEcio
parts[7] = EvdoSnr
parts[8] = LteSignalStrength
parts[9] = LteRsrp
parts[10] = LteRsrq
parts[11] = LteRssnr
parts[12] = LteCqi
parts[13] = gsm|lte|cdma

Sending SNR data with HTTP GET and AsyncTask

Database queries should be done using AsyncTask in Android. Works with issue #6

    @Override
    protected String doInBackground(fetchedSNRDataP... arrFSnrDP) {
        String textViewResult = "";
        HttpResponse response;

        response = null;
        try {
            String link = "server_string/sendData.php/?username=" + "root" + "&password=" + "asdcemasd"
                    + "&ROUTENUM=" + arrFSnrDP[0].getRouteNum() + "&SNR=" + arrFSnrDP[0].getSNR()
                    + "&LOC_X=" + arrFSnrDP[0].getLoc_x() + "&LOC_Y=" + arrFSnrDP[0].getLoc_y() + "&SDATE=" + arrFSnrDP[0].getDate() + "&STIME=" + arrFSnrDP[0].getTime() + "&TABLE=" + arrFSnrDP[0].getTable();

            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            response = client.execute(request);

            textViewResult = "Data Sent";

        } catch (Exception e) {
            e.printStackTrace();
            textViewResult = "error " + response;
        }
        return textViewResult;
    }

Creating time interval after every sensor read

Waiting would be done inside a thread not to interrupt the whole activity. fetching data, drawing the graph are done realtime in the code below:

    @Override
    protected void onResume() {
        super.onResume();
        Global.Moving_Avg_Signal = 0.0;
        try {
            mTimer1 = new Runnable() {
                @Override
                public void run() {
                    if(graph != null)
                        graph.removeAllSeries();
                    if (Global.jsonText != null) {
                        fetchSNR();
                        drawGraph();
                        setPageText();
                    }
                    new asyncGraphSmallWait().execute(mHandler, mTimer1, 40);
                }
            };
            new asyncGraphSmallWait().execute(mHandler, mTimer1, 40);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

AsyncTask execution with sending different variables

First AsyncTask example:

For creating delayed background processes without halting whole application, AsyncTask is needed. Parameter type should be written to the class definition. In the doInBackground declaration, parameter should be written as doInBackground(paramType... params). asyncTask class should be called with different type parameters inside the function call.

// Calling the asyncTask method:
new asyncGraphSmallWait().execute(mHandler, mTimer1, 40);
public class asyncGraphSmallWait extends AsyncTask<Object, Void, Void>
{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
    @Override
    protected Void doInBackground(Object... params) {
        Handler mHandler = (Handler) params[0];
        Runnable mTimer1 = (Runnable) params[1];
        int time = (int) params[2];
        mHandler.postDelayed(mTimer1, time);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //this method will be running on UI thread

    }
}

Listening Cell-Mobile signal via SignalStrength

Executing the phoneListener

TelephonyManager tm = (TelephonyManager) c.getSystemService(c.TELEPHONY_SERVICE);
tm.listen(this, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

Listener for the signal strength.

    @Override
    public void onSignalStrengthsChanged(SignalStrength ss) {
        super.onSignalStrengthsChanged(ss);

        //if phone is not Huawei, execute the general analyzing code.
        analyzeCellGeneral(ss);
    }
    private void analyzeCellGeneral(SignalStrength ssG) {
        if (ssG.isGsm()) {
            if (ssG.getGsmSignalStrength() != 99)
                Global.myNetwork_Signal = ssG.getGsmSignalStrength() * 2 - 113.0;
            else
                Global.myNetwork_Signal = ssG.getGsmSignalStrength() + 0.0;
        } else {
            Global.myNetwork_Signal = ssG.getCdmaDbm() + 0.0;
        }
        Global.SNR = ssG.getEvdoSnr() + 0.0;
    }

New secure queries

Database queries should not be done using HTTP GET method. A secure method should be found and implemented.

More proper location reading

Location is read by the GPS service. However, GPS service does not respond very fast and it could not be used very easily as tracking the route from the real google maps. Android’s GPS service should be understood better and the application should be developed accordingly. I used a general GPSTracker code for reading the location.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.