ThreatMapFragment.java 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package de.tudarmstadt.informatik.hostage.ui2.fragment;
  2. import android.app.Activity;
  3. import android.app.Fragment;
  4. import android.app.FragmentManager;
  5. import android.graphics.Color;
  6. import android.location.Location;
  7. import android.os.Bundle;
  8. import android.view.InflateException;
  9. import android.view.LayoutInflater;
  10. import android.view.View;
  11. import android.view.ViewGroup;
  12. import com.google.android.gms.common.ConnectionResult;
  13. import com.google.android.gms.common.GooglePlayServicesClient;
  14. import com.google.android.gms.location.LocationClient;
  15. import com.google.android.gms.location.LocationListener;
  16. import com.google.android.gms.location.LocationRequest;
  17. import com.google.android.gms.maps.CameraUpdateFactory;
  18. import com.google.android.gms.maps.GoogleMap;
  19. import com.google.android.gms.maps.MapFragment;
  20. import com.google.android.gms.maps.model.CircleOptions;
  21. import com.google.android.gms.maps.model.LatLng;
  22. import com.google.android.gms.maps.model.Marker;
  23. import com.google.android.gms.maps.model.MarkerOptions;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.Map;
  27. import de.tudarmstadt.informatik.hostage.R;
  28. import de.tudarmstadt.informatik.hostage.logging.Record;
  29. import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
  30. import de.tudarmstadt.informatik.hostage.ui.LogFilter;
  31. import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  32. import static com.google.android.gms.common.GooglePlayServicesUtil.*;
  33. /**
  34. * ThreatMapFragment
  35. *
  36. * Created by Fabio Arnold on 10.02.14.
  37. */
  38. public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindowClickListener,
  39. GooglePlayServicesClient.ConnectionCallbacks,
  40. GooglePlayServicesClient.OnConnectionFailedListener,
  41. LocationListener {
  42. private static GoogleMap sMap = null;
  43. private static View sView = null;
  44. private static HashMap<String, String> sMarkerIDToSSID = new HashMap<String, String>();
  45. private LocationClient mLocationClient;
  46. private static final LocationRequest REQUEST = LocationRequest.create()
  47. .setExpirationDuration(5000) // 5 seconds
  48. .setInterval(5000) // 5 seconds
  49. .setFastestInterval(16) // 16ms = 60fps
  50. .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  51. /**
  52. * if google play services aren't available an error notification will be displayed
  53. *
  54. * @return true if the google play services are available
  55. */
  56. private boolean isGooglePlay() {
  57. int status = isGooglePlayServicesAvailable(getActivity());
  58. boolean result = status == ConnectionResult.SUCCESS;
  59. if (!result) {
  60. getErrorDialog(status, getActivity(), 10).show();
  61. }
  62. return result;
  63. }
  64. /**
  65. * callback for when the info window of a marker gets clicked
  66. * open the RecordOverviewFragment and display all records belonging to an SSID
  67. *
  68. * @param marker this info window belongs to
  69. */
  70. @Override
  71. public void onInfoWindowClick(Marker marker) {
  72. //MainActivity.getInstance().displayView(MainActivity.MainMenuItem.RECORDS.getValue());
  73. //RecordOverviewFragment recordOverviewFragment = (RecordOverviewFragment)MainActivity.getInstance().getCurrentFragment();
  74. //if (recordOverviewFragment != null) {
  75. String ssid = sMarkerIDToSSID.get(marker.getId());
  76. ArrayList<String> ssids = new ArrayList<String>();
  77. ssids.add(ssid);
  78. LogFilter filter = new LogFilter();
  79. filter.setESSIDs(ssids);
  80. RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
  81. recordOverviewFragment.setFilter(filter);
  82. recordOverviewFragment.setGroupKey("ESSID");
  83. MainActivity.getInstance().injectFragment(recordOverviewFragment, false);
  84. //recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
  85. //}
  86. }
  87. /**
  88. * callbacks from LocationClient
  89. */
  90. @Override
  91. public void onConnected(Bundle bundle) {
  92. mLocationClient.requestLocationUpdates(REQUEST, this);
  93. }
  94. @Override
  95. public void onDisconnected() {
  96. }
  97. @Override
  98. public void onConnectionFailed(ConnectionResult connectionResult) {
  99. }
  100. @Override
  101. public void onLocationChanged(Location location) {
  102. sMap.animateCamera(CameraUpdateFactory.newLatLng(
  103. new LatLng(location.getLatitude(), location.getLongitude())));
  104. }
  105. /**
  106. * helper class
  107. * easier to use than LatLng
  108. */
  109. private class Point {
  110. public double x, y;
  111. public Point(double sx, double sy) {
  112. x = sx;
  113. y = sy;
  114. }
  115. }
  116. /**
  117. * helper class
  118. * contains heuristic to split SSIDs by location
  119. * see MAX_DISTANCE
  120. */
  121. private class SSIDArea {
  122. private Point mMinimum, mMaximum;
  123. public int numPoints;
  124. public static final int MAX_NUM_ATTACKS = 20;
  125. public static final float MAX_DISTANCE = 1000.0f; // 1km
  126. public SSIDArea(LatLng initialLocation) {
  127. //mMinimum = new Point(360.0, 360.0);
  128. //mMaximum = new Point(-360.0, -360.0);
  129. mMinimum = new Point(initialLocation.latitude, initialLocation.longitude);
  130. mMaximum = new Point(initialLocation.latitude, initialLocation.longitude);
  131. numPoints = 1;
  132. }
  133. public boolean doesLocationBelongToArea(LatLng location) {
  134. LatLng center = calculateCenterLocation();
  135. float[] result = new float[1];
  136. Location.distanceBetween(center.latitude, center.longitude, location.latitude, location.longitude, result);
  137. return result[0] < MAX_DISTANCE;
  138. }
  139. public void addLocation(LatLng location) {
  140. Point point = new Point(location.latitude, location.longitude);
  141. if (point.x < mMinimum.x) mMinimum.x = point.x;
  142. if (point.x > mMaximum.x) mMaximum.x = point.x;
  143. if (point.y < mMinimum.y) mMinimum.y = point.y;
  144. if (point.y > mMaximum.y) mMaximum.y = point.y;
  145. numPoints++;
  146. }
  147. public LatLng calculateCenterLocation() {
  148. return new LatLng(0.5 * (mMinimum.x + mMaximum.x), 0.5 * (mMinimum.y + mMaximum.y));
  149. }
  150. public float calculateRadius() {
  151. float[] result = new float[1];
  152. Location.distanceBetween(mMinimum.x, mMinimum.y, mMaximum.x, mMaximum.y, result);
  153. return 0.5f * result[0];
  154. }
  155. public int calculateColor() {
  156. int threatLevel = numPoints;
  157. if (threatLevel > MAX_NUM_ATTACKS) threatLevel = MAX_NUM_ATTACKS;
  158. float alpha = 1.0f - (float)(threatLevel-1) / (float)(MAX_NUM_ATTACKS-1);
  159. return Color.argb(127, (int) (240.0 + 15.0 * alpha), (int) (80.0 + 175.0 * alpha), 60);
  160. }
  161. }
  162. /**
  163. * fills the map with markers and circle representing SSIDs
  164. */
  165. private void populateMap() {
  166. UglyDbHelper dbh = new UglyDbHelper(getActivity());
  167. ArrayList<Record> records = dbh.getAllRecords();
  168. HashMap<String, ArrayList<SSIDArea>> threadAreas = new HashMap<String, ArrayList<SSIDArea>>();
  169. for (Record record : records) {
  170. LatLng location = new LatLng(record.getLatitude(), record.getLongitude());
  171. ArrayList<SSIDArea> areas;
  172. if (threadAreas.containsKey(record.getSsid())) {
  173. areas = threadAreas.get(record.getSsid());
  174. boolean foundArea = false;
  175. for (SSIDArea area : areas) {
  176. if (area.doesLocationBelongToArea(location)) {
  177. area.addLocation(location);
  178. foundArea = true;
  179. break;
  180. }
  181. }
  182. if (!foundArea) {
  183. areas.add(new SSIDArea(location));
  184. }
  185. } else {
  186. areas = new ArrayList<SSIDArea>();
  187. areas.add(new SSIDArea(location));
  188. threadAreas.put(record.getSsid(), areas);
  189. }
  190. }
  191. CircleOptions circleOptions = new CircleOptions().radius(200.0).fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
  192. for (Map.Entry<String, ArrayList<SSIDArea>> entry : threadAreas.entrySet()) {
  193. String ssid = entry.getKey();
  194. ArrayList<SSIDArea> areas = entry.getValue();
  195. for (SSIDArea area : areas) {
  196. int color = area.calculateColor();
  197. LatLng center = area.calculateCenterLocation();
  198. float radius = area.calculateRadius();
  199. sMap.addCircle(circleOptions.center(center).radius(100.0 + radius).fillColor(color));
  200. Marker marker = sMap.addMarker(new MarkerOptions()
  201. .title(ssid + ": " + area.numPoints + (area.numPoints == 1 ? getResources().getString(R.string.attack)
  202. : getResources().getString(R.string.attacks))).position(
  203. center));
  204. sMarkerIDToSSID.put(marker.getId(), ssid);
  205. }
  206. }
  207. sMap.setMyLocationEnabled(true);
  208. LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
  209. sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
  210. }
  211. /**
  212. * performs initialization
  213. * checks if google play services are supported
  214. * view must be removed if this object has been created once before
  215. * that is why view is static
  216. *
  217. * @param inflater the inflater
  218. * @param container the container
  219. * @param savedInstanceState the savedInstanceState
  220. * @return the view
  221. */
  222. @Override
  223. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  224. Bundle savedInstanceState) {
  225. super.onCreateView(inflater, container, savedInstanceState);
  226. final Activity activity = getActivity();
  227. if (activity != null) {
  228. activity.setTitle(getResources().getString(R.string.drawer_threat_map));
  229. }
  230. if (sView != null) {
  231. ViewGroup parent = (ViewGroup) sView.getParent();
  232. if (parent != null)
  233. parent.removeView(sView);
  234. }
  235. try {
  236. sView = inflater.inflate(R.layout.fragment_threatmap, container, false);
  237. if (isGooglePlay()) {
  238. final FragmentManager fragmentManager = getFragmentManager();
  239. if (fragmentManager != null) {
  240. final MapFragment mapFragment = (MapFragment) getFragmentManager()
  241. .findFragmentById(R.id.threatmapfragment);
  242. if (mapFragment != null) {
  243. sMap = mapFragment.getMap();
  244. populateMap();
  245. }
  246. }
  247. }
  248. } catch (InflateException e) {
  249. // map already exists
  250. //e.printStackTrace();
  251. }
  252. if (sMap != null) {
  253. sMap.setOnInfoWindowClickListener(this);
  254. }
  255. return sView;
  256. }
  257. @Override
  258. public void onResume() {
  259. super.onResume();
  260. if (mLocationClient == null) {
  261. mLocationClient = new LocationClient(MainActivity.getInstance().getApplicationContext(), this, this);
  262. }
  263. mLocationClient.connect();
  264. }
  265. @Override
  266. public void onPause() {
  267. super.onPause();
  268. if (mLocationClient != null) {
  269. mLocationClient.disconnect();
  270. }
  271. }
  272. }