ThreatMapFragment.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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.ui2.model.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 TrackerFragment 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 Thread mLoader = null;
  52. private static HashMap<String, String> sMarkerIDToSSID = new HashMap<String, String>();
  53. private LocationClient mLocationClient;
  54. private static final LocationRequest REQUEST = LocationRequest.create()
  55. .setExpirationDuration(5000) // 5 seconds
  56. .setInterval(5000) // 5 seconds
  57. .setFastestInterval(16) // 16ms = 60fps
  58. .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  59. /**
  60. * if google play services aren't available an error notification will be displayed
  61. *
  62. * @return true if the google play services are available
  63. */
  64. private boolean isGooglePlay() {
  65. int status = isGooglePlayServicesAvailable(getActivity());
  66. boolean result = status == ConnectionResult.SUCCESS;
  67. if (!result) {
  68. getErrorDialog(status, getActivity(), 10).show();
  69. }
  70. return result;
  71. }
  72. /**
  73. * callback for when the info window of a marker gets clicked
  74. * open the RecordOverviewFragment and display all records belonging to an SSID
  75. *
  76. * @param marker this info window belongs to
  77. */
  78. @Override
  79. public void onInfoWindowClick(Marker marker) {
  80. //MainActivity.getInstance().displayView(MainActivity.MainMenuItem.RECORDS.getValue());
  81. //RecordOverviewFragment recordOverviewFragment = (RecordOverviewFragment)MainActivity.getInstance().getCurrentFragment();
  82. //if (recordOverviewFragment != null) {
  83. String ssid = sMarkerIDToSSID.get(marker.getId());
  84. ArrayList<String> ssids = new ArrayList<String>();
  85. ssids.add(ssid);
  86. LogFilter filter = new LogFilter();
  87. filter.setESSIDs(ssids);
  88. RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
  89. recordOverviewFragment.setFilter(filter);
  90. recordOverviewFragment.setGroupKey("ESSID");
  91. recordOverviewFragment.setAllowBack(true);
  92. MainActivity.getInstance().injectFragment(recordOverviewFragment);
  93. //recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
  94. //}
  95. }
  96. /**
  97. * callbacks from LocationClient
  98. */
  99. @Override
  100. public void onConnected(Bundle bundle) {
  101. mLocationClient.requestLocationUpdates(REQUEST, this);
  102. }
  103. @Override
  104. public void onDisconnected() {
  105. }
  106. @Override
  107. public void onConnectionFailed(ConnectionResult connectionResult) {
  108. }
  109. @Override
  110. public void onLocationChanged(Location location) {
  111. sMap.animateCamera(CameraUpdateFactory.newLatLng(
  112. new LatLng(location.getLatitude(), location.getLongitude())));
  113. }
  114. /**
  115. * helper class
  116. * easier to use than LatLng
  117. */
  118. private class Point {
  119. public double x, y;
  120. public Point(double sx, double sy) {
  121. x = sx;
  122. y = sy;
  123. }
  124. }
  125. /**
  126. * helper class
  127. * contains heuristic to split SSIDs by location
  128. * see MAX_DISTANCE
  129. */
  130. private class SSIDArea {
  131. private Point mMinimum, mMaximum;
  132. public int numPoints;
  133. public static final int MAX_NUM_ATTACKS = 20;
  134. public static final float MAX_DISTANCE = 1000.0f; // 1km
  135. public SSIDArea(LatLng initialLocation) {
  136. //mMinimum = new Point(360.0, 360.0);
  137. //mMaximum = new Point(-360.0, -360.0);
  138. mMinimum = new Point(initialLocation.latitude, initialLocation.longitude);
  139. mMaximum = new Point(initialLocation.latitude, initialLocation.longitude);
  140. numPoints = 1;
  141. }
  142. public boolean doesLocationBelongToArea(LatLng location) {
  143. LatLng center = calculateCenterLocation();
  144. float[] result = new float[1];
  145. Location.distanceBetween(center.latitude, center.longitude, location.latitude,
  146. location.longitude, result);
  147. return result[0] < MAX_DISTANCE;
  148. }
  149. public void addLocation(LatLng location) {
  150. Point point = new Point(location.latitude, location.longitude);
  151. if (point.x < mMinimum.x) {
  152. mMinimum.x = point.x;
  153. }
  154. if (point.x > mMaximum.x) {
  155. mMaximum.x = point.x;
  156. }
  157. if (point.y < mMinimum.y) {
  158. mMinimum.y = point.y;
  159. }
  160. if (point.y > mMaximum.y) {
  161. mMaximum.y = point.y;
  162. }
  163. numPoints++;
  164. }
  165. public LatLng calculateCenterLocation() {
  166. return new LatLng(0.5 * (mMinimum.x + mMaximum.x), 0.5 * (mMinimum.y + mMaximum.y));
  167. }
  168. public float calculateRadius() {
  169. float[] result = new float[1];
  170. Location.distanceBetween(mMinimum.x, mMinimum.y, mMaximum.x, mMaximum.y, result);
  171. return 0.5f * result[0];
  172. }
  173. public int calculateColor() {
  174. int threatLevel = numPoints;
  175. if (threatLevel > MAX_NUM_ATTACKS) {
  176. threatLevel = MAX_NUM_ATTACKS;
  177. }
  178. float alpha = 1.0f - (float) (threatLevel - 1) / (float) (MAX_NUM_ATTACKS - 1);
  179. return Color.argb(127, (int) (240.0 + 15.0 * alpha), (int) (80.0 + 175.0 * alpha), 60);
  180. }
  181. }
  182. /**
  183. * fills the map with markers and circle representing SSIDs
  184. * does it asynchronously in background thread
  185. */
  186. private void populateMap() {
  187. if (mLoader != null) {
  188. mLoader.interrupt();
  189. }
  190. mLoader = new Thread(new Runnable() {
  191. private void updateUI(final HashMap<String, ArrayList<SSIDArea>> threatAreas) {
  192. if (mLoader.isInterrupted()) {
  193. return;
  194. }
  195. Activity activity = getActivity();
  196. if (activity != null) {
  197. activity.runOnUiThread(new Runnable() {
  198. @Override
  199. public void run() {
  200. sMap.clear();
  201. CircleOptions circleOptions = new CircleOptions().radius(200.0)
  202. .fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
  203. BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
  204. .fromResource(R.drawable.wifi_marker);
  205. for (Map.Entry<String, ArrayList<SSIDArea>> entry : threatAreas.entrySet()) {
  206. String ssid = entry.getKey();
  207. ArrayList<SSIDArea> areas = entry.getValue();
  208. for (SSIDArea area : areas) {
  209. int color = area.calculateColor();
  210. LatLng center = area.calculateCenterLocation();
  211. float radius = area.calculateRadius();
  212. sMap.addCircle(circleOptions.center(center).radius(100.0 + radius)
  213. .fillColor(color));
  214. Marker marker = sMap.addMarker(new MarkerOptions()
  215. .title(ssid + ": " + area.numPoints + (area.numPoints == 1
  216. ? getResources()
  217. .getString(R.string.attack)
  218. : getResources().getString(R.string.attacks))).position(
  219. center));
  220. marker.setIcon(bitmapDescriptor);
  221. sMarkerIDToSSID.put(marker.getId(), ssid);
  222. }
  223. }
  224. }
  225. });
  226. }
  227. }
  228. private HashMap<String, ArrayList<SSIDArea>> doInBackground() {
  229. HostageDBOpenHelper dbh = new HostageDBOpenHelper(getActivity());
  230. ArrayList<Record> records = dbh.getRecordsForFilter(new LogFilter());
  231. HashMap<String, ArrayList<SSIDArea>> threatAreas
  232. = new HashMap<String, ArrayList<SSIDArea>>();
  233. for (Record record : records) {
  234. LatLng location = new LatLng(record.getLatitude(), record.getLongitude());
  235. //Log.i("location", "lat: " + location.latitude + " long: " + location.longitude);
  236. ArrayList<SSIDArea> areas;
  237. if (threatAreas.containsKey(record.getSsid())) {
  238. areas = threatAreas.get(record.getSsid());
  239. boolean foundArea = false;
  240. for (SSIDArea area : areas) {
  241. if (area.doesLocationBelongToArea(location)) {
  242. area.addLocation(location);
  243. foundArea = true;
  244. break;
  245. }
  246. }
  247. if (!foundArea) {
  248. areas.add(new SSIDArea(location));
  249. }
  250. } else {
  251. areas = new ArrayList<SSIDArea>();
  252. areas.add(new SSIDArea(location));
  253. threatAreas.put(record.getSsid(), areas);
  254. }
  255. }
  256. return threatAreas;
  257. }
  258. @Override
  259. public void run() {
  260. updateUI(doInBackground());
  261. }
  262. });
  263. mLoader.start(); // run!
  264. }
  265. /**
  266. * performs initialization
  267. * checks if google play services are supported
  268. * view must be removed if this object has been created once before
  269. * that is why view is static
  270. *
  271. * @param inflater the inflater
  272. * @param container the container
  273. * @param savedInstanceState the savedInstanceState
  274. * @return the view
  275. */
  276. @Override
  277. public View onCreateView(final LayoutInflater inflater, ViewGroup container,
  278. Bundle savedInstanceState) {
  279. super.onCreateView(inflater, container, savedInstanceState);
  280. final Activity activity = getActivity();
  281. if (activity != null) {
  282. activity.setTitle(getResources().getString(R.string.drawer_threat_map));
  283. }
  284. if (sView != null) {
  285. ViewGroup parent = (ViewGroup) sView.getParent();
  286. if (parent != null) {
  287. parent.removeView(sView);
  288. }
  289. }
  290. try {
  291. sView = inflater.inflate(R.layout.fragment_threatmap, container, false);
  292. if (isGooglePlay()) {
  293. final FragmentManager fragmentManager = getFragmentManager();
  294. if (fragmentManager != null) {
  295. final MapFragment mapFragment = (MapFragment) getFragmentManager()
  296. .findFragmentById(R.id.threatmapfragment);
  297. if (mapFragment != null) {
  298. sMap = mapFragment.getMap();
  299. }
  300. }
  301. }
  302. } catch (InflateException e) {
  303. // map already exists
  304. //e.printStackTrace();
  305. }
  306. if (sMap != null) {
  307. sMap.setOnInfoWindowClickListener(this);
  308. // custom info window layout
  309. sMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
  310. @Override
  311. public View getInfoWindow(Marker marker) {
  312. return null;
  313. }
  314. @Override
  315. public View getInfoContents(Marker marker) {
  316. View view = inflater.inflate(R.layout.fragment_threatmap_infowindow, null);
  317. if (view != null) {
  318. TextView titleTextView = (TextView) view
  319. .findViewById(R.id.threatmap_infowindow_title);
  320. if (titleTextView != null) {
  321. titleTextView.setText(marker.getTitle());
  322. }
  323. }
  324. return view;
  325. }
  326. });
  327. sMap.setMyLocationEnabled(true);
  328. LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
  329. sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
  330. populateMap();
  331. }
  332. // tell the user to enable wifi so map data can be streamed
  333. if (activity != null && !HelperUtils.isNetworkAvailable(activity)) {
  334. new AlertDialog.Builder(activity)
  335. .setTitle(R.string.information)
  336. .setMessage(R.string.no_network_connection_threatmap_msg)
  337. .setPositiveButton(android.R.string.ok,
  338. new DialogInterface.OnClickListener() {
  339. public void onClick(DialogInterface dialog,
  340. int which) {
  341. }
  342. }
  343. )
  344. .setIcon(android.R.drawable.ic_dialog_info).show();
  345. }
  346. return sView;
  347. }
  348. @Override
  349. public void onResume() {
  350. super.onResume();
  351. if (mLocationClient == null) {
  352. mLocationClient = new LocationClient(MainActivity.getInstance().getApplicationContext(),
  353. this, this);
  354. }
  355. mLocationClient.connect();
  356. }
  357. @Override
  358. public void onPause() {
  359. super.onPause();
  360. if (mLocationClient != null) {
  361. mLocationClient.disconnect();
  362. }
  363. }
  364. }