ThreatMapFragment.java 10 KB

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