android端rfid的sdk

1 篇文章 0 订阅
1 篇文章 0 订阅

android端rfid的sdk

1 项目简介

名称:仓储管理系统

需求:利用手机终端扫描RFID芯片管理设备的生命周期

2 蓝牙RFID模块
/**
 * 蓝牙设备 扫描功能
 * 判断蓝牙连接情况,连接蓝牙,
 * 开始盘点、结束盘点
 * 关闭app时关闭蓝牙
 */
public class BluetoothRfidModule extends WXSDKEngine.DestroyableModule {

    final byte MSG_M100CMDRESP = 0X08;
    final byte MSG_M100GETVERSION = 0X0C;
    final byte MSG_M100DATARESP_INV = 0X0B;
    final byte MSG_M100GETANTPOW = 0x05;
    final byte MSG_M100SETANTPOW = 0x50;
    final byte MSG_M100WRITERESULT = 0X0D;
    final byte MSG_M100SELECTRESULT = 0X0E;
    final byte MSG_M100ERRORRESULT = 0X11;
    final byte MSG_M100STOPINVMULTIRESULT = 0X10;
    final byte MSG_M100READTAGRESULT = 0X12;
    final byte MSG_IOEXCEPTION = 0X13;
    //rfid
    public M100_RFID_API rfid = new M100_RFID_API();
    //蓝牙适配器
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();

    /**
     * 初始化参数
     * StandRSSI 设置扫描距离。
     *
     * @param options
     * @param jsCallback
     */
    @JSMethod(uiThread = true)
    public void init(JSONObject options, final JSCallback jsCallback) {
        Map rs = new HashMap();
        Log.e("UhfRfid", "init" + options.toJSONString());
        bluetoothPermissions();
        //获取已经配对设备的列表、进行通信
        _bluetooth.getBondedDevices();
    }

    private void bluetoothPermissions() {
        if (_bluetooth == null) {
            Toast.makeText(this.mWXSDKInstance.getContext(), "无法打开设备蓝牙,请确认设备是否有蓝牙功能!", Toast.LENGTH_LONG).show();
            return;
        }
        new Thread() {
            public void run() {
                if (_bluetooth.isEnabled() == false) {
                    _bluetooth.enable();
                }
            }
        }.start();
        Util.initSoundPool(this.mWXSDKInstance.getContext());

    }

    @Override
    public void destroy() {

    }

    // 查找到设备和搜索完成action监听器
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // 查找到设备action
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 得到蓝牙设备
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                } else { // 添加到已配对设备列表
                }
                // 搜索完成action
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {

                // if(mPairedDevicesArrayAdapter.getCount() > 0)
                // findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            }
        }
    };

    public String CaclWiegand_Comon(byte[] data_arr, int data_len) {
        //4244224   40C300
        String strwiegand = "";
        if (data_len >= 3) {
            strwiegand = String.format("%08d", ((data_arr[data_len - 3] & 0xFF) * 65536 + (data_arr[data_len - 2] & 0xFF) * 256 + (data_arr[data_len - 1] & 0xFF)));
        }
        return strwiegand;
    }

    public void ShowDevVersion(String HWver, String SWver) {
        Toast toast = Toast.makeText(this.mWXSDKInstance.getContext(), "HardWareVer = " + HWver + "\n\n\n"
                + "SoftWareVer = " + SWver, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_M100DATARESP_INV:
                    Bundle x6b4 = msg.getData();
                    String x6EPCstr4 = x6b4.getString("InvData");
                    byte[] x6invdatabyte = x6b4.getByteArray("InvDatabyte");
                    String x6invtt = "";
                    for (int i = 0; i < x6invdatabyte.length; i++) {
                        x6invtt += String.format("%1$x", x6invdatabyte[i]);
                    }
                    LogUtil.d("DEBUG", "ByteArray INV:" + x6invtt);
                    LogUtil.d("DEBUG", "handle INV: " + x6EPCstr4);
                    //CaclWiegand(x6invdatabyte,x6invdatabyte.length);
                    String caclInfo = CaclWiegand_Comon(x6invdatabyte, x6invdatabyte.length);
                    LogUtil.d("DEBUG", "caclInfo" + caclInfo);
                    break;
                case MSG_M100GETVERSION:
                    Bundle ver = msg.getData();
                    String HWver = ver.getString("HWver");
                    String SWver = ver.getString("SWver");
                    LogUtil.d("DEBUG", "HWver: " + HWver);
                    LogUtil.d("DEBUG", "SWver: " + SWver);
                    ShowDevVersion(HWver, SWver);
                    break;
                case MSG_M100GETANTPOW:
                    Bundle pow = msg.getData();
                    int M100pow = pow.getInt("AntPow");
                    LogUtil.d("DEBUG", "AntPow: " + M100pow);
                    break;
                case MSG_M100SETANTPOW:
                    LogUtil.d("DEBUG", "Setpow_Result(1=fail  0=success): " + msg.arg1);//00 成功  01失败
                    break;
                case MSG_M100WRITERESULT:
                    LogUtil.d("DEBUG", "WriteTag_Result(1=fail  0=success): " + msg.arg1);//00 成功  01失败
                    break;
                case MSG_M100SELECTRESULT:
                    LogUtil.d("DEBUG", "SelectTag_Result(1=fail  0=success): " + msg.arg1);//00 成功  01失败
                    break;
                case MSG_M100ERRORRESULT:
                    LogUtil.d("DEBUG", "ErrorCode_Result(01=fail  00=success 10=NoTAG  16=pssword error): " + String.format("%1$02x" + " ", msg.arg1));//00 成功  01失败
                    //write
                    //10 该标签没有在场区或者指定的 EPC 代码不对
                    //16  Access Password 不正确
                    //B0|X  B3即B0|03=B3   03为存储区超出  03为EPC Gen2协议规定的错误代码
                    //InvMuluti
                    //没有收到标签返回或者返回数据 CRC 校验错误,将返回错误代码 0x15
                    break;
                case MSG_M100STOPINVMULTIRESULT:
                    LogUtil.d("DEBUG", "StopInvMultiTag_Result(1=fail  0=success): " + msg.arg1);//00 成功  01失败
                    break;
                case MSG_M100READTAGRESULT:
                    Bundle ReadTagdata = msg.getData();
                    String Readstr = ReadTagdata.getString("ReadData");
                    byte[] Readdatabyte = ReadTagdata.getByteArray("ReadDatabyte");
                    String Readtt = "";
                    for (int i = 0; i < Readdatabyte.length; i++) {
                        Readtt += String.format("%1$02x", Readdatabyte[i]);
                    }
                    LogUtil.d("DEBUG", "ByteArray READ:" + Readtt);
                    LogUtil.d("DEBUG", "handle READ: " + Readstr);
                    break;
                case MSG_IOEXCEPTION:
                    Bundle e = msg.getData();
                    LogUtil.d("DEBUG", "IOException:" + e.getString("e"));

                    try {
                        rfid.M100_CloseBluetoothSocket();
                        //_socket.close();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    //_socket = null;
                    break;
                case MSG_M100CMDRESP:
                    Bundle x6ver = msg.getData();
                    String x6HWver = x6ver.getString("HWver");
                    String x6SWver = x6ver.getString("SWver");
                    LogUtil.d("DEBUG", "x6HWver: " + x6HWver);
                    LogUtil.d("DEBUG", "x6SWver: " + x6SWver);
                    ShowDevVersion(x6HWver, x6SWver);
                    break;
                default:
                    break;
            }

        }
    };


}

3 蓝牙连接模块

public class DeviceListActivity extends Activity implements OnClickListener{

	private static final String TAG = "DeviceListActivity";
	private static final boolean D = true;


	public static String EXTRA_DEVICE_ADDRESS = "设备地址";

	// 成员域
	private BluetoothAdapter mBtAdapter;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 得到本地蓝牙句柄
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		// 创建并显示窗口
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); // 设置窗口显示模式为窗口方式
		setContentView(R.layout.device_list);

		// 设定默认返回值为取消
		setResult(Activity.RESULT_CANCELED);

		// 设定扫描按键响应
		Button scanButton = (Button) findViewById(R.id.button_scan);
		scanButton.setOnClickListener(this);//指定当前对象

		// 初使化设备存储数组
		mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);
		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);

		// 设置已配队设备列表

		ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
		pairedListView.setAdapter(mPairedDevicesArrayAdapter);
		pairedListView.setOnItemClickListener(mDeviceClickListener);

		// 设置新查找设备列表
		ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
		newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
		newDevicesListView.setOnItemClickListener(mDeviceClickListener);

		// 注册接收查找到设备action接收器
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
		filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		this.registerReceiver(mReceiver, filter);

		// 注册查找结束action接收器
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);

		// 得到本地蓝牙句柄
		//mBtAdapter = BluetoothAdapter.getDefaultAdapter();

		// 得到已配对蓝牙设备列表
		// Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

		// 添加已配对设备到列表并显示
		// if (pairedDevices.size() > 0) {
		// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
		// for (BluetoothDevice device : pairedDevices) {
		// mPairedDevicesArrayAdapter.add(device.getName() + "\n" +
		// device.getAddress());
		// }
		// } else {
		// String noDevices = "No devices have been paired";
		// mPairedDevicesArrayAdapter.add(noDevices);
		// }
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// 关闭服务查找
		if (mBtAdapter != null) {
			mBtAdapter.cancelDiscovery();
		}

		// 注销action接收器
		this.unregisterReceiver(mReceiver);
	}

	public void OnCancel(View v) {
		finish();
	}

	/**
	 * 开始服务和设备查找
	 */
	private void doDiscovery() {
		if (D)
			Log.d(TAG, "doDiscovery()");

		// 在窗口显示查找中信息
		setProgressBarIndeterminateVisibility(true);
		setTitle(R.string.listsearching);

		// 显示其它设备(未配对设备)列表
		findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

		// 关闭再进行的服务查找
		if (mBtAdapter.isDiscovering()) {
			mBtAdapter.cancelDiscovery();
		}
		// 并重新开始
		mBtAdapter.startDiscovery();
	}

	// 选择设备响应函数
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			// 准备连接设备,关闭服务查找
			mBtAdapter.cancelDiscovery();

			// 得到mac地址
			String info = ((TextView) v).getText().toString();
			
			System.out.println("BlueTooth mac is :"+info);
			if (info.length() < 17) {
				finish();
				return;
			}
			
			String address = info.substring(info.length() - 17);
			LogUtil.d("DEBUG","BlueTooth mac address is :"+address);
			// 设置返回数据
			Intent intent = new Intent();
			intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
			// 设置返回值并结束程序
			setResult(Activity.RESULT_OK, intent);
			finish();
		}
	};

	// 查找到设备和搜索完成action监听器
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			// 查找到设备action
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// 得到蓝牙设备
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// 如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					mNewDevicesArrayAdapter.add(device.getName() + "\n"
							+ device.getAddress());
				} else { // 添加到已配对设备列表
					mPairedDevicesArrayAdapter.add(device.getName() + "\n"
							+ device.getAddress());
				}
				// 搜索完成action
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
				setTitle(R.string.listselectdevtoconn);
				if (mNewDevicesArrayAdapter.getCount() == 0) {
					// int noDevices =R.string.listnotgetdev;
					String noDevices = context.getResources().getString(
							R.string.listnotgetdev);
					mNewDevicesArrayAdapter.add(noDevices);
				}
				// if(mPairedDevicesArrayAdapter.getCount() > 0)
				// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
			}
		}
	};

	@Override
	public void onClick(View view) {
		int i = view.getId();
		if (i == R.id.button_scan) {
			doDiscovery();
			view.setVisibility(View.GONE);

		}
	}
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值