P2PSyncActivity.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. package de.tudarmstadt.informatik.hostage.sync.p2p;
  2. import android.app.Activity;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.IntentFilter;
  6. import android.net.wifi.p2p.WifiP2pConfig;
  7. import android.net.wifi.p2p.WifiP2pDevice;
  8. import android.net.wifi.p2p.WifiP2pDeviceList;
  9. import android.net.wifi.p2p.WifiP2pGroup;
  10. import android.net.wifi.p2p.WifiP2pInfo;
  11. import android.net.wifi.p2p.WifiP2pManager;
  12. import android.os.AsyncTask;
  13. import android.os.Bundle;
  14. import android.util.Log;
  15. import android.view.LayoutInflater;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.widget.AdapterView;
  19. import android.widget.ArrayAdapter;
  20. import android.widget.ListView;
  21. import android.widget.RelativeLayout;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24. import android.widget.ViewAnimator;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.InputStreamReader;
  28. import java.io.OutputStream;
  29. import java.io.Reader;
  30. import java.io.UnsupportedEncodingException;
  31. import java.lang.reflect.InvocationTargetException;
  32. import java.lang.reflect.Method;
  33. import java.net.InetSocketAddress;
  34. import java.net.ServerSocket;
  35. import java.net.Socket;
  36. import java.util.ArrayList;
  37. import java.util.List;
  38. import de.tudarmstadt.informatik.hostage.R;
  39. public class P2PSyncActivity extends Activity implements WifiP2pManager.GroupInfoListener, WifiP2pManager.PeerListListener, WifiP2pManager.ChannelListener, AdapterView.OnItemClickListener, WifiP2pManager.ConnectionInfoListener {
  40. private WifiP2pManager mManager;
  41. private WifiP2pManager.Channel mChannel;
  42. private BroadcastReceiver mReceiver;
  43. private IntentFilter mIntentFilter;
  44. private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
  45. private TextView mTxtP2PDeviceName;
  46. private TextView mTxtP2PDeviceStatus;
  47. private ViewAnimator mViewAnimator;
  48. private RelativeLayout mDevicesContainer;
  49. private TextView mTxtP2PSearchProgress;
  50. private ListView mLstP2PDevices;
  51. private RelativeLayout mWelcomeContainer;
  52. private TextView mTxtP2PNotAvailable;
  53. private TextView mTxtP2PChangeDeviceName;
  54. private WifiP2pDevice mDevice;
  55. private WifiP2pDevice mOtherDevice;
  56. private WifiP2pInfo mInfo;
  57. private final int OWNER_SERVER_PORT = 8988;
  58. private final int CLIENT_SERVER_PORT = 8989;
  59. private ClientAsyncTask clientAsync;
  60. private ServerAsyncTask serverAsync;
  61. private void extractFromView(){
  62. mTxtP2PDeviceName = (TextView) findViewById(R.id.txt_p2p_device_name);
  63. mTxtP2PDeviceStatus = (TextView) findViewById(R.id.txt_p2p_device_status);
  64. mTxtP2PChangeDeviceName = (TextView) findViewById(R.id.txtP2PChangeDeviceName);
  65. //mTxtP2PHeader = (TextView) findViewById(R.id.txtP2PHeader);
  66. //mTxtP2PSubHeader = (TextView) findViewById(R.id.txtP2PSubheader);
  67. //mTxtP2PHelpBack = (TextView) findViewById(R.id.txtP2PHelpBack);
  68. mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
  69. mDevicesContainer = (RelativeLayout) findViewById(R.id.devicesContainer);
  70. mWelcomeContainer = (RelativeLayout) findViewById(R.id.welcomeContainer);
  71. mTxtP2PSearchProgress = (TextView) findViewById(R.id.txtP2PSearchProgress);
  72. mLstP2PDevices = (ListView) findViewById(R.id.lstP2PDevices);
  73. //mBtnP2PSearch = (Button) findViewById(R.id.btnP2PSearch);
  74. mTxtP2PNotAvailable = (TextView) findViewById(R.id.txtP2PNotAvailable);
  75. }
  76. public void discoverPeers(){
  77. mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
  78. @Override
  79. public void onSuccess() {
  80. mViewAnimator.showNext();
  81. mTxtP2PSearchProgress.setVisibility(View.VISIBLE);
  82. setWifiDirectAvailable();
  83. }
  84. @Override
  85. public void onFailure(int reason) {
  86. if(reason == WifiP2pManager.P2P_UNSUPPORTED) {
  87. setWifiDirectNotAvailable();
  88. }
  89. }
  90. });
  91. }
  92. public void setWifiDirectNotAvailable(){
  93. //mBtnP2PSearch.setVisibility(View.GONE);
  94. mTxtP2PNotAvailable.setVisibility(View.VISIBLE);
  95. peers.clear();
  96. ((WiFiPeerListAdapter) mLstP2PDevices.getAdapter()).notifyDataSetChanged();
  97. mDevice = null;
  98. }
  99. public void setWifiDirectAvailable(){
  100. //mBtnP2PSearch.setVisibility(View.VISIBLE);
  101. mTxtP2PNotAvailable.setVisibility(View.GONE);
  102. }
  103. public void closeConnection(){
  104. if(this.serverAsync != null && !this.serverAsync.isCancelled()){
  105. this.serverAsync.cancel(true);
  106. }
  107. if(this.clientAsync != null && !this.clientAsync.isCancelled()){
  108. this.clientAsync.cancel(true);
  109. }
  110. }
  111. public void registerListeners(){
  112. mTxtP2PChangeDeviceName.setOnClickListener(new View.OnClickListener() {
  113. @Override
  114. public void onClick(View v) {
  115. Method method1 = null;
  116. try {
  117. method1 = mManager.getClass().getDeclaredMethod("setDeviceName", WifiP2pManager.Channel.class);
  118. method1.invoke(mManager, mChannel, "Android_fc546");
  119. } catch (NoSuchMethodException e) {
  120. e.printStackTrace();
  121. } catch (InvocationTargetException e) {
  122. e.printStackTrace();
  123. } catch (IllegalAccessException e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. });
  128. }
  129. @Override
  130. protected void onCreate(Bundle savedInstanceState) {
  131. super.onCreate(savedInstanceState);
  132. setContentView(R.layout.activity_p2_psync);
  133. assert getActionBar() != null;
  134. getActionBar().setTitle("WifiDirect Synchronization");
  135. this.extractFromView();
  136. this.registerListeners();
  137. this.mLstP2PDevices.setAdapter(new WiFiPeerListAdapter(this, R.layout.row_devices, peers));
  138. this.mLstP2PDevices.setOnItemClickListener(this);
  139. mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
  140. mChannel = mManager.initialize(this, getMainLooper(), new WifiP2pManager.ChannelListener() {
  141. @Override
  142. public void onChannelDisconnected() {
  143. System.out.println("---------------------> CHannel disconnect!!!");
  144. }
  145. });
  146. mIntentFilter = new IntentFilter();
  147. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
  148. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
  149. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
  150. mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
  151. this.discoverPeers();
  152. }
  153. @Override
  154. protected void onResume() {
  155. super.onResume();
  156. mReceiver = new P2PBroadcastReceiver(mManager, mChannel, this);
  157. registerReceiver(mReceiver, mIntentFilter);
  158. }
  159. @Override
  160. protected void onPause() {
  161. super.onPause();
  162. unregisterReceiver(mReceiver);
  163. }
  164. @Override
  165. public void onPeersAvailable(WifiP2pDeviceList peerList){
  166. mTxtP2PSearchProgress.setVisibility(View.GONE);
  167. peers.clear();
  168. peers.addAll(peerList.getDeviceList());
  169. ((WiFiPeerListAdapter) mLstP2PDevices.getAdapter()).notifyDataSetChanged();
  170. if (peers.size() == 0) {
  171. return;
  172. }
  173. }
  174. private WifiP2pDevice getConnectedPeer(){
  175. for(WifiP2pDevice device: peers){
  176. if(device.status == WifiP2pDevice.CONNECTED){
  177. return device;
  178. }
  179. }
  180. return null;
  181. }
  182. private static String getDeviceStatus(int deviceStatus) {
  183. switch (deviceStatus) {
  184. case WifiP2pDevice.AVAILABLE:
  185. return "Available";
  186. case WifiP2pDevice.INVITED:
  187. return "Invited";
  188. case WifiP2pDevice.CONNECTED:
  189. return "Connected";
  190. case WifiP2pDevice.FAILED:
  191. return "Failed";
  192. case WifiP2pDevice.UNAVAILABLE:
  193. return "Unavailable";
  194. default:
  195. return "Unknown";
  196. }
  197. }
  198. public void updateThisDevice(WifiP2pDevice device) {
  199. this.mDevice = device;
  200. mTxtP2PDeviceName.setText(device.deviceName);
  201. mTxtP2PDeviceStatus.setText(getDeviceStatus(device.status));
  202. }
  203. @Override
  204. public void onChannelDisconnected() {
  205. closeConnection();
  206. }
  207. @Override
  208. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  209. final WifiP2pDevice device = (WifiP2pDevice) this.mLstP2PDevices.getAdapter().getItem(position);
  210. WifiP2pConfig config = new WifiP2pConfig();
  211. config.deviceAddress = device.deviceAddress;
  212. mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
  213. @Override
  214. public void onSuccess() {
  215. mOtherDevice = device;
  216. }
  217. @Override
  218. public void onFailure(int reason) {
  219. //mOtherDevice = null;
  220. Toast.makeText(P2PSyncActivity.this, "Could not connect to device. Retry.", Toast.LENGTH_LONG).show();
  221. }
  222. });
  223. }
  224. @Override
  225. public void onConnectionInfoAvailable(WifiP2pInfo info) {
  226. mInfo = info;
  227. //if(mOtherDevice == null) return;
  228. if(info.groupFormed && info.isGroupOwner){
  229. Log.i("server", "I am the group owner!");
  230. WifiP2pDevice connectedPeer = getConnectedPeer();
  231. if(connectedPeer != null && mInfo != null){
  232. Log.i("peers", mInfo.groupFormed + " - " + mInfo.isGroupOwner);
  233. Log.i("server", "Starting async server!");
  234. serverAsync = new ServerAsyncTask(this, OWNER_SERVER_PORT);
  235. serverAsync.execute();
  236. }
  237. //new ClientAsyncTask(this, mOtherDevice.deviceAddress, CLIENT_SERVER_PORT).execute();
  238. } else if(info.groupFormed){
  239. //new ServerAsyncTask(this, CLIENT_SERVER_PORT).execute();
  240. Log.i("client", "Starting async client!");
  241. clientAsync = new ClientAsyncTask(this, mInfo.groupOwnerAddress.getHostAddress(), OWNER_SERVER_PORT);
  242. clientAsync.execute();
  243. }
  244. }
  245. public void sendDatabase(boolean isOwner){
  246. }
  247. @Override
  248. public void onGroupInfoAvailable(WifiP2pGroup group) {
  249. }
  250. /**
  251. * Array adapter for ListFragment that maintains WifiP2pDevice list.
  252. */
  253. private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {
  254. private List<WifiP2pDevice> items;
  255. /**
  256. * @param context
  257. * @param textViewResourceId
  258. * @param objects
  259. */
  260. public WiFiPeerListAdapter(Context context, int textViewResourceId,
  261. List<WifiP2pDevice> objects) {
  262. super(context, textViewResourceId, objects);
  263. items = objects;
  264. }
  265. @Override
  266. public View getView(int position, View convertView, ViewGroup parent) {
  267. View v = convertView;
  268. if (v == null) {
  269. LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  270. v = vi.inflate(R.layout.row_devices, null);
  271. }
  272. WifiP2pDevice device = items.get(position);
  273. if (device != null) {
  274. TextView top = (TextView) v.findViewById(R.id.device_name);
  275. TextView bottom = (TextView) v.findViewById(R.id.device_details);
  276. if (top != null) {
  277. top.setText(device.deviceName);
  278. }
  279. if (bottom != null) {
  280. bottom.setText(getDeviceStatus(device.status));
  281. }
  282. }
  283. return v;
  284. }
  285. }
  286. public static class ServerAsyncTask extends AsyncTask<Void, Void, String> {
  287. private Activity context;
  288. private int port;
  289. /**
  290. * @param context
  291. */
  292. public ServerAsyncTask(Activity context, int port) {
  293. this.context = context;
  294. this.port = port;
  295. }
  296. @Override
  297. protected String doInBackground(Void... params) {
  298. try {
  299. ServerSocket serverSocket = new ServerSocket(this.port);
  300. Log.i("server", "Waiting for clients!");
  301. Socket client = serverSocket.accept();
  302. Log.i("server", "Client connected!");
  303. /*final File f = new File(Environment.getExternalStorageDirectory() + "/"
  304. + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
  305. + ".txt");
  306. File dirs = new File(f.getParent());
  307. if (!dirs.exists())
  308. dirs.mkdirs();
  309. f.createNewFile();*/
  310. InputStream inputstream = client.getInputStream();
  311. readToToast(inputstream);
  312. Log.i("server", "writing to client");
  313. client.getOutputStream().write(("HELLO I HOPE THIS WILL REACH IT'S DESTINATION. I am server").getBytes());
  314. //copyFile(inputstream, new FileOutputStream(f));
  315. inputstream.close();
  316. serverSocket.close();
  317. return "";
  318. } catch (IOException e) {
  319. return null;
  320. }
  321. }
  322. public void readToToast(InputStream inputStream){
  323. final String received = inputStreamToString(inputStream, 2048);
  324. Log.i("server", "Received: " + received);
  325. context.runOnUiThread(new Runnable() {
  326. public void run() {
  327. Toast.makeText(context, "Received: " + received, Toast.LENGTH_LONG).show();
  328. }
  329. });
  330. }
  331. public static String inputStreamToString(final InputStream is, final int bufferSize)
  332. {
  333. final char[] buffer = new char[bufferSize];
  334. final StringBuilder out = new StringBuilder();
  335. try {
  336. final Reader in = new InputStreamReader(is, "UTF-8");
  337. try {
  338. for (;;) {
  339. int rsz = in.read(buffer, 0, buffer.length);
  340. if (rsz < 0)
  341. break;
  342. out.append(buffer, 0, rsz);
  343. }
  344. } finally {
  345. in.close();
  346. }
  347. } catch (UnsupportedEncodingException ex) {
  348. ex.printStackTrace();
  349. } catch (IOException ex) {
  350. ex.printStackTrace();
  351. }
  352. return out.toString();
  353. }
  354. }
  355. public static class ClientAsyncTask extends AsyncTask<Void, Void, Void> {
  356. private Context context;
  357. private int port;
  358. private String host;
  359. private static final int SOCKET_TIMEOUT = 10000;
  360. private int tryNum = 0;
  361. /**
  362. * @param context
  363. */
  364. public ClientAsyncTask(Context context, String host, int port) {
  365. this.context = context;
  366. this.host = host;
  367. this.port = port;
  368. }
  369. @Override
  370. protected Void doInBackground(Void... params) {
  371. Socket socket = new Socket();
  372. tryNum++;
  373. try {
  374. Log.i("client", "trying to connect to " + host + ":" + port);
  375. socket.bind(null);
  376. socket.connect(new InetSocketAddress(host, port), SOCKET_TIMEOUT);
  377. Log.i("client", "connected to server");
  378. OutputStream stream = socket.getOutputStream();
  379. Log.i("client", "sending: " + "HELLO I HOPE THIS WILL REACH IT'S DESTINATION. I am " + host);
  380. stream.write(("HELLO I HOPE THIS WILL REACH IT'S DESTINATION. I am " + host).getBytes());
  381. stream.flush();
  382. stream.close();
  383. socket.close();
  384. } catch (IOException e) {
  385. if(tryNum >= 12) {
  386. return null;
  387. }
  388. long seconds_to_wait = (long) Math.min(60, Math.pow(2, tryNum));
  389. Log.i("client", "could not connect to server. Will try again in " + seconds_to_wait + "s");
  390. try {
  391. Thread.sleep(seconds_to_wait * 1000);
  392. doInBackground(params);
  393. } catch (InterruptedException e1) {
  394. e1.printStackTrace();
  395. }
  396. }
  397. return null;
  398. }
  399. }
  400. public static boolean copyFile(InputStream inputStream, OutputStream out) {
  401. byte buf[] = new byte[1024];
  402. int len;
  403. try {
  404. while ((len = inputStream.read(buf)) != -1) {
  405. out.write(buf, 0, len);
  406. }
  407. out.close();
  408. inputStream.close();
  409. } catch (IOException e) {
  410. return false;
  411. }
  412. return true;
  413. }
  414. }