ThreatMapFragment.java 11 KB

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