Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.93 KB | None | 0 0
  1. package com.example.a305.TurvaVali;
  2.  
  3. import android.graphics.Color;
  4. import android.location.Location;
  5. import android.support.v4.app.FragmentActivity;
  6. import android.os.Bundle;
  7. import android.util.Log;
  8. import android.widget.EditText;
  9. import android.widget.TextView;
  10.  
  11. import com.android.volley.AuthFailureError;
  12. import com.android.volley.Request;
  13. import com.android.volley.RequestQueue;
  14. import com.android.volley.Response;
  15. import com.android.volley.VolleyError;
  16. import com.android.volley.toolbox.StringRequest;
  17. import com.android.volley.toolbox.Volley;
  18. import com.google.android.gms.maps.CameraUpdateFactory;
  19. import com.google.android.gms.maps.GoogleMap;
  20. import com.google.android.gms.maps.OnMapReadyCallback;
  21. import com.google.android.gms.maps.SupportMapFragment;
  22. import com.google.android.gms.maps.model.LatLng;
  23. import com.google.android.gms.maps.model.Marker;
  24. import com.google.android.gms.maps.model.MarkerOptions;
  25. import com.google.android.gms.maps.model.Polyline;
  26. import com.google.android.gms.maps.model.PolylineOptions;
  27. import com.google.gson.Gson;
  28. import com.google.gson.GsonBuilder;
  29. import com.google.gson.reflect.TypeToken;
  30.  
  31. import org.eclipse.paho.android.service.MqttAndroidClient;
  32. import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
  33. import org.eclipse.paho.client.mqttv3.IMqttActionListener;
  34. import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
  35. import org.eclipse.paho.client.mqttv3.IMqttToken;
  36. import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
  37. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  38. import org.eclipse.paho.client.mqttv3.MqttException;
  39. import org.eclipse.paho.client.mqttv3.MqttMessage;
  40. import org.json.JSONArray;
  41. import org.json.JSONException;
  42. import org.json.JSONObject;
  43.  
  44. import java.util.ArrayList;
  45. import java.util.HashMap;
  46. import java.util.List;
  47. import java.util.Map;
  48.  
  49. public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
  50.  
  51.     private GoogleMap mMap;
  52.     private Marker markerName = null;
  53.     private static final String TAG = "MyActivity";
  54.     private LatLng rovaniemi;
  55.  
  56.     private TextView brakeDistance;
  57.     private double frictionMultiplier;
  58.     TextView mqttTextView;
  59.  
  60.     private EditText speedText;
  61.     private TextView frictionText;
  62.     private EditText distanceToText;
  63.  
  64.     private String friction;
  65.     private String distanceTo;
  66.     private String speed;
  67.  
  68.     private double speedValue;
  69.     private double frictionValue;
  70.     private double distanceToValue;
  71.  
  72.     MqttAndroidClient mqttAndroidClient;
  73.     final String serverUri = "tcp://ylowmv.messaging.internetofthings.ibmcloud.com:1883";
  74.     String clientId = "a:ylowmv:310";
  75.     final String subscriptionTopic = "iot-2/type/its-car/id/310/evt/data/fmt/json";
  76.     static final String mqttUsername = "a-ylowmv-lr1cz1ljzg";
  77.     static final String mqttPassword = "TWyCAdjkEDG&B8mfbg";
  78.  
  79.     @Override
  80.     protected void onCreate(Bundle savedInstanceState) {
  81.         super.onCreate(savedInstanceState);
  82.         setContentView(R.layout.activity_maps);
  83.         // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  84.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  85.                 .findFragmentById(R.id.map);
  86.         mapFragment.getMapAsync(this);
  87.         mqttTextView = (TextView)findViewById(R.id.mqttTextView);
  88.         clientId = clientId + System.currentTimeMillis();
  89.  
  90.         // Create the client!
  91.         mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
  92.  
  93.         // CALLBACKS, these will take care of the connection if something unexpected happen
  94.         mqttAndroidClient.setCallback(new MqttCallbackExtended() {
  95.             @Override
  96.             public void connectComplete(boolean reconnect, String serverURI) {
  97.                 if (reconnect) {
  98.                     addToHistory("Reconnected to : " + serverURI);
  99.                     // Because Clean Session is true, we need to re-subscribe
  100.                     subscribeToTopic();
  101.                 } else {
  102.                     addToHistory("Connected to: " + serverURI);
  103.                 }
  104.             }
  105.             @Override
  106.             public void connectionLost(Throwable cause) {
  107.                 addToHistory("The Connection was lost.");
  108.             }
  109.             @Override
  110.             public void messageArrived(String topic, MqttMessage message) throws Exception {
  111.                 addToHistory("Incoming message: " + new String(message.getPayload()));
  112.                 // THIS VARIABLE IS THE JSON DATA. you can use GSON to get the needed
  113.                 // data (temperature for example) out of it, and show it in a textview or something else
  114.                 try {
  115.                      mqttTextView.setText(message.toString());
  116.                      Log.d("a", "test");
  117.  
  118.                 }
  119.                 catch (Exception e) {
  120.                     Log.d("a", e.getMessage());
  121.                 }
  122.             }
  123.             @Override
  124.             public void deliveryComplete(IMqttDeliveryToken token) {}
  125.         });
  126.  
  127.         // CONNECT TO MQTT
  128.         // set up connection settings
  129.         MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
  130.         mqttConnectOptions.setAutomaticReconnect(true);
  131.         mqttConnectOptions.setCleanSession(false);
  132.         mqttConnectOptions.setUserName(mqttUsername);
  133.         mqttConnectOptions.setPassword(mqttPassword.toCharArray());
  134.  
  135.         try {
  136.             addToHistory("Connecting to " + serverUri);
  137.  
  138.             mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
  139.                 @Override
  140.                 public void onSuccess(IMqttToken asyncActionToken) {
  141.                     DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
  142.                     disconnectedBufferOptions.setBufferEnabled(true);
  143.                     disconnectedBufferOptions.setBufferSize(100);
  144.                     disconnectedBufferOptions.setPersistBuffer(false);
  145.                     disconnectedBufferOptions.setDeleteOldestMessages(false);
  146.                     mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
  147.                     subscribeToTopic();
  148.                 }
  149.                 @Override
  150.                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  151.                     addToHistory("Failed to connect to: " + serverUri);
  152.                     addToHistory(exception.getMessage());
  153.                 }
  154.             });
  155.  
  156.         } catch (MqttException ex){
  157.             ex.printStackTrace();
  158.         }
  159.         Thread t = new Thread(){
  160.             @Override
  161.             public void run(){
  162.                 try{
  163.                     while (!isInterrupted()){
  164.                         Thread.sleep(200);
  165.                         runOnUiThread(new Runnable() {
  166.                             @Override
  167.                             public void run() {
  168.                                 //Calculating braking distance from the EditText fields
  169.                                 try {
  170.                                     findViewById(R.id.ylaLayout).setBackgroundColor(Color.WHITE);
  171.                                     //EditText to String
  172.                                     friction = frictionText.getText().toString();
  173.                                     speed = speedText.getText().toString();
  174.                                     distanceTo = mqttTextView.getText().toString();
  175.  
  176.                                     //String to Double
  177.                                     speedValue = Double.parseDouble(speed);
  178.                                     frictionValue = Double.parseDouble(friction);
  179.                                     distanceToValue = Double.parseDouble(distanceTo);
  180.  
  181.                                     speedValue = speedValue/3.6; //Converting from km/h to m/s
  182.                                     double speedValueSquare = Math.pow(speedValue, 2);
  183.                                     double brakeDistanceDouble = Math.round(speedValueSquare / (2*frictionValue*9.81)); //Formula for calculating braking distance. V^2/(2*f*G)
  184.                                     String brakeDistanceString = Double.toString(brakeDistanceDouble);
  185.                                     brakeDistance.setText(brakeDistanceString);
  186.  
  187.                                     //Giving the user a warning if they are too close to the object ahead
  188.                                     if(distanceToValue < brakeDistanceDouble) {
  189.                                         //Warning for being too close to the object in front of you here
  190.                                         /*String warningToast = "You are too close to the object ahead, slow down!";
  191.                                         myToast.setText(warningToast);
  192.                                         myToast.show();
  193.                                         Toast.makeText(getApplicationContext(), warningToast, Toast.LENGTH_SHORT).show();*/
  194.                                         findViewById(R.id.ylaLayout).setBackgroundColor(Color.RED);
  195.                                         Log.d(TAG, "onMapClick: Warning given");
  196.                                     }
  197.                                 }
  198.                                 catch(Exception e) {
  199.                                     Log.d(TAG, "Exception calculating braking distance. Most probably empty String.");
  200.                                 }
  201.                             }
  202.                         });
  203.                     }
  204.                 }catch (InterruptedException e){}
  205.             }
  206.         };
  207.         t.start();
  208.     }
  209.  
  210.  
  211.     // this could do something else, like update the new data to the layout!
  212.     private void addToHistory(String mainText){
  213.         Log.d("MYERROR", mainText);
  214.     }
  215.  
  216.     // subscriber method
  217.     public void subscribeToTopic(){
  218.         try {
  219.             mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
  220.                 @Override
  221.                 public void onSuccess(IMqttToken asyncActionToken) {
  222.                     addToHistory("Subscribed!");
  223.                 }
  224.  
  225.                 @Override
  226.                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  227.                     addToHistory("Failed to subscribe");
  228.                 }
  229.             });
  230.         } catch (MqttException ex){
  231.             System.err.println("Exception whilst subscribing");
  232.             ex.printStackTrace();
  233.         }
  234.     }
  235.     /**
  236.      * Manipulates the map once available.
  237.      * This callback is triggered when the map is ready to be used.
  238.      * This is where we can add markers or lines, add listeners or move the camera. In this case,
  239.      * we just add a marker near Sydney, Australia.
  240.      * If Google Play services is not installed on the device, the user will be prompted to install
  241.      * it inside the SupportMapFragment. This method will only be triggered once the user has
  242.      * installed Google Play services and returned to the app.
  243.      */
  244.     @Override
  245.     public void onMapReady(GoogleMap googleMap) {
  246.         mMap = googleMap;
  247.         mMap.getUiSettings().setZoomControlsEnabled(true);
  248.  
  249.         rovaniemi = new LatLng(66, 25);
  250.         mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(rovaniemi, 7));
  251.         brakeDistance = findViewById(R.id.textView_brake);
  252.         speedText = findViewById(R.id.editText_speed);
  253.         frictionText = findViewById(R.id.textView_conditions);
  254.  
  255.         getRoadConditionData();
  256.  
  257.         mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
  258.             @Override
  259.             public void onMapClick(LatLng point) {
  260.                 if (null != markerName) {
  261.                     markerName.remove();
  262.                     mMap.clear();
  263.                 }
  264.                 markerName = mMap.addMarker(new MarkerOptions().position(point));
  265.                 mMap.moveCamera(CameraUpdateFactory.newLatLng(point));
  266.                 getRoadConditionData();
  267.             }
  268.         });
  269.     }
  270.     HashMap<Polyline, RoadCondition> wirmaData = new HashMap();
  271.  
  272.     public void getRoadConditionData()
  273.     {
  274.         // this is the url where we want to get our data
  275.         // Note: 10.0.2.2 is for the Android -emulator, it redirects to your computers localhost!
  276.         String JSON_URL = "http://wirma.plab.fi/cached_geojson/-1/condition/";
  277.         // Request a string response from the provided URL.
  278.         StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
  279.                 new Response.Listener<String>() {
  280.                     @Override
  281.                     public void onResponse(String response) {
  282.                         // your response when getting data. Check out the example
  283.                         // "Handling the JSON in the Volley response" for this part
  284.                         // Note: if you send data to API, this might not be needed
  285.                         ArrayList<RoadCondition> conditions = new ArrayList();
  286.                         Gson gson = new GsonBuilder().setPrettyPrinting().create();
  287.  
  288.                         try {
  289.                             // Apigility returns HAL/JSON instead of typical JSON-data. HAL/JSON adds data relation information and metadata to a given JSON data.
  290.                             // these lines dig out the actual JSON data content from the HAL/JSON response
  291.                             JSONObject jObject = new JSONObject(response);
  292.                             // in this case feedback is the name of our service
  293.                             JSONArray jArray = jObject.getJSONArray("features");
  294.                             // place the found JSON data into our ArrayList in object form
  295.                             // GSON here expects our Android project has a class called "Feedback" in it. You can create this class by using the service jsonschema2pojo
  296.                             conditions = gson.fromJson(jArray.toString(), new TypeToken<ArrayList<RoadCondition>>() {}.getType());
  297.  
  298.                         } catch (JSONException e) {
  299.                             // error in handling the JSON
  300.                             Log.d("TESTI", e.getMessage());
  301.                         }
  302.  
  303.                         for(RoadCondition rc : conditions) {
  304.                             //LatLng[] points = new LatLng[rc.getGeometry().getCoordinates().size()];
  305.                             LatLng[] points = null;
  306.                             ArrayList<LatLng> pointsList = new ArrayList();
  307.  
  308.                             int roadRadius = 1500;
  309.                             boolean isRoadCloseEnough = false;
  310.                             Double smallestDistance = null;
  311.                             RoadCondition closestRoad = null;
  312.  
  313.                             try {
  314.                                 for(List<Double> coordinates : rc.getGeometry().getCoordinates()) {
  315.                                     LatLng point = new LatLng(coordinates.get(1), coordinates.get(0));
  316.                                     if(markerName != null)
  317.                                     {
  318.                                         Location l1 = new Location("");
  319.                                         l1.setLatitude(point.latitude);
  320.                                         l1.setLongitude(point.longitude);
  321.  
  322.                                         Location l2 = new Location("");
  323.                                         l2.setLatitude(markerName.getPosition().latitude);
  324.                                         l2.setLongitude(markerName.getPosition().longitude);
  325.  
  326.                                         double distance = l1.distanceTo(l2);
  327.                                         if(smallestDistance == null)
  328.                                         {
  329.                                             smallestDistance = distance;
  330.                                         }
  331.                                         if(distance < smallestDistance)
  332.                                         {
  333.                                             smallestDistance = distance;
  334.                                             closestRoad = rc;
  335.                                         }
  336.                                         if (closestRoad != null)
  337.                                         {
  338.                                             if (smallestDistance < roadRadius)
  339.                                             {
  340.                                                 int frictionCondition = closestRoad.getProperties().getSensorvalueRange();
  341.                                                 if(frictionCondition == 0){frictionMultiplier = 0;}
  342.                                                 if(frictionCondition == 1){frictionMultiplier = 0.7;}
  343.                                                 if(frictionCondition == 2){frictionMultiplier = 0.55;}
  344.                                                 if(frictionCondition == 3){frictionMultiplier = 0.4;}
  345.                                                 if(frictionCondition == 4){frictionMultiplier = 0.35;}
  346.                                                 if(frictionCondition == 5){frictionMultiplier = 0.25;}
  347.                                                 if(frictionCondition == 6){frictionMultiplier = 0.35;}
  348.                                                 frictionText.setText(Double.toString(frictionMultiplier));
  349.                                                 Log.d(TAG, "closestRoad condition: " + frictionCondition + " closestRoad multiplier:" + frictionMultiplier);
  350.                                             }
  351.                                         }
  352.                                     }
  353.                                     pointsList.add(point);
  354.                                 }
  355.  
  356.                                 if(closestRoad != null) {
  357.                                     pointsList = new ArrayList<>();
  358.                                     for (List<Double> coordinates : closestRoad.getGeometry().getCoordinates()) {
  359.                                         LatLng point = new LatLng(coordinates.get(1), coordinates.get(0));
  360.  
  361.                                         Location l1 = new Location("");
  362.                                         l1.setLatitude(point.latitude);
  363.                                         l1.setLongitude(point.longitude);
  364.  
  365.                                         Location l2 = new Location("");
  366.                                         l2.setLatitude(markerName.getPosition().latitude);
  367.                                         l2.setLongitude(markerName.getPosition().longitude);
  368.                                         pointsList.add(point);
  369.                                     }
  370.                                 }
  371.                             }
  372.                             catch(Exception e) {
  373.                                 Log.d(TAG, e.getMessage());
  374.                             }
  375.  
  376.                             if(pointsList.size() > 0)
  377.                             {
  378.                                 points = new LatLng[pointsList.size()];
  379.                                 LatLng[] routeData = pointsList.toArray(points);
  380.                                 int[] conditionColors = {
  381.                                         Color.TRANSPARENT, // no data
  382.                                         Color.GREEN, // dry
  383.                                         Color.CYAN, // moist
  384.                                         Color.BLUE, //wet
  385.                                         Color.LTGRAY, // slush
  386.                                         Color.RED, // ice
  387.                                         Color.WHITE};// snow
  388.  
  389.                                 int selectedColor = rc.getProperties().getSensorvalueRange();
  390.                                 Polyline line = mMap.addPolyline(new PolylineOptions()
  391.                                         .add(routeData)
  392.                                         .width(10)
  393.                                         .color(conditionColors[selectedColor]));
  394.                                 wirmaData.put(line, rc);
  395.                             }
  396.  
  397.                         }
  398.                         Log.d("TESTI", response);
  399.                     }
  400.                 }, new Response.ErrorListener() {
  401.             @Override
  402.             public void onErrorResponse(VolleyError error) {
  403.                 // probably a connection error
  404.                 Log.d("TESTI", "" + error.getMessage());
  405.             }
  406.         }){
  407.             @Override
  408.             public Map<String, String> getHeaders() throws AuthFailureError {
  409.  
  410.                 // we have to specify a proper header, otherwise Apigility will block our queries!
  411.                 // define we are after JSON data!
  412.                 HashMap<String, String> headers = new HashMap<String, String>();
  413.                 headers.put("Accept", "application/json");
  414.                 headers.put("Content-Type", "application/json; charset=utf-8");
  415.                 return headers;
  416.             }
  417.         };
  418.         // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
  419.         RequestQueue requestQueue = Volley.newRequestQueue(this);
  420.         requestQueue.add(stringRequest);
  421.     }
  422. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement