P2PSyncActivity.java 20 KB

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