ThreatMapFragment.java 12 KB

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