SearchWiFiDirectPrinterTask.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package com.epson.mobilephone.common.wifidirect;
  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.IntentFilter;
  6. import android.net.wifi.ScanResult;
  7. import android.net.wifi.WifiManager;
  8. import android.net.wifi.p2p.WifiP2pDevice;
  9. import android.net.wifi.p2p.WifiP2pDeviceList;
  10. import android.net.wifi.p2p.WifiP2pManager;
  11. import android.os.AsyncTask;
  12. import android.os.Build;
  13. import android.os.Bundle;
  14. import android.os.Handler;
  15. import android.os.Message;
  16. import android.os.SystemClock;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.List;
  20. import epson.print.CommonDefine;
  21. public class SearchWiFiDirectPrinterTask {
  22. private static final int DELEY_SEARCH = 1000;
  23. public static final String MACADDR_INFRA = "addr_infra";
  24. public static final String MACADDR_P2P = "addr_p2p";
  25. private static final int MAX_RETRY_SCANNING = 5;
  26. private static final int MAX_RETRY_SCANNING_CHECKINGTIME = 3;
  27. private static final int MAX_RETRY_SCANNING_P2P = 30;
  28. private static final int MAX_SCANRESULT_TIME = 30000;
  29. public static final String NETWORK_ID = "id";
  30. public static final String PRINTER_NAME = "name";
  31. public static final int PRINTER_P2P = 2;
  32. public static final int PRINTER_SIMPLEAP = 1;
  33. public static final String PRINTER_SSID = "ssid";
  34. public static final int SCANNING_TIMEOUT = 15;
  35. public static final String TAG = "SearchWiFiDirectPrinterTask";
  36. protected static long lastScan;
  37. private static SearchWiFiDirectPrinterTask searchWiFiDirectPrinterTask;
  38. private final int DISCOVER_PEERS = 0;
  39. boolean bDisConnectP2P = false;
  40. Context context = null;
  41. int idResult = 0;
  42. ArrayList<String> listFoundSSID = new ArrayList<>();
  43. Handler mHandler = null;
  44. WifiP2pManager mWiFiP2PManager = null;
  45. WifiManager mWifiManager = null;
  46. NetworkStateChangeReciever networkStateChangeReciever = null;
  47. WifiP2pManager.Channel p2pChannnel = null;
  48. WiFiDirectBroadcastReceiver p2pStateChangeReciever = null;
  49. int retryScaning = 0;
  50. int retryScaningP2P = 0;
  51. ScanningObserver scannigObserver = new ScanningObserver();
  52. Handler searchHandler = new Handler(new Handler.Callback() {
  53. public boolean handleMessage(Message message) {
  54. if (message.what == 0) {
  55. WifiP2pUtils.ConnectionInfo connectionInfo = WifiP2pUtils.getInstance (context).getConnectionInfo();
  56. if (connectionInfo != null) {
  57. if (context).isExcludedMacAddress(WiFiControl.p2pAddr2PtrAddr(connectionInfo.p2PMacAdder, connectionInfo.printerName))) {
  58. bDisConnectP2P = true;
  59. }
  60. }
  61. SearchWiFiDirectPrinterTask.mWiFiP2PManager.discoverPeers (p2pChannnel, new WifiP2pManager.ActionListener() {
  62. public void onSuccess() {
  63. EPLog.d(SearchWiFiDirectPrinterTask.TAG, "discoverPeers Start");
  64. serarchingStatus |= 2;
  65. }
  66. public void onFailure(int i) {
  67. switch (i) {
  68. case 0:
  69. EPLog.w(SearchWiFiDirectPrinterTask.TAG, "P2P_Operation ERROR");
  70. break;
  71. case 1:
  72. EPLog.w(SearchWiFiDirectPrinterTask.TAG, "P2P_Operation P2P_UNSUPPORTED");
  73. break;
  74. case 2:
  75. EPLog.w(SearchWiFiDirectPrinterTask.TAG, "P2P_Operation BUSY");
  76. if (!bDisConnectP2P && WifiP2pUtils.getInstance (context).isConnectedWiFiP2P()) {
  77. EPLog.w(SearchWiFiDirectPrinterTask.TAG, "Disconnect P2P and And Retry");
  78. WifiP2pUtils.getInstance (context).disconnect();
  79. bDisConnectP2P = true;
  80. searchHandler.sendEmptyMessageDelayed(0, 1000);
  81. return;
  82. }
  83. default:
  84. EPLog.w(SearchWiFiDirectPrinterTask.TAG, "P2P_Operation Fail");
  85. break;
  86. }
  87. if (serarchingStatus == 0) {
  88. SearchWiFiDirectPrinterTask.mHandler.sendEmptyMessage (idResult);
  89. }
  90. }
  91. });
  92. }
  93. return true;
  94. }
  95. });
  96. volatile int serarchingStatus = 0;
  97. int timeout = 15;
  98. public static SearchWiFiDirectPrinterTask getInstance(Context context2) {
  99. SearchWiFiDirectPrinterTask searchWiFiDirectPrinterTask2 = searchWiFiDirectPrinterTask;
  100. if (searchWiFiDirectPrinterTask2 != null) {
  101. return searchWiFiDirectPrinterTask2;
  102. }
  103. searchWiFiDirectPrinterTask = new SearchWiFiDirectPrinterTask(context2);
  104. return searchWiFiDirectPrinterTask;
  105. }
  106. private SearchWiFiDirectPrinterTask(Context context2) {
  107. context = context2.getApplicationContext();
  108. mWifiManager = (WifiManager) context2.getSystemService(Service.WIFI_SERVICE);
  109. mWiFiP2PManager = (WifiP2pManager) context2.getSystemService("wifip2p");
  110. WifiP2pManager wifiP2pManager = mWiFiP2PManager;
  111. if (wifiP2pManager != null) {
  112. p2pChannnel = wifiP2pManager.initialize(context2, context2.getMainLooper(), (WifiP2pManager.ChannelListener) null);
  113. }
  114. }
  115. private boolean start(int i, Handler handler, int i2, int i3) {
  116. if (serarchingStatus != 0) {
  117. EPLog.d(TAG, "Already started");
  118. return true;
  119. }
  120. EPLog.d(TAG, "start()");
  121. mHandler = handler;
  122. idResult = i2;
  123. timeout = i3;
  124. if (!mWifiManager.isWifiEnabled()) {
  125. return false;
  126. }
  127. listFoundSSID.clear();
  128. retryScaning = 0;
  129. retryScaningP2P = 0;
  130. scannigObserver.start(i3 * 1000);
  131. if ((i & 1) != 0) {
  132. networkStateChangeReciever = new NetworkStateChangeReciever();
  133. context.registerReceiver(networkStateChangeReciever, new IntentFilter("android.net.wifi.SCAN_RESULTS"));
  134. serarchingStatus |= 1;
  135. onScanResultAvailable();
  136. }
  137. if (!((i & 2) == 0 || mWiFiP2PManager == null || p2pChannnel == null)) {
  138. p2pStateChangeReciever = new WiFiDirectBroadcastReceiver();
  139. context.registerReceiver(p2pStateChangeReciever, new IntentFilter("android.net.wifi.p2p.PEERS_CHANGED"));
  140. bDisConnectP2P = false;
  141. searchHandler.sendEmptyMessage(0);
  142. }
  143. return true;
  144. }
  145. public void interrupt() {
  146. EPLog.d(TAG, "interrupt()");
  147. Handler handler = searchHandler;
  148. if (handler != null) {
  149. handler.removeMessages(0);
  150. }
  151. scannigObserver.interrunpt();
  152. if (!(mWiFiP2PManager == null || p2pChannnel == null)) {
  153. EPLog.d(TAG, "stopPeerDiscovery");
  154. mWiFiP2PManager.stopPeerDiscovery(p2pChannnel, (WifiP2pManager.ActionListener) null);
  155. }
  156. unRegisterReceiverSimpleAp();
  157. unRegisterReceiverP2P();
  158. serarchingStatus = 0;
  159. }
  160. private void unRegisterReceiverSimpleAp() {
  161. NetworkStateChangeReciever networkStateChangeReciever2 = networkStateChangeReciever;
  162. if (networkStateChangeReciever2 != null) {
  163. try {
  164. context.unregisterReceiver(networkStateChangeReciever2);
  165. } catch (IllegalArgumentException e) {
  166. e.printStackTrace();
  167. }
  168. networkStateChangeReciever = null;
  169. }
  170. }
  171. private void unRegisterReceiverP2P() {
  172. WiFiDirectBroadcastReceiver wiFiDirectBroadcastReceiver = p2pStateChangeReciever;
  173. if (wiFiDirectBroadcastReceiver != null) {
  174. try {
  175. context.unregisterReceiver(wiFiDirectBroadcastReceiver);
  176. } catch (IllegalArgumentException e) {
  177. e.printStackTrace();
  178. }
  179. p2pStateChangeReciever = null;
  180. }
  181. }
  182. private void onScanResultAvailable() {
  183. boolean z;
  184. int existSimpleApDisabled;
  185. long elapsedRealtime = SystemClock.elapsedRealtime();
  186. if (Build.VERSION.SDK_INT >= 17) {
  187. z = true;
  188. } else {
  189. long j = lastScan;
  190. if (j != 0 && elapsedRealtime - j < 30000) {
  191. EPLog.i(TAG, "onScanResultAvailable, use this Result");
  192. z = true;
  193. } else if (retryScaning > 0) {
  194. EPLog.i(TAG, "onScanResultAvailable, use this Retry Result");
  195. z = true;
  196. } else {
  197. EPLog.w(TAG, "onScanResultAvailable, ignore this Result");
  198. z = false;
  199. }
  200. }
  201. if (z) {
  202. List<ScanResult> arrayList = new ArrayList<>();
  203. try {
  204. arrayList = mWifiManager.getScanResults();
  205. } catch (SecurityException e) {
  206. e.printStackTrace();
  207. }
  208. if (arrayList.size() != 0) {
  209. for (ScanResult scanResult : arrayList) {
  210. if (retryScaning < 3 && Build.VERSION.SDK_INT >= 17) {
  211. long j2 = elapsedRealtime - (scanResult.timestamp / 1000);
  212. if (j2 >= 30000) {
  213. EPLog.w(TAG, "onScanResultAvailable, Ignore for timeout : SSID =" + scanResult.SSID + " past " + j2 + " msec");
  214. }
  215. }
  216. String removeQuotationsInSSID = WiFiUtils.removeQuotationsInSSID(scanResult.SSID);
  217. if (WiFiControl.isSimpleAP(removeQuotationsInSSID)) {
  218. int networkId = WiFiUtils.getInstance(context).getNetworkId(removeQuotationsInSSID);
  219. if (networkId != -1) {
  220. onFindPrinterResult(WiFiControl.addSSIDPrefix(removeQuotationsInSSID, WiFiControl.ConnectType.SimpleAP), networkId, scanResult.BSSID);
  221. } else if (Build.VERSION.SDK_INT < 23 && (existSimpleApDisabled = WiFiUtils.getInstance(context).getExistSimpleApDisabled(removeQuotationsInSSID)) != -1) {
  222. onFindPrinterResult(WiFiControl.addSSIDPrefix(removeQuotationsInSSID, WiFiControl.ConnectType.SimpleAP), existSimpleApDisabled, scanResult.BSSID);
  223. }
  224. }
  225. }
  226. }
  227. }
  228. lastScan = elapsedRealtime;
  229. retryScaning++;
  230. if (retryScaning < 5) {
  231. EPLog.i(TAG, "Retry startScan()");
  232. mWifiManager.startScan();
  233. return;
  234. }
  235. EPLog.i(TAG, "MAX_RETRY_SCANING");
  236. unRegisterReceiverSimpleAp();
  237. serarchingStatus &= -2;
  238. if (serarchingStatus == 0) {
  239. mHandler.sendEmptyMessage(idResult);
  240. interrupt();
  241. }
  242. }
  243. private void onFindPrinterResult(String str, int i, String str2) {
  244. if (listFoundSSID.contains(str)) {
  245. listFoundSSID.add(str);
  246. SimpleAPInfoDB.SimpleAPInfo simpleAPInfoDB = SimpleAPInfoDB.getSimpleAPInfoDB(context, str);
  247. if (simpleAPInfoDB == null) {
  248. simpleAPInfoDB = new SimpleAPInfoDB.SimpleAPInfo();
  249. simpleAPInfoDB.ssid = str;
  250. WiFiControl.getInstance(context);
  251. simpleAPInfoDB.printerName = WiFiControl.getPrinterNetworkName(str);
  252. }
  253. Message obtain = Message.obtain();
  254. obtain.what = idResult;
  255. Bundle bundle = new Bundle();
  256. bundle.putString("ssid", simpleAPInfoDB.ssid);
  257. bundle.putString("name", simpleAPInfoDB.printerName);
  258. bundle.putInt("id", i);
  259. bundle.putString(MACADDR_P2P, str2);
  260. if (-1 != i) {
  261. bundle.putString(MACADDR_INFRA, WiFiControl.p2pAddr2PtrAddr(str2, (String) null));
  262. } else {
  263. bundle.putString(MACADDR_INFRA, WiFiControl.p2pAddr2PtrAddr(str2, simpleAPInfoDB.ssid));
  264. }
  265. EPLog.d(TAG, "onFindPrinterResult() data = " + bundle.getString("ssid") + CommonDefine.SLASH + bundle.getString("name") + CommonDefine.SLASH + bundle.getString(MACADDR_INFRA) + CommonDefine.SLASH + bundle.getString(MACADDR_P2P));
  266. obtain.setData(bundle);
  267. mHandler.sendMessage(obtain);
  268. }
  269. }
  270. class NetworkStateChangeReciever extends BroadcastReceiver {
  271. NetworkStateChangeReciever() {
  272. }
  273. public void onReceive(Context context, Intent intent) {
  274. if (intent.getAction().equals("android.net.wifi.SCAN_RESULTS")) {
  275. EPLog.d(SearchWiFiDirectPrinterTask.TAG, "Scan Results Available");
  276. onScanResultAvailable();
  277. }
  278. }
  279. }
  280. class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
  281. WiFiDirectBroadcastReceiver() {
  282. }
  283. public void onReceive(Context context, Intent intent) {
  284. WifiP2pDeviceList wifiP2pDeviceList;
  285. if (intent.getAction().equals("android.net.wifi.p2p.PEERS_CHANGED") && (wifiP2pDeviceList = (WifiP2pDeviceList) intent.getParcelableExtra("wifiP2pDeviceList")) != null) {
  286. Collection<WifiP2pDevice> deviceList = wifiP2pDeviceList.getDeviceList();
  287. if (deviceList.size() == 0) {
  288. EPLog.d(SearchWiFiDirectPrinterTask.TAG, "No devices found");
  289. return;
  290. }
  291. for (WifiP2pDevice next : deviceList) {
  292. if (next.deviceName == null || next.deviceName.trim().isEmpty()) {
  293. EPLog.w(SearchWiFiDirectPrinterTask.TAG, "deviceName is empty" + next.deviceAddress);
  294. } else if (!WifiP2pUtils.PrimaryDeviceType.isPrinter(next.primaryDeviceType)) {
  295. EPLog.i(SearchWiFiDirectPrinterTask.TAG, "Category Not Printer " + next.deviceName);
  296. } else if (MacAddrFilter.getInstance(context).isExcludedMacAddress(WiFiControl.p2pAddr2PtrAddr(next.deviceAddress, next.deviceName))) {
  297. EPLog.i(SearchWiFiDirectPrinterTask.TAG, "Excluded Printer " + next.deviceName);
  298. } else {
  299. onFindPrinterResult(WiFiControl.addSSIDPrefix(next.deviceName, WiFiControl.ConnectType.WiFiP2P), -1, next.deviceAddress);
  300. }
  301. }
  302. EPLog.i(SearchWiFiDirectPrinterTask.TAG, "Continue discover Peers()");
  303. }
  304. }
  305. }
  306. class ScanningObserver {
  307. AsyncTask<Void, Void, Void> observerTask = null;
  308. ScanningObserver() {
  309. }
  310. private void start(final int i) {
  311. interrunpt();
  312. EPLog.d(SearchWiFiDirectPrinterTask.TAG, "Start ScanningObserver");
  313. observerTask = new AsyncTask<Void, Void, Void>() {
  314. protected Void doInBackground(Void... voidArr) {
  315. int i = 0;
  316. do {
  317. try {
  318. if (i >= i) {
  319. return null;
  320. }
  321. Thread.sleep(100);
  322. i += 100;
  323. } catch (InterruptedException e) {
  324. e.printStackTrace();
  325. return null;
  326. }
  327. } while (!isCancelled());
  328. return null;
  329. }
  330. protected void onPostExecute(Void voidR) {
  331. EPLog.i(SearchWiFiDirectPrinterTask.TAG, "Timeout ScanningObserver");
  332. SearchWiFiDirectPrinterTask.mHandler.sendEmptyMessage (idResult);
  333. interrupt();
  334. }
  335. }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]);
  336. }
  337. private void interrunpt() {
  338. AsyncTask<Void, Void, Void> asyncTask = observerTask;
  339. if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING && !this.observerTask.isCancelled()) {
  340. EPLog.d(SearchWiFiDirectPrinterTask.TAG, "Stop ScanningObserver");
  341. observerTask.cancel(false);
  342. }
  343. }
  344. }
  345. }