Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.a305.TurvaVali;
- import android.graphics.Color;
- import android.location.Location;
- import android.support.v4.app.FragmentActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.EditText;
- import android.widget.TextView;
- import com.android.volley.AuthFailureError;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.Response;
- import com.android.volley.VolleyError;
- import com.android.volley.toolbox.StringRequest;
- import com.android.volley.toolbox.Volley;
- import com.google.android.gms.maps.CameraUpdateFactory;
- import com.google.android.gms.maps.GoogleMap;
- import com.google.android.gms.maps.OnMapReadyCallback;
- import com.google.android.gms.maps.SupportMapFragment;
- import com.google.android.gms.maps.model.LatLng;
- import com.google.android.gms.maps.model.Marker;
- import com.google.android.gms.maps.model.MarkerOptions;
- import com.google.android.gms.maps.model.Polyline;
- import com.google.android.gms.maps.model.PolylineOptions;
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import com.google.gson.reflect.TypeToken;
- import org.eclipse.paho.android.service.MqttAndroidClient;
- import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
- import org.eclipse.paho.client.mqttv3.IMqttActionListener;
- import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
- import org.eclipse.paho.client.mqttv3.IMqttToken;
- import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
- import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
- import org.eclipse.paho.client.mqttv3.MqttException;
- import org.eclipse.paho.client.mqttv3.MqttMessage;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
- private GoogleMap mMap;
- private Marker markerName = null;
- private static final String TAG = "MyActivity";
- private LatLng rovaniemi;
- private TextView brakeDistance;
- private double frictionMultiplier;
- TextView mqttTextView;
- private EditText speedText;
- private TextView frictionText;
- private EditText distanceToText;
- private String friction;
- private String distanceTo;
- private String speed;
- private double speedValue;
- private double frictionValue;
- private double distanceToValue;
- MqttAndroidClient mqttAndroidClient;
- final String serverUri = "tcp://ylowmv.messaging.internetofthings.ibmcloud.com:1883";
- String clientId = "a:ylowmv:310";
- final String subscriptionTopic = "iot-2/type/its-car/id/310/evt/data/fmt/json";
- static final String mqttUsername = "a-ylowmv-lr1cz1ljzg";
- static final String mqttPassword = "TWyCAdjkEDG&B8mfbg";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_maps);
- // Obtain the SupportMapFragment and get notified when the map is ready to be used.
- SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
- .findFragmentById(R.id.map);
- mapFragment.getMapAsync(this);
- mqttTextView = (TextView)findViewById(R.id.mqttTextView);
- clientId = clientId + System.currentTimeMillis();
- // Create the client!
- mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
- // CALLBACKS, these will take care of the connection if something unexpected happen
- mqttAndroidClient.setCallback(new MqttCallbackExtended() {
- @Override
- public void connectComplete(boolean reconnect, String serverURI) {
- if (reconnect) {
- addToHistory("Reconnected to : " + serverURI);
- // Because Clean Session is true, we need to re-subscribe
- subscribeToTopic();
- } else {
- addToHistory("Connected to: " + serverURI);
- }
- }
- @Override
- public void connectionLost(Throwable cause) {
- addToHistory("The Connection was lost.");
- }
- @Override
- public void messageArrived(String topic, MqttMessage message) throws Exception {
- addToHistory("Incoming message: " + new String(message.getPayload()));
- // THIS VARIABLE IS THE JSON DATA. you can use GSON to get the needed
- // data (temperature for example) out of it, and show it in a textview or something else
- try {
- mqttTextView.setText(message.toString());
- Log.d("a", "test");
- }
- catch (Exception e) {
- Log.d("a", e.getMessage());
- }
- }
- @Override
- public void deliveryComplete(IMqttDeliveryToken token) {}
- });
- // CONNECT TO MQTT
- // set up connection settings
- MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
- mqttConnectOptions.setAutomaticReconnect(true);
- mqttConnectOptions.setCleanSession(false);
- mqttConnectOptions.setUserName(mqttUsername);
- mqttConnectOptions.setPassword(mqttPassword.toCharArray());
- try {
- addToHistory("Connecting to " + serverUri);
- mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
- @Override
- public void onSuccess(IMqttToken asyncActionToken) {
- DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
- disconnectedBufferOptions.setBufferEnabled(true);
- disconnectedBufferOptions.setBufferSize(100);
- disconnectedBufferOptions.setPersistBuffer(false);
- disconnectedBufferOptions.setDeleteOldestMessages(false);
- mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
- subscribeToTopic();
- }
- @Override
- public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
- addToHistory("Failed to connect to: " + serverUri);
- addToHistory(exception.getMessage());
- }
- });
- } catch (MqttException ex){
- ex.printStackTrace();
- }
- Thread t = new Thread(){
- @Override
- public void run(){
- try{
- while (!isInterrupted()){
- Thread.sleep(200);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- //Calculating braking distance from the EditText fields
- try {
- findViewById(R.id.ylaLayout).setBackgroundColor(Color.WHITE);
- //EditText to String
- friction = frictionText.getText().toString();
- speed = speedText.getText().toString();
- distanceTo = mqttTextView.getText().toString();
- //String to Double
- speedValue = Double.parseDouble(speed);
- frictionValue = Double.parseDouble(friction);
- distanceToValue = Double.parseDouble(distanceTo);
- speedValue = speedValue/3.6; //Converting from km/h to m/s
- double speedValueSquare = Math.pow(speedValue, 2);
- double brakeDistanceDouble = Math.round(speedValueSquare / (2*frictionValue*9.81)); //Formula for calculating braking distance. V^2/(2*f*G)
- String brakeDistanceString = Double.toString(brakeDistanceDouble);
- brakeDistance.setText(brakeDistanceString);
- //Giving the user a warning if they are too close to the object ahead
- if(distanceToValue < brakeDistanceDouble) {
- //Warning for being too close to the object in front of you here
- /*String warningToast = "You are too close to the object ahead, slow down!";
- myToast.setText(warningToast);
- myToast.show();
- Toast.makeText(getApplicationContext(), warningToast, Toast.LENGTH_SHORT).show();*/
- findViewById(R.id.ylaLayout).setBackgroundColor(Color.RED);
- Log.d(TAG, "onMapClick: Warning given");
- }
- }
- catch(Exception e) {
- Log.d(TAG, "Exception calculating braking distance. Most probably empty String.");
- }
- }
- });
- }
- }catch (InterruptedException e){}
- }
- };
- t.start();
- }
- // this could do something else, like update the new data to the layout!
- private void addToHistory(String mainText){
- Log.d("MYERROR", mainText);
- }
- // subscriber method
- public void subscribeToTopic(){
- try {
- mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
- @Override
- public void onSuccess(IMqttToken asyncActionToken) {
- addToHistory("Subscribed!");
- }
- @Override
- public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
- addToHistory("Failed to subscribe");
- }
- });
- } catch (MqttException ex){
- System.err.println("Exception whilst subscribing");
- ex.printStackTrace();
- }
- }
- /**
- * Manipulates the map once available.
- * This callback is triggered when the map is ready to be used.
- * This is where we can add markers or lines, add listeners or move the camera. In this case,
- * we just add a marker near Sydney, Australia.
- * If Google Play services is not installed on the device, the user will be prompted to install
- * it inside the SupportMapFragment. This method will only be triggered once the user has
- * installed Google Play services and returned to the app.
- */
- @Override
- public void onMapReady(GoogleMap googleMap) {
- mMap = googleMap;
- mMap.getUiSettings().setZoomControlsEnabled(true);
- rovaniemi = new LatLng(66, 25);
- mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(rovaniemi, 7));
- brakeDistance = findViewById(R.id.textView_brake);
- speedText = findViewById(R.id.editText_speed);
- frictionText = findViewById(R.id.textView_conditions);
- getRoadConditionData();
- mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
- @Override
- public void onMapClick(LatLng point) {
- if (null != markerName) {
- markerName.remove();
- mMap.clear();
- }
- markerName = mMap.addMarker(new MarkerOptions().position(point));
- mMap.moveCamera(CameraUpdateFactory.newLatLng(point));
- getRoadConditionData();
- }
- });
- }
- HashMap<Polyline, RoadCondition> wirmaData = new HashMap();
- public void getRoadConditionData()
- {
- // this is the url where we want to get our data
- // Note: 10.0.2.2 is for the Android -emulator, it redirects to your computers localhost!
- String JSON_URL = "http://wirma.plab.fi/cached_geojson/-1/condition/";
- // Request a string response from the provided URL.
- StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
- new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- // your response when getting data. Check out the example
- // "Handling the JSON in the Volley response" for this part
- // Note: if you send data to API, this might not be needed
- ArrayList<RoadCondition> conditions = new ArrayList();
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- try {
- // Apigility returns HAL/JSON instead of typical JSON-data. HAL/JSON adds data relation information and metadata to a given JSON data.
- // these lines dig out the actual JSON data content from the HAL/JSON response
- JSONObject jObject = new JSONObject(response);
- // in this case feedback is the name of our service
- JSONArray jArray = jObject.getJSONArray("features");
- // place the found JSON data into our ArrayList in object form
- // GSON here expects our Android project has a class called "Feedback" in it. You can create this class by using the service jsonschema2pojo
- conditions = gson.fromJson(jArray.toString(), new TypeToken<ArrayList<RoadCondition>>() {}.getType());
- } catch (JSONException e) {
- // error in handling the JSON
- Log.d("TESTI", e.getMessage());
- }
- for(RoadCondition rc : conditions) {
- //LatLng[] points = new LatLng[rc.getGeometry().getCoordinates().size()];
- LatLng[] points = null;
- ArrayList<LatLng> pointsList = new ArrayList();
- int roadRadius = 1500;
- boolean isRoadCloseEnough = false;
- Double smallestDistance = null;
- RoadCondition closestRoad = null;
- try {
- for(List<Double> coordinates : rc.getGeometry().getCoordinates()) {
- LatLng point = new LatLng(coordinates.get(1), coordinates.get(0));
- if(markerName != null)
- {
- Location l1 = new Location("");
- l1.setLatitude(point.latitude);
- l1.setLongitude(point.longitude);
- Location l2 = new Location("");
- l2.setLatitude(markerName.getPosition().latitude);
- l2.setLongitude(markerName.getPosition().longitude);
- double distance = l1.distanceTo(l2);
- if(smallestDistance == null)
- {
- smallestDistance = distance;
- }
- if(distance < smallestDistance)
- {
- smallestDistance = distance;
- closestRoad = rc;
- }
- if (closestRoad != null)
- {
- if (smallestDistance < roadRadius)
- {
- int frictionCondition = closestRoad.getProperties().getSensorvalueRange();
- if(frictionCondition == 0){frictionMultiplier = 0;}
- if(frictionCondition == 1){frictionMultiplier = 0.7;}
- if(frictionCondition == 2){frictionMultiplier = 0.55;}
- if(frictionCondition == 3){frictionMultiplier = 0.4;}
- if(frictionCondition == 4){frictionMultiplier = 0.35;}
- if(frictionCondition == 5){frictionMultiplier = 0.25;}
- if(frictionCondition == 6){frictionMultiplier = 0.35;}
- frictionText.setText(Double.toString(frictionMultiplier));
- Log.d(TAG, "closestRoad condition: " + frictionCondition + " closestRoad multiplier:" + frictionMultiplier);
- }
- }
- }
- pointsList.add(point);
- }
- if(closestRoad != null) {
- pointsList = new ArrayList<>();
- for (List<Double> coordinates : closestRoad.getGeometry().getCoordinates()) {
- LatLng point = new LatLng(coordinates.get(1), coordinates.get(0));
- Location l1 = new Location("");
- l1.setLatitude(point.latitude);
- l1.setLongitude(point.longitude);
- Location l2 = new Location("");
- l2.setLatitude(markerName.getPosition().latitude);
- l2.setLongitude(markerName.getPosition().longitude);
- pointsList.add(point);
- }
- }
- }
- catch(Exception e) {
- Log.d(TAG, e.getMessage());
- }
- if(pointsList.size() > 0)
- {
- points = new LatLng[pointsList.size()];
- LatLng[] routeData = pointsList.toArray(points);
- int[] conditionColors = {
- Color.TRANSPARENT, // no data
- Color.GREEN, // dry
- Color.CYAN, // moist
- Color.BLUE, //wet
- Color.LTGRAY, // slush
- Color.RED, // ice
- Color.WHITE};// snow
- int selectedColor = rc.getProperties().getSensorvalueRange();
- Polyline line = mMap.addPolyline(new PolylineOptions()
- .add(routeData)
- .width(10)
- .color(conditionColors[selectedColor]));
- wirmaData.put(line, rc);
- }
- }
- Log.d("TESTI", response);
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- // probably a connection error
- Log.d("TESTI", "" + error.getMessage());
- }
- }){
- @Override
- public Map<String, String> getHeaders() throws AuthFailureError {
- // we have to specify a proper header, otherwise Apigility will block our queries!
- // define we are after JSON data!
- HashMap<String, String> headers = new HashMap<String, String>();
- headers.put("Accept", "application/json");
- headers.put("Content-Type", "application/json; charset=utf-8");
- return headers;
- }
- };
- // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
- RequestQueue requestQueue = Volley.newRequestQueue(this);
- requestQueue.add(stringRequest);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement