ThreatMapFragment.java 11 KB

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