UsbInterfaceAdapter.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package com.synjones.otg;
  2. import android.app.PendingIntent;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.hardware.usb.UsbConstants;
  6. import android.hardware.usb.UsbDevice;
  7. import android.hardware.usb.UsbDeviceConnection;
  8. import android.hardware.usb.UsbEndpoint;
  9. import android.hardware.usb.UsbInterface;
  10. import android.hardware.usb.UsbManager;
  11. import android.os.Environment;
  12. import android.util.Log;
  13. import com.synjones.multireaderlib.DataTransInterface;
  14. import org.apache.log4j.Level;
  15. import org.apache.log4j.Logger;
  16. import java.io.File;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.Iterator;
  20. import java.util.List;
  21. import de.mindpipe.android.logging.log4j.LogConfigurator;
  22. /**
  23. * Created by zhaodianbo on 1/15.
  24. */
  25. public class UsbInterfaceAdapter implements DataTransInterface {
  26. /**
  27. * 版本标志
  28. */
  29. public static String VERSION = "1.1";
  30. /**
  31. * 调试标志
  32. */
  33. public static String TAG = "XZXUsbReader";
  34. /**
  35. * 权限标志
  36. */
  37. public static final String ACTION_SYNJONES_USB_PERMISSION = "com.synjones.hid.USB_PERMISSION";
  38. /**
  39. * 卸载USB设备
  40. */
  41. public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
  42. // 超时
  43. private int TimeOut = 100;
  44. private int transferTimeOut = TimeOut;
  45. private int readTimeOut = TimeOut;
  46. private int writeTimeOut = TimeOut;
  47. private Context context;
  48. private UsbManager usbManager;
  49. private UsbDevice usbDevice;
  50. private UsbDeviceConnection usbDeviceConnection;
  51. private UsbInterface usbInterface;
  52. private UsbEndpoint uein;
  53. private UsbEndpoint ueout;
  54. private boolean opened = false;
  55. // 收发器属性
  56. private static final int MAX_SENDLEN = 1;
  57. private static final int SECVBUF_LEN = 4096;
  58. private static final int SENDBUF_LEN = MAX_SENDLEN;
  59. // 缓冲区
  60. private byte[] recv_buf = new byte[SECVBUF_LEN];
  61. private byte[] send_buf = new byte[SENDBUF_LEN];
  62. private long receivecount = 0, sendcount = 0;
  63. private ArrayList<String> Supported_VID_PID = new ArrayList();
  64. private Logger gLogger;
  65. public UsbInterfaceAdapter(Context context) {
  66. this.context = context;
  67. this.usbManager = (UsbManager) this.context.getSystemService(Context.USB_SERVICE);
  68. Supported_VID_PID.add("0316:5020");
  69. Supported_VID_PID.add("0400:C35A");
  70. configLog();
  71. }
  72. public UsbInterfaceAdapter(Context context, UsbDevice device) {
  73. this(context);
  74. if (!isSupportedDevice(device)) {
  75. log(getDeviceString(device) + "may is not a supported device");
  76. }
  77. this.usbDevice = device;
  78. }
  79. public String getDevName(){
  80. if(usbDevice==null) return "";
  81. return usbDevice.getDeviceName();
  82. }
  83. public void configLog()
  84. {
  85. LogConfigurator logConfigurator = new LogConfigurator();
  86. logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "usbOtg.txt");
  87. // Set the root log level
  88. logConfigurator.setRootLevel(Level.DEBUG);
  89. // Set log level of a specific logger
  90. logConfigurator.setLevel("org.apache", Level.ERROR);
  91. logConfigurator.configure();
  92. //gLogger = Logger.getLogger(this.getClass());
  93. gLogger = Logger.getLogger("OtgTest");
  94. }
  95. private void log(String log){
  96. Log.e(TAG, log);
  97. //gLogger.error(log);
  98. }
  99. /**
  100. * 判断是否是支持的USB设备类型,即是否是我司设备
  101. *
  102. * @param device
  103. * USB设备
  104. * @return true表示支持,false表示不支持
  105. */
  106. public boolean isSupportedDevice(UsbDevice device) {
  107. //return device.getProductId() == PL2303HXA_PRODUCT_ID;
  108. Iterator<String> iterator=Supported_VID_PID.iterator();
  109. while(iterator.hasNext()){
  110. if(getDeviceVIDPID(device).equals(iterator.next()))
  111. return true;
  112. }
  113. return false;
  114. }
  115. /**
  116. * 获取所有支持的设备,即获取所有的usb设备
  117. *
  118. * @return 设备列表
  119. */
  120. public List<UsbDevice> getAllSupportedDevices() {
  121. List<UsbDevice> res = new ArrayList<UsbDevice>();
  122. HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
  123. Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
  124. while (deviceIterator.hasNext()) {
  125. UsbDevice device = deviceIterator.next();
  126. boolean flag = isSupportedDevice(device);
  127. log(getDeviceString(device) + (flag ? "" : " not support!"));
  128. if (flag)
  129. res.add(device);
  130. }
  131. return res;
  132. }
  133. /**
  134. * 获取设备描述字符串
  135. *
  136. * @param device
  137. * 设备
  138. * @return 描述字符串
  139. */
  140. public static String getDeviceString(UsbDevice device) {
  141. return String.format("DID:%d VID:%04X PID:%04X",
  142. new Object[] { Integer.valueOf(device.getDeviceId()),
  143. Integer.valueOf(device.getVendorId()),
  144. Integer.valueOf(device.getProductId()) });
  145. }
  146. private String getDeviceVIDPID(UsbDevice d) {
  147. return String.format("%04X:%04X", new Object[] {Integer.valueOf(d.getVendorId()),
  148. Integer.valueOf(d.getProductId()) });
  149. }
  150. /**
  151. * 获取USB设备
  152. *
  153. * @return USB设备
  154. */
  155. public UsbDevice getUsbDevice() {
  156. return usbDevice;
  157. }
  158. /**
  159. * 获取设备ID
  160. *
  161. * @return 设备ID
  162. */
  163. public int getDeviceID() {
  164. return this.usbDevice.getDeviceId();
  165. }
  166. /**
  167. * 转换为字符串描述
  168. *
  169. * @return 描述字符串
  170. */
  171. public String toString() {
  172. return String.format("DeviceID:%d VendorID:%04X ProductID:%04X R:%d T:%d", new Object[] { Integer.valueOf(usbDevice.getDeviceId()), Integer.valueOf(usbDevice.getVendorId()), Integer.valueOf(usbDevice.getProductId()), receivecount, sendcount });
  173. }
  174. /**
  175. * 获取设备名称
  176. *
  177. * @return 设备名词
  178. */
  179. public String getName() {
  180. return String.format("usbDeviceID_%d", usbDevice.getDeviceId());
  181. }
  182. /**
  183. * 检查权限,如果没有权限则请求授权
  184. *
  185. * @return true 有权限, false 无权限,并开始请求授权
  186. */
  187. public boolean checkPermission() {
  188. return checkPermission(true);
  189. }
  190. /**
  191. * 检查权限
  192. *
  193. * @param autoRequest
  194. * 没有权限的时候是否自动请求权限,true自动请求,false不自动请求
  195. * @return true 有权限, false 无权限,并开始请求授权
  196. */
  197. public boolean checkPermission(boolean autoRequest) {
  198. if (!usbManager.hasPermission(usbDevice)) {
  199. log( "no permission");
  200. if (autoRequest) {
  201. log( "requesting permission");
  202. PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_SYNJONES_USB_PERMISSION), 0);
  203. usbManager.requestPermission(usbDevice, mPermissionIntent);
  204. }
  205. return false;
  206. }
  207. log( "permission true");
  208. return true;
  209. }
  210. /**
  211. * 打开设备
  212. *打开失败异常,如果未授权或不支持的设置参数
  213. */
  214. public boolean open() {
  215. close();
  216. List<UsbDevice> devList=getAllSupportedDevices();
  217. if(devList.size()<=0){
  218. log("usb device not find");
  219. return false;
  220. }
  221. usbDevice=devList.get(0);
  222. if (usbDevice == null ||usbManager ==null) {
  223. log( "open failed,usbDevice|usbManager = null");
  224. return false;
  225. }
  226. log( "find usb device="+usbDevice);
  227. if(!checkPermission())
  228. return false;
  229. int UARTintf = 0;
  230. for (int index = 0; index < usbDevice.getInterfaceCount(); ++index) {
  231. UsbInterface intf = usbDevice.getInterface(index);
  232. if ((255 != intf.getInterfaceClass()) || (intf.getInterfaceProtocol() != 0) ||
  233. (intf.getInterfaceSubclass() != 0)) continue;
  234. UARTintf = index;
  235. break;
  236. }
  237. log( "UARTintf="+UARTintf);
  238. UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(usbDevice);
  239. if (usbDeviceConnection != null) {
  240. log( "openDevice()=>ok!");
  241. // Log.i(TAG, "getInterfaceCount()=>" + device.getInterfaceCount());
  242. this.usbDeviceConnection=usbDeviceConnection;
  243. this.usbInterface = usbDevice.getInterface(UARTintf);
  244. //this.uein= usbInterface.getEndpoint(0);
  245. //this.ueout = usbInterface.getEndpoint(1);
  246. log( "usbInterface="+usbInterface);
  247. for (int i = 0; i < usbInterface.getEndpointCount(); ++i) {
  248. UsbEndpoint ue = usbInterface.getEndpoint(i);
  249. if ((ue.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK || ue.getType()==UsbConstants.USB_ENDPOINT_XFER_INT) && ue.getDirection() == UsbConstants.USB_DIR_IN) {
  250. uein = ue;
  251. } else if ((ue.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK || ue.getType()==UsbConstants.USB_ENDPOINT_XFER_INT) && ue.getDirection() == UsbConstants.USB_DIR_OUT) {
  252. ueout = ue;
  253. }
  254. }
  255. if (uein != null && ueout != null) {
  256. log("uein="+uein);
  257. log("ueout="+ueout);
  258. if(usbDeviceConnection.claimInterface(usbInterface, true)){
  259. log("get Endpoint ok!");
  260. opened = true;
  261. }else{
  262. usbDeviceConnection.close();
  263. }
  264. }
  265. } else {
  266. log( "openDevice()=>fail!");
  267. // throw new Exception("usbManager.openDevice failed!");
  268. }
  269. return opened;
  270. }
  271. /**
  272. * 重置
  273. */
  274. public void reset() throws Exception {
  275. /*
  276. byte[] mPortSetting = new byte[7];
  277. controlTransfer(161, 33, 0, 0, mPortSetting, 7, transferTimeOut);
  278. mPortSetting[0] = (byte) (baudRate & 0xff);
  279. mPortSetting[1] = (byte) (baudRate >> 8 & 0xff);
  280. mPortSetting[2] = (byte) (baudRate >> 16 & 0xff);
  281. mPortSetting[3] = (byte) (baudRate >> 24 & 0xff);
  282. mPortSetting[4] = 0;
  283. mPortSetting[5] = 0;
  284. mPortSetting[6] = 8;
  285. controlTransfer(33, 32, 0, 0, mPortSetting, 7, transferTimeOut);
  286. controlTransfer(161, 33, 0, 0, mPortSetting, 7, transferTimeOut);
  287. */
  288. }
  289. private int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) {
  290. int res = this.usbDeviceConnection.controlTransfer(requestType, request, value, index, buffer, length, timeout);
  291. if (res < 0) {
  292. String err = String.format("controlTransfer fail when: %d %d %d %d buffer %d %d", requestType, request, value, index, length, timeout);
  293. log( err);
  294. }
  295. return res;
  296. }
  297. /**
  298. * 设备是否已经打开
  299. *
  300. * @return true已经打开,false未打开
  301. */
  302. public boolean isOpened() {
  303. return opened;
  304. }
  305. /**
  306. * 向串口发一字节
  307. *
  308. * @param data
  309. * 要发送的数据
  310. * @return 发送了的字节数
  311. */
  312. public int write(byte data) {
  313. send_buf[0] = data;
  314. int ret = usbDeviceConnection.bulkTransfer(ueout, send_buf, 1, writeTimeOut);
  315. ++sendcount;
  316. return ret;
  317. }
  318. /**
  319. * 发送一串数据
  320. *
  321. * @param datas
  322. * 要发送的数据数组
  323. * @return 发送了的字节数
  324. */
  325. public int write(byte[] datas) {
  326. int ret = usbDeviceConnection.bulkTransfer(ueout, datas, datas.length, writeTimeOut);
  327. sendcount += ret;
  328. return ret;
  329. }
  330. private int readix = 0;
  331. private int readlen = 0;
  332. private boolean readSuccess = false;
  333. /**
  334. * 读取一个字节,调用该函数之后需要调用isReadSuccess()进行判断返回的数据是否是真正读取的数据
  335. *
  336. * @return 被读取的数据
  337. */
  338. public byte read() {
  339. byte ret = 0;
  340. if (readix >= readlen) {
  341. readlen = usbDeviceConnection.bulkTransfer(uein, recv_buf, SECVBUF_LEN, readTimeOut);
  342. readix = 0;
  343. }
  344. if (readix < readlen) {
  345. ret = recv_buf[readix];
  346. readSuccess = true;
  347. ++receivecount;
  348. ++readix;
  349. } else {
  350. readSuccess = false;
  351. }
  352. return ret;
  353. }
  354. /**
  355. * 判断上一个读操作是否成功
  356. *
  357. * @return
  358. */
  359. public boolean isReadSuccess() {
  360. return readSuccess;
  361. }
  362. /**
  363. * 关闭串口
  364. */
  365. public void close() {
  366. this.opened = false;
  367. if (this.usbDeviceConnection != null) {
  368. /*if (this.usbInterface != null) {
  369. this.usbDeviceConnection.releaseInterface(this.usbInterface);
  370. this.usbInterface = null;
  371. }*/
  372. this.usbDeviceConnection.close();
  373. this.usbDevice = null;
  374. this.usbDeviceConnection = null;
  375. }
  376. }
  377. public void release(){
  378. if (this.usbInterface != null) {
  379. this.usbDeviceConnection.releaseInterface(this.usbInterface);
  380. this.usbInterface = null;
  381. }
  382. }
  383. /**
  384. * 清空读缓冲区
  385. */
  386. public void cleanRead() {
  387. if (usbDeviceConnection == null){
  388. return;
  389. }
  390. while ((readlen = usbDeviceConnection.bulkTransfer(uein, recv_buf, recv_buf.length, readTimeOut)) > 0) {
  391. }
  392. readlen = 0;
  393. readix = 0;
  394. }
  395. public int getReadTimeOut() {
  396. return readTimeOut;
  397. }
  398. public void setReadTimeOut(int readTimeOut) {
  399. this.readTimeOut = readTimeOut;
  400. }
  401. public int getWriteTimeOut() {
  402. return writeTimeOut;
  403. }
  404. public void setWriteTimeOut(int writeTimeOut) {
  405. this.writeTimeOut = writeTimeOut;
  406. }
  407. @Override
  408. public void sendData(byte[] data, int datalen) {
  409. int offset=0;
  410. while(datalen>0){
  411. byte sendBuf[]=new byte[Math.min(64,datalen)];
  412. System.arraycopy(data,offset,sendBuf,0,sendBuf.length);
  413. if (usbDeviceConnection == null){
  414. return;
  415. }
  416. int ret = usbDeviceConnection.bulkTransfer(ueout, sendBuf, sendBuf.length, writeTimeOut);
  417. sendcount+=ret;
  418. offset+=sendBuf.length;
  419. datalen-=sendBuf.length;
  420. }
  421. // sendcount += ret;
  422. }
  423. @Override
  424. public int recvData(byte[] recvbuf, int offset) {
  425. if (usbDeviceConnection == null){
  426. return -1;
  427. }
  428. byte buffer[]=new byte[64];
  429. readlen = usbDeviceConnection.bulkTransfer(uein, buffer, 64, readTimeOut);
  430. if(readlen<=0) return readlen;
  431. receivecount+=readlen;
  432. int recvbufLen=recvbuf.length;
  433. int remainSpace=recvbufLen-offset;
  434. int copyLen=Math.min(remainSpace,readlen);
  435. System.arraycopy(buffer,0,recvbuf,offset,copyLen);
  436. return copyLen;
  437. }
  438. @Override
  439. public void clear() {
  440. cleanRead();
  441. }
  442. }