P2PSyncActivity.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package de.tudarmstadt.informatik.hostage.sync.p2p;
  2. import android.app.Activity;
  3. import android.app.ProgressDialog;
  4. import android.content.BroadcastReceiver;
  5. import android.content.Context;
  6. import android.content.IntentFilter;
  7. import android.net.wifi.p2p.WifiP2pConfig;
  8. import android.net.wifi.p2p.WifiP2pDevice;
  9. import android.net.wifi.p2p.WifiP2pDeviceList;
  10. import android.net.wifi.p2p.WifiP2pGroup;
  11. import android.net.wifi.p2p.WifiP2pInfo;
  12. import android.net.wifi.p2p.WifiP2pManager;
  13. import android.os.AsyncTask;
  14. import android.os.Bundle;
  15. import android.util.Log;
  16. import android.view.LayoutInflater;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.widget.AdapterView;
  20. import android.widget.ArrayAdapter;
  21. import android.widget.ListView;
  22. import android.widget.RelativeLayout;
  23. import android.widget.TextView;
  24. import android.widget.Toast;
  25. import android.widget.ViewAnimator;
  26. import java.io.IOException;
  27. import java.io.InputStream;
  28. import java.io.InputStreamReader;
  29. import java.io.ObjectInputStream;
  30. import java.io.ObjectOutputStream;
  31. import java.io.OutputStream;
  32. import java.io.Reader;
  33. import java.io.UnsupportedEncodingException;
  34. import java.lang.reflect.InvocationTargetException;
  35. import java.lang.reflect.Method;
  36. import java.net.InetSocketAddress;
  37. import java.net.ServerSocket;
  38. import java.net.Socket;
  39. import java.util.ArrayList;
  40. import java.util.List;
  41. import de.tudarmstadt.informatik.hostage.R;
  42. import de.tudarmstadt.informatik.hostage.logging.Record;
  43. import de.tudarmstadt.informatik.hostage.logging.SyncData;
  44. import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
  45. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  46. import de.tudarmstadt.informatik.hostage.sync.Synchronizer;
  47. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  48. public class P2PSyncActivity extends Activity implements WifiP2pManager.GroupInfoListener, WifiP2pManager.PeerListListener, WifiP2pManager.ChannelListener, AdapterView.OnItemClickListener, WifiP2pManager.ConnectionInfoListener {
  49. private WifiP2pManager mManager;
  50. private WifiP2pManager.Channel mChannel;
  51. private BroadcastReceiver mReceiver;
  52. private IntentFilter mIntentFilter;
  53. private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
  54. private TextView mTxtP2PDeviceName;
  55. private TextView mTxtP2PDeviceStatus;
  56. private ViewAnimator mViewAnimator;
  57. private RelativeLayout mDevicesContainer;
  58. private TextView mTxtP2PSearchProgress;
  59. private ListView mLstP2PDevices;
  60. private RelativeLayout mWelcomeContainer;
  61. private TextView mTxtP2PNotAvailable;
  62. private TextView mTxtP2PChangeDeviceName;
  63. private WifiP2pDevice mDevice;
  64. private WifiP2pDevice mOtherDevice;
  65. private WifiP2pInfo mInfo;
  66. private final int OWNER_SERVER_PORT = 8988;
  67. private final int CLIENT_SERVER_PORT = 8989;
  68. private ClientAsyncTask clientAsync;
  69. private ServerAsyncTask serverAsync;
  70. private HostageDBOpenHelper mDbHelper;
  71. private Synchronizer synchronizer;
  72. private void extractFromView(){
  73. mTxtP2PDeviceName = (TextView) findViewById(R.id.txt_p2p_device_name);
  74. mTxtP2PDeviceStatus = (TextView) findViewById(R.id.txt_p2p_device_status);
  75. mTxtP2PChangeDeviceName = (TextView) findViewById(R.id.txtP2PChangeDeviceName);
  76. //mTxtP2PHeader = (TextView) findViewById(R.id.txtP2PHeader);
  77. //mTxtP2PSubHeader = (TextView) findViewById(R.id.txtP2PSubheader);
  78. //mTxtP2PHelpBack = (TextView) findViewById(R.id.txtP2PHelpBack);
  79. mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
  80. mDevicesContainer = (RelativeLayout) findViewById(R.id.devicesContainer);
  81. mWelcomeContainer = (RelativeLayout) findViewById(R.id.welcomeContainer);
  82. mTxtP2PSearchProgress = (TextView) findViewById(R.id.txtP2PSearchProgress);
  83. mLstP2PDevices = (ListView) findViewById(R.id.lstP2PDevices);
  84. //mBtnP2PSearch = (Button) findViewById(R.id.btnP2PSearch);
  85. mTxtP2PNotAvailable = (TextView) findViewById(R.id.txtP2PNotAvailable);
  86. }
  87. public void discoverPeers(){
  88. mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
  89. @Override
  90. public void onSuccess() {
  91. mViewAnimator.showNext();
  92. mTxtP2PSearchProgress.setVisibility(View.VISIBLE);
  93. setWifiDirectAvailable();
  94. }
  95. @Override
  96. public void onFailure(int reason) {
  97. if(reason == WifiP2pManager.P2P_UNSUPPORTED) {
  98. setWifiDirectNotAvailable();
  99. }
  100. }
  101. });
  102. }
  103. public void setWifiDirectNotAvailable(){
  104. //mBtnP2PSearch.setVisibility(View.GONE);
  105. mTxtP2PNotAvailable.setVisibility(View.VISIBLE);
  106. peers.clear();
  107. ((WiFiPeerListAdapter) mLstP2PDevices.getAdapter()).notifyDataSetChanged();
  108. mDevice = null;
  109. }
  110. public void setWifiDirectAvailable(){
  111. //mBtnP2PSearch.setVisibility(View.VISIBLE);
  112. mTxtP2PNotAvailable.setVisibility(View.GONE);
  113. }
  114. public void closeConnection(){
  115. if(this.serverAsync != null && !this.serverAsync.isCancelled()){
  116. this.serverAsync.cancel(true);
  117. }
  118. if(this.clientAsync != null && !this.clientAsync.isCancelled()){
  119. this.clientAsync.cancel(true);
  120. }
  121. }
  122. public void registerListeners(){
  123. mTxtP2PChangeDeviceName.setOnClickListener(new View.OnClickListener() {
  124. @Override
  125. public void onClick(View v) {
  126. Method method1 = null;
  127. try {
  128. method1 = mManager.getClass().getDeclaredMethod("setDeviceName", WifiP2pManager.Channel.class);
  129. method1.invoke(mManager, mChannel, "Android_fc546");
  130. } catch (NoSuchMethodException e) {
  131. e.printStackTrace();
  132. } catch (InvocationTargetException e) {
  133. e.printStackTrace();
  134. } catch (IllegalAccessException e) {
  135. e.printStackTrace();
  136. }
  137. }
  138. });
  139. }
  140. @Override
  141. protected void onCreate(Bundle savedInstanceState) {
  142. super.onCreate(savedInstanceState);
  143. mDbHelper = new HostageDBOpenHelper(getApplicationContext());
  144. synchronizer = new Synchronizer(mDbHelper);
  145. setContentView(R.layout.activity_p2_psync);
  146. assert getActionBar() != null;
  147. getActionBar().setTitle("WifiDirect Synchronization");
  148. this.extractFromView();
  149. this.registerListeners();
  150. this.mLstP2PDevices.setAdapter(new WiFiPeerListAdapter(this, R.layout.row_devices, peers));
  151. this.mLstP2PDevices.setOnItemClickListener(this);
  152. mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
  153. mChannel = mManager.initialize(this, getMainLooper(), new WifiP2pManager.ChannelListener() {
  154. @Override
  155. public void onChannelDisconnected() {
  156. System.out.println("---------------------> CHannel disconnect!!!");
  157. }
  158. });
  159. mIntentFilter = new IntentFilter();
  160. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
  161. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
  162. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
  163. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
  164. this.discoverPeers();
  165. }
  166. @Override
  167. protected void onResume() {
  168. super.onResume();
  169. mReceiver = new P2PBroadcastReceiver(mManager, mChannel, this);
  170. registerReceiver(mReceiver, mIntentFilter);
  171. }
  172. @Override
  173. protected void onPause() {
  174. super.onPause();
  175. unregisterReceiver(mReceiver);
  176. }
  177. @Override
  178. public void onPeersAvailable(WifiP2pDeviceList peerList){
  179. mTxtP2PSearchProgress.setVisibility(View.GONE);
  180. peers.clear();
  181. peers.addAll(peerList.getDeviceList());
  182. ((WiFiPeerListAdapter) mLstP2PDevices.getAdapter()).notifyDataSetChanged();
  183. if (peers.size() == 0) {
  184. return;
  185. }
  186. }
  187. private WifiP2pDevice getConnectedPeer(){
  188. for(WifiP2pDevice device: peers){
  189. if(device.status == WifiP2pDevice.CONNECTED){
  190. return device;
  191. }
  192. }
  193. return null;
  194. }
  195. private static String getDeviceStatus(int deviceStatus) {
  196. switch (deviceStatus) {
  197. case WifiP2pDevice.AVAILABLE:
  198. return "Available";
  199. case WifiP2pDevice.INVITED:
  200. return "Invited";
  201. case WifiP2pDevice.CONNECTED:
  202. return "Connected";
  203. case WifiP2pDevice.FAILED:
  204. return "Failed";
  205. case WifiP2pDevice.UNAVAILABLE:
  206. return "Unavailable";
  207. default:
  208. return "Unknown";
  209. }
  210. }
  211. public void updateThisDevice(WifiP2pDevice device) {
  212. this.mDevice = device;
  213. mTxtP2PDeviceName.setText(device.deviceName);
  214. mTxtP2PDeviceStatus.setText(getDeviceStatus(device.status));
  215. }
  216. @Override
  217. public void onChannelDisconnected() {
  218. closeConnection();
  219. }
  220. @Override
  221. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  222. final WifiP2pDevice device = (WifiP2pDevice) this.mLstP2PDevices.getAdapter().getItem(position);
  223. WifiP2pConfig config = new WifiP2pConfig();
  224. config.deviceAddress = device.deviceAddress;
  225. mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
  226. @Override
  227. public void onSuccess() {
  228. mOtherDevice = device;
  229. }
  230. @Override
  231. public void onFailure(int reason) {
  232. //mOtherDevice = null;
  233. Toast.makeText(P2PSyncActivity.this, "Could not connect to device. Retry.", Toast.LENGTH_LONG).show();
  234. }
  235. });
  236. }
  237. @Override
  238. public void onConnectionInfoAvailable(WifiP2pInfo info) {
  239. mInfo = info;
  240. //if(mOtherDevice == null) return;
  241. if(info.groupFormed && info.isGroupOwner){
  242. Log.i("server", "I am the group owner!");
  243. WifiP2pDevice connectedPeer = getConnectedPeer();
  244. if(connectedPeer != null && mInfo != null){
  245. Log.i("peers", mInfo.groupFormed + " - " + mInfo.isGroupOwner);
  246. Log.i("server", "Starting async server!");
  247. serverAsync = new ServerAsyncTask(this, OWNER_SERVER_PORT, synchronizer);
  248. serverAsync.execute();
  249. }
  250. //new ClientAsyncTask(this, mOtherDevice.deviceAddress, CLIENT_SERVER_PORT).execute();
  251. } else if(info.groupFormed){
  252. //new ServerAsyncTask(this, CLIENT_SERVER_PORT).execute();
  253. Log.i("client", "Starting async client!");
  254. clientAsync = new ClientAsyncTask(this, mInfo.groupOwnerAddress.getHostAddress(), OWNER_SERVER_PORT, synchronizer);
  255. clientAsync.execute();
  256. }
  257. }
  258. public void sendDatabase(boolean isOwner){
  259. }
  260. @Override
  261. public void onGroupInfoAvailable(WifiP2pGroup group) {
  262. }
  263. /**
  264. * Array adapter for ListFragment that maintains WifiP2pDevice list.
  265. */
  266. private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {
  267. private List<WifiP2pDevice> items;
  268. /**
  269. * @param context
  270. * @param textViewResourceId
  271. * @param objects
  272. */
  273. public WiFiPeerListAdapter(Context context, int textViewResourceId,
  274. List<WifiP2pDevice> objects) {
  275. super(context, textViewResourceId, objects);
  276. items = objects;
  277. }
  278. @Override
  279. public View getView(int position, View convertView, ViewGroup parent) {
  280. View v = convertView;
  281. if (v == null) {
  282. LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  283. v = vi.inflate(R.layout.row_devices, null);
  284. }
  285. WifiP2pDevice device = items.get(position);
  286. if (device != null) {
  287. TextView top = (TextView) v.findViewById(R.id.device_name);
  288. TextView bottom = (TextView) v.findViewById(R.id.device_details);
  289. if (top != null) {
  290. top.setText(device.deviceName);
  291. }
  292. if (bottom != null) {
  293. bottom.setText(getDeviceStatus(device.status));
  294. }
  295. }
  296. return v;
  297. }
  298. }
  299. public static class ServerAsyncTask extends AsyncTask<String, Integer, Integer> {
  300. private Activity context;
  301. private int port;
  302. private final ProgressDialog progressDialog;
  303. private final Synchronizer synchronizer;
  304. /**
  305. * @param context
  306. */
  307. public ServerAsyncTask(Activity context, int port, Synchronizer synchronizer) {
  308. this.context = context;
  309. this.port = port;
  310. this.progressDialog = new ProgressDialog(context);
  311. this.synchronizer = synchronizer;
  312. }
  313. @Override
  314. protected void onPreExecute() {
  315. super.onPreExecute();
  316. this.progressDialog.setMessage("Synchronizing data with other device...");
  317. this.progressDialog.setIndeterminate(false);
  318. this.progressDialog.setMax(100);
  319. this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  320. this.progressDialog.setCancelable(true);
  321. this.progressDialog.show();
  322. }
  323. @Override
  324. protected Integer doInBackground(String... params) {
  325. try {
  326. ServerSocket serverSocket = new ServerSocket(this.port);
  327. Log.i("server", "Waiting for clients!");
  328. Socket client = serverSocket.accept();
  329. Log.i("server", "Client connected!");
  330. publishProgress(1);
  331. ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
  332. ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
  333. // -- client speaks first, receive syncinfo
  334. SyncInfo otherSyncInfo = null;
  335. try {
  336. otherSyncInfo = (SyncInfo) ois.readObject();
  337. } catch (ClassNotFoundException e) {
  338. e.printStackTrace();
  339. }
  340. publishProgress(2);
  341. // --- 1. write first message - syncinfo
  342. Log.i("server", "writing to client");
  343. SyncInfo thisSyncInfo = new SyncInfo();
  344. thisSyncInfo.deviceMap.put("dev1", 12L);
  345. thisSyncInfo.deviceMap.put("dev2", 13L);
  346. oos.writeObject(thisSyncInfo);
  347. oos.flush();
  348. publishProgress(3);
  349. // --- 2. read sync data
  350. SyncData syncData = null;
  351. try {
  352. syncData = (SyncData) ois.readObject();
  353. } catch (ClassNotFoundException e) {
  354. e.printStackTrace();
  355. }
  356. publishProgress(4);
  357. // --- 3. send sync data
  358. SyncData mySyncData = new SyncData();
  359. //mySyncData.records.add(new Record());
  360. oos.writeObject(mySyncData);
  361. oos.flush();
  362. publishProgress(5);
  363. // --- 4. We are done!
  364. ois.close();
  365. oos.close();
  366. //copyFile(inputstream, new FileOutputStream(f));
  367. serverSocket.close();
  368. return 0;
  369. } catch (IOException e) {
  370. return -1;
  371. }
  372. }
  373. @Override
  374. protected void onProgressUpdate(Integer... progress) {
  375. this.progressDialog.setProgress(progress[0] * (100 / 5));
  376. }
  377. @Override
  378. protected void onPostExecute(Integer unused) {
  379. this.progressDialog.dismiss();
  380. }
  381. }
  382. public static class ClientAsyncTask extends AsyncTask<String, Integer, Integer> {
  383. private Context context;
  384. private int port;
  385. private String host;
  386. private static final int SOCKET_TIMEOUT = 10000;
  387. private int tryNum = 0;
  388. private final ProgressDialog progressDialog;
  389. private final Synchronizer synchronizer;
  390. @Override
  391. protected void onPreExecute() {
  392. super.onPreExecute();
  393. this.progressDialog.setMessage("Synchronizing data with other device...");
  394. this.progressDialog.setIndeterminate(false);
  395. this.progressDialog.setMax(100);
  396. this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  397. this.progressDialog.setCancelable(true);
  398. this.progressDialog.show();
  399. }
  400. /**
  401. * @param context
  402. */
  403. public ClientAsyncTask(Context context, String host, int port, Synchronizer synchronizer) {
  404. this.context = context;
  405. this.host = host;
  406. this.port = port;
  407. this.progressDialog = new ProgressDialog(context);
  408. this.synchronizer = synchronizer;
  409. }
  410. @Override
  411. protected Integer doInBackground(String... params) {
  412. Socket socket = new Socket();
  413. tryNum++;
  414. try {
  415. Log.i("client", "trying to connect to " + host + ":" + port);
  416. socket.bind(null);
  417. socket.connect(new InetSocketAddress(host, port), SOCKET_TIMEOUT);
  418. Log.i("client", "connected to server");
  419. publishProgress(1);
  420. ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
  421. ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
  422. // Client sends first!
  423. SyncInfo thisSyncInfo = new SyncInfo();
  424. thisSyncInfo.deviceMap.put("dev4", 12L);
  425. thisSyncInfo.deviceMap.put("dev5", 13L);
  426. oos.writeObject(thisSyncInfo);
  427. oos.flush();
  428. publishProgress(2);
  429. // --- 1. Receive sync info
  430. SyncInfo otherSyncInfo = null;
  431. try {
  432. otherSyncInfo = (SyncInfo) ois.readObject();
  433. } catch (ClassNotFoundException e) {
  434. e.printStackTrace();
  435. }
  436. publishProgress(3);
  437. // --- 2. Send sync data
  438. SyncData thisSyncData = new SyncData();
  439. //thisSyncData.records.add(new Record());
  440. oos.writeObject(thisSyncData);
  441. oos.flush();
  442. publishProgress(4);
  443. // --- 3. Receive sync data
  444. SyncData otherSyncData = null;
  445. try {
  446. otherSyncData = (SyncData) ois.readObject();
  447. } catch (ClassNotFoundException e) {
  448. e.printStackTrace();
  449. }
  450. publishProgress(5);
  451. // --
  452. ois.close();
  453. oos.close();
  454. socket.close();
  455. } catch (IOException e) {
  456. if(tryNum >= 5) {
  457. return -1;
  458. }
  459. long seconds_to_wait = (long) Math.min(60, Math.pow(2, tryNum));
  460. Log.i("client", "could not connect to server. Will try again in " + seconds_to_wait + "s");
  461. try {
  462. Thread.sleep(seconds_to_wait * 1000);
  463. doInBackground(params);
  464. } catch (InterruptedException e1) {
  465. e1.printStackTrace();
  466. }
  467. }
  468. return 0;
  469. }
  470. @Override
  471. protected void onProgressUpdate(Integer... progress) {
  472. this.progressDialog.setProgress(progress[0] * (100 / 5));
  473. }
  474. @Override
  475. protected void onPostExecute(Integer unused) {
  476. this.progressDialog.dismiss();
  477. }
  478. }
  479. public static boolean copyFile(InputStream inputStream, OutputStream out) {
  480. byte buf[] = new byte[1024];
  481. int len;
  482. try {
  483. while ((len = inputStream.read(buf)) != -1) {
  484. out.write(buf, 0, len);
  485. }
  486. out.close();
  487. inputStream.close();
  488. } catch (IOException e) {
  489. return false;
  490. }
  491. return true;
  492. }
  493. }