生活不易、且行且珍惜。网站首页 程序人生
Java调用海康HCUsbSDK制卡刷卡读卡
发布时间:2020-11-18 14:50编辑:zj 阅读:文章分类: Java互动QQ群:170915747
根据HCUsbSDK接口文档和JAVADEMO开发的一个发卡、读卡、刷卡的程序
淘宝买的空白UID卡,卡里需要存入员工工号和卡编号,在web后台来操作制卡、刷卡
简单记录下,方便以后开发相似的功能可以直接拿去用
发卡器型号是【海康威视DS-K1F100-D8E】
Mifare卡操作
登录设备、激活卡、密码验证
/** * @param args the command line arguments */ static HCUsbSDK hcusbsdk = HCUsbSDK.INSTANCE; static fDEVInfoCallBack fdeviceCallBack = null;// 报警回调函数实现 static HCUsbSDK.USB_SDK_DEVICE_INFO StruDevceInfo = new HCUsbSDK.USB_SDK_DEVICE_INFO(); static boolean bDevCallBack = false; public static class fDEVInfoCallBack implements HCUsbSDK.fEnumDeviceCallBack { @Override public void invoke(HCUsbSDK.USB_SDK_DEVICE_INFO pDevceInfo, Pointer pUser) { if ((pDevceInfo.szDeviceName[0] == 'D') && (pDevceInfo.szDeviceName[1] == 'S') && (pDevceInfo.szDeviceName[2] == '-') && (pDevceInfo.szDeviceName[3] == 'K')) { StruDevceInfo = pDevceInfo; String strName = new String(pDevceInfo.szDeviceName); System.out.println("枚举到的设备信息:" + strName); bDevCallBack = true; } } } //登录设备 private static NativeLong login() { int iError = 0; boolean bInit = hcusbsdk.USB_SDK_Init(); if (bInit) { hcusbsdk.USB_SDK_SetLogToFile(3, "C:/USBSDKLog", false); } if (fdeviceCallBack == null) { fdeviceCallBack = new fDEVInfoCallBack(); } boolean bEnum = hcusbsdk.USB_SDK_EnumDevice(fdeviceCallBack, null); if (!bEnum) { iError = hcusbsdk.USB_SDK_GetLastError(); System.out.println("枚举失败,错误码为" + iError); return null; } HCUsbSDK.USB_SDK_USER_LOGIN_INFO struUserLoginInfo = new HCUsbSDK.USB_SDK_USER_LOGIN_INFO(); struUserLoginInfo.dwSize = struUserLoginInfo.size(); struUserLoginInfo.dwTimeout = 5000; while (true) { if (bDevCallBack) { struUserLoginInfo.dwVID = StruDevceInfo.dwVID; struUserLoginInfo.dwPID = StruDevceInfo.dwPID; struUserLoginInfo.szUserName = "admin".getBytes(); struUserLoginInfo.szPassword = "12345".getBytes(); struUserLoginInfo.szSerialNumber = StruDevceInfo.szSerialNumber; break; } } struUserLoginInfo.write(); // System.out.println("dwSize:" +struUserLoginInfo.dwSize ); // System.out.println("dwVID:" +struUserLoginInfo.dwVID ); // System.out.println("dwPID:" +struUserLoginInfo.dwPID ); // System.out.println("szUserName:" + new String(struUserLoginInfo.szUserName).trim() ); // System.out.println("szPassword:" +new String(struUserLoginInfo.szPassword).trim() ); // System.out.println("szSerialNumber:" +new String(struUserLoginInfo.szSerialNumber).trim() ); HCUsbSDK.USB_SDK_DEVICE_REG_RES struRegRes = new HCUsbSDK.USB_SDK_DEVICE_REG_RES(); struRegRes.dwSize = struRegRes.size(); struRegRes.write(); NativeLong lUserID = hcusbsdk.USB_SDK_Login(struUserLoginInfo, struRegRes);// 登录设备 if (lUserID.intValue() == -1) { iError = hcusbsdk.USB_SDK_GetLastError(); System.out.println("登陆失败,错误码为" + iError); hcusbsdk.USB_SDK_Logout(lUserID); } else { System.out.println("登陆成功"); } return lUserID; } //激活卡 private static String active(NativeLong lUserID) { int iError = 0; HCUsbSDK.USB_SDK_WAIT_SECOND struWaitSecond = new HCUsbSDK.USB_SDK_WAIT_SECOND(); struWaitSecond.dwSize = struWaitSecond.size(); struWaitSecond.byWait = 0; struWaitSecond.write(); HCUsbSDK.USB_SDK_ACTIVATE_CARD_RES struActivate = new HCUsbSDK.USB_SDK_ACTIVATE_CARD_RES(); struActivate.dwSize = struActivate.size(); struActivate.byCardType = 1; struActivate.write(); HCUsbSDK.USB_CONFIG_INPUT_INFO struInput = new HCUsbSDK.USB_CONFIG_INPUT_INFO(); struInput.lpInBuffer = struWaitSecond.getPointer(); struInput.dwInBufferSize = struWaitSecond.size(); struInput.write(); HCUsbSDK.USB_CONFIG_OUTPUT_INFO struOutput = new HCUsbSDK.USB_CONFIG_OUTPUT_INFO(); struOutput.lpOutBuffer = struActivate.getPointer(); struOutput.dwOutBufferSize = struActivate.size(); struOutput.write(); boolean bRet = hcusbsdk.USB_SDK_GetDeviceConfig(lUserID, HCUsbSDK.USB_SDK_GET_ACTIVATE_CARD, struInput, struOutput); if (!bRet) { iError = hcusbsdk.USB_SDK_GetLastError(); System.out.println("激活失败,错误码为" + iError); return ""; } struOutput.read(); struActivate.read(); String strSerial = ""; for (int i = 0; i < struActivate.bySerialLen; i++) { int iSerial = struActivate.bySerial[i] & 0xff; strSerial = strSerial + new String(Integer.toHexString(iSerial)) + " "; } System.out.println("激活成功,卡号:" + strSerial); return strSerial; } //密码验证 private static void valid(NativeLong lUserID) { int iError = 0; HCUsbSDK.USB_SDK_SET_M1_PWD_VERIFY struWaitSecond = new HCUsbSDK.USB_SDK_SET_M1_PWD_VERIFY(); struWaitSecond.dwSize = struWaitSecond.size(); struWaitSecond.bySectionNum = hexToByte("1"); struWaitSecond.byCardType = hexToByte("0"); struWaitSecond.byPassword = hexToByteArray("FFFFFFFFFFFF"); struWaitSecond.write(); HCUsbSDK.USB_CONFIG_INPUT_INFO struInput = new HCUsbSDK.USB_CONFIG_INPUT_INFO(); struInput.lpInBuffer = struWaitSecond.getPointer(); struInput.dwInBufferSize = struWaitSecond.size(); struInput.write(); HCUsbSDK.USB_CONFIG_OUTPUT_INFO struOutput = new HCUsbSDK.USB_CONFIG_OUTPUT_INFO(); struOutput.lpOutBuffer = struWaitSecond.getPointer(); struOutput.dwOutBufferSize = struWaitSecond.size(); struOutput.write(); boolean bRet = hcusbsdk.USB_SDK_SetDeviceConfig(lUserID, HCUsbSDK.USB_SDK_SET_M1_PWD_VERIFY, struInput, struOutput); if (!bRet) { iError = hcusbsdk.USB_SDK_GetLastError(); System.out.println("验证失败,错误码为" + iError); return; } System.out.println("验证成功"); }
写卡、读卡
private static void write(NativeLong lUserID, String cardNo) { int iError = 0; while (cardNo.length() < 32) { cardNo = "0" + cardNo; } if (cardNo.length() > 32) { cardNo = cardNo.substring(0, 16); } HCUsbSDK.USB_SDK_M1_BLOCK_WRITE_DATA struWaitSecond = new HCUsbSDK.USB_SDK_M1_BLOCK_WRITE_DATA(); struWaitSecond.dwSize = struWaitSecond.size(); struWaitSecond.wAddr = hexToByteArray("4"); struWaitSecond.byDataLen = 16; struWaitSecond.byData = hexToByteArray(cardNo); struWaitSecond.write(); HCUsbSDK.USB_CONFIG_INPUT_INFO struInput = new HCUsbSDK.USB_CONFIG_INPUT_INFO(); struInput.lpInBuffer = struWaitSecond.getPointer(); struInput.dwInBufferSize = struWaitSecond.size(); struInput.write(); HCUsbSDK.USB_CONFIG_OUTPUT_INFO struOutput = new HCUsbSDK.USB_CONFIG_OUTPUT_INFO(); struOutput.lpOutBuffer = struWaitSecond.getPointer(); struOutput.dwOutBufferSize = struWaitSecond.size(); struOutput.write(); boolean bRet = hcusbsdk.USB_SDK_SetDeviceConfig(lUserID, HCUsbSDK.USB_SDK_SET_M1_WRITE_BLOCK, struInput, struOutput); if (!bRet) { iError = hcusbsdk.USB_SDK_GetLastError(); System.out.println("写卡失败,错误码为" + iError); makeDevice(lUserID, "3", "3", "2", "3"); //写卡错误是快鸣2下,闪烁2下红灯 return; } makeDevice(lUserID, "2", "1", "3", "2"); //写卡成功是慢鸣1下,闪烁2下蓝灯 System.out.println("写卡成功,内容为" + cardNo); } private static String read(NativeLong lUserID) { int iError = 0; HCUsbSDK.USB_SDK_M1_BLOCK_ADDR struWaitSecond = new HCUsbSDK.USB_SDK_M1_BLOCK_ADDR(); struWaitSecond.dwSize = struWaitSecond.size(); struWaitSecond.wAddr = hexToByteArray("4"); struWaitSecond.write(); HCUsbSDK.USB_SDK_M1_BLOCK_DATA struOut = new HCUsbSDK.USB_SDK_M1_BLOCK_DATA(); struOut.dwSize = struOut.size(); struOut.write(); HCUsbSDK.USB_CONFIG_INPUT_INFO struInput = new HCUsbSDK.USB_CONFIG_INPUT_INFO(); struInput.lpInBuffer = struWaitSecond.getPointer(); struInput.dwInBufferSize = struWaitSecond.size(); struInput.write(); HCUsbSDK.USB_CONFIG_OUTPUT_INFO struOutput = new HCUsbSDK.USB_CONFIG_OUTPUT_INFO(); struOutput.lpOutBuffer = struOut.getPointer(); struOutput.dwOutBufferSize = struOut.size(); struOutput.write(); boolean bRet = hcusbsdk.USB_SDK_SetDeviceConfig(lUserID, HCUsbSDK.USB_SDK_GET_M1_READ_BLOCK, struInput, struOutput); if (!bRet) { iError = hcusbsdk.USB_SDK_GetLastError(); System.out.println("读卡失败,错误码为" + iError); makeDevice(lUserID, "3", "3", "2", "3"); return ""; } struOutput.read(); struOut.read(); String strSerial = ""; /*for (int i = 0; i < struOut.byData.length; i++) { int iSerial = struOut.byData[i] & 0xff; System.out.println(struOut.byData[i]+"____"+iSerial+"___"+Integer.toHexString(iSerial)); strSerial = strSerial + new String(Integer.toHexString(iSerial)) + ""; }*/ strSerial = bytes2hexStr(struOut.byData); System.out.println(strSerial); makeDevice(lUserID, "2", "1", "3", "2"); System.out.println("读卡成功,内容为" + Long.parseLong(strSerial, 16)); return String.valueOf(Long.parseLong(strSerial, 16)); }
控制蜂鸣器及显示灯(自定义声音和显示灯闪烁提示)
public static Boolean makeDevice(NativeLong lUserID, String buBeepType, String buBeepCount, String byFlickerType, String byFlickerCount){ HCUsbSDK.USB_SDK_SET_BEEP_AND_FLICKER fukcjer = new HCUsbSDK.USB_SDK_SET_BEEP_AND_FLICKER(); fukcjer.dwSize = fukcjer.size(); fukcjer.byBeepType = hexToByte(buBeepType); fukcjer.byBeepCount = hexToByte(buBeepCount); fukcjer.byFlickerType = hexToByte(byFlickerType); fukcjer.byFlickerCount = hexToByte(byFlickerCount); fukcjer.write(); HCUsbSDK.USB_CONFIG_INPUT_INFO pInputInfo = new HCUsbSDK.USB_CONFIG_INPUT_INFO(); pInputInfo.lpInBuffer = fukcjer.getPointer(); pInputInfo.dwInBufferSize = fukcjer.size(); pInputInfo.write(); HCUsbSDK.USB_CONFIG_OUTPUT_INFO pOutInfo = new HCUsbSDK.USB_CONFIG_OUTPUT_INFO(); pOutInfo.dwOutBufferSize = fukcjer.size(); pOutInfo.write(); Boolean bb =hcusbsdk.USB_SDK_SetDeviceConfig(lUserID, HCUsbSDK.USB_SDK_SET_BEEP_AND_FLICKER,pInputInfo,pOutInfo); System.out.println(bb); return bb; }
上面就是调用sdk的部分了,都是根据接口文档写的,下面是业务代码
获取唯一卡号、写卡、读卡
@RequestMapping(value = "/getKh.do") @ResponseBody public Object getKh() { NativeLong lUserID = login(); String readKh = active(lUserID); valid(lUserID); Boolean ss =hcusbsdk.USB_SDK_Logout(lUserID); System.out.println("只获取卡号方法:"+readKh); System.out.println("退出登录:"+ss); return Ret.ok("获取成功").put("kh",readKh).put("lUserID",lUserID).build(); } @RequestMapping(value = "/make.do") @ResponseBody public Object make() { Map<String, Object> map = new HashMap<String, Object>(); PageData pd = this.getPageData(); NativeLong lUserID = login(); try { int cardnum = pd.getInteger("cardnum")+1; String number = pd.getString("number"); String readKh = active(lUserID); valid(lUserID); String cardNo = number+ String.valueOf(cardnum); System.out.println("写入卡号:" + cardNo+"----"+Long.toHexString(Long.valueOf(cardNo))); write(lUserID, Long.toHexString(Long.valueOf(cardNo))); map.put("kh", readKh); map.put("cardNo", cardNo); //退出登录 Boolean ss =hcusbsdk.USB_SDK_Logout(lUserID); pd.put("cardnum", cardnum); pd.put("status", "1"); memberService.edit(pd); System.out.println("退出登录:"+ss); return Ret.ok("获取成功").put("kh",readKh).put("cardnum", cardnum).build(); } catch (Exception e) { //退出登录 hcusbsdk.USB_SDK_Logout(lUserID); logger.error(e.toString(), e); } return ""; } @RequestMapping(value = "/showmakeRecord.do") @ResponseBody public Object showmakeRecord() { Map<String, Object> map = new HashMap<String, Object>(); PageData pd = this.getPageData(); NativeLong lUserID = login(); try { String readKh = active(lUserID); map.put("kh", readKh); if(Tools.isEmpty(readKh)){ map.put("cardid", ""); }else{ valid(lUserID); String cardid = read(lUserID); if(Tools.isEmpty(cardid)||cardid.equals("0")){ map.put("cardid", "0"); hcusbsdk.USB_SDK_Logout(lUserID); return map; } System.out.println("读卡内容:"+cardid); String number = cardid.substring(0,4); pd.put("number",number); List<PageData> list = memberService.listAll(pd); map.put("lUserID", lUserID); map.put("info", list.get(0)); map.put("cardid", cardid); //查询该卡当天是否已存记录 PageData rpd = new PageData(); rpd.put("cardNumber", cardid); Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); rpd.put("createTime", sdf.format(now)); List<PageData> rList = cardRecordService.listAll(rpd); //如该卡当天未刷,则新增记录 if(rList.size()==0){ PageData savePd = new PageData(); savePd.put("id", Tools.getUniqueId()); savePd.put("name", list.get(0).getString("name")); savePd.put("cardNumber", cardid); savePd.put("number", number); savePd.put("status", "0"); savePd.put("type", "0"); savePd.put("createTime", now); savePd.put("modifiedTime",now); savePd.put("isDeleted", 0); cardRecordService.save(savePd); } } hcusbsdk.USB_SDK_Logout(lUserID); } catch (Exception e) { hcusbsdk.USB_SDK_Logout(lUserID); logger.error(e.toString(), e); } return map; }
前端写卡、刷卡操作
var num ; var totalnum ; var datetime ; var overnum ; var kh ; var rtkh ; function khf(i){ console.log("i="+i+"——————num="+num); if(i>num){ $('.btn-primary').removeAttr('disabled'); return; }else{ $.ajax({ url: '<%=basePath%>cardMake/getKh.do', type: "POST", data:$('#form').serialize(), dataType: "json", async: true, success: function(data){ rtkh = data.kh; $('#lUserID').val(data.lUserID); console.log("rtkh="+rtkh+"______kh="+kh); if(rtkh==""){ var now = new Date().getTime(); Alert("请将卡放置在卡机上", 1000,false); var tt = now - datetime; if(tt>10000){ $('#showinfo').html("<h4 style='color:red;'>由于长时间未操作,制卡已停止,已制卡"+overnum+"张,还剩"+totalnum+"张,请重新选择制卡张数开始制卡</h4>"); return; } khf(i); }else{ if(kh != rtkh){ $.ajax({ url: '<%=basePath%>cardMake/make.do', type: "POST", data: $('#form').serialize(), dataType: "json", async: true, success: function(data){ kh = data.kh; datetime = new Date().getTime(); totalnum--; overnum++; $('#cardnum').val(data.cardnum); $('#cardnumover').text(data.cardnum); // Alert("制卡成功!", 2000); if(overnum == num){ $('#showinfo').html("<h4 style='color:red;'>制卡完成,本轮共制卡"+overnum+"张</h4>"); }else{ $('#showinfo').html("<h4 style='color:red;'>制卡成功,已制卡"+overnum+"张</h4>"); } khf(i+1); } }) }else{ Alert("该卡已制卡成功,请换一张卡!", 1000,false); var tt = new Date().getTime() - datetime; if(tt>10000){ $('#showinfo').html("<h4 style='color:red;'>由于长时间未操作,制卡已停止,已制卡"+overnum+"张,还剩"+totalnum+"张,请重新选择制卡张数开始制卡</h4>"); $('.btn-primary').removeAttr('disabled'); return; } khf(i); } } } }) } } function save(){ $('.btn-primary').attr('disabled', 'disabled'); $('#showinfo').html("<h4 style='color:red;'>请将卡放置在卡机上</h4>"); if($('#form').valid()){ num = $('#num').val(); totalnum = $('#num').val(); datetime = new Date().getTime(); overnum = 0; kh = ""; rtkh = ""; khf(1); }else{ $('.btn-primary').removeAttr('disabled'); } } var datetime ; var rtkh="" ; var kh = ""; var i = 0; function khf(){ $.ajax({ url: '<%=basePath%>cardMake/getKh.do', type: "POST", data:$('#form').serialize(), dataType: "json", async: true, success: function(data){ rtkh = data.kh; console.log(data.lUserID); $('#lUserID').val(data.lUserID); console.log("kh="+kh+"___rtkh="+rtkh); if(kh != rtkh){ $.ajax({ url: '<%=basePath%>cardMake/showmakeRecord.do', type: "POST", data:$('#form').serialize(), dataType: "json", async: true, success: function(data){ kh = data.kh; console.log(data); datetime = new Date().getTime(); if(data.cardid==""){ var str = "<h3 style='margin-left: 12px;color:red;'>读卡失败,请重试</h3><hr>"; $('#showinfo').html(str); }else if(data.cardid=="0"){ var str = "<h3 style='margin-left: 12px;color:red;'>读卡失败,该卡为空卡</h3><hr>"; $('#showinfo').html(str); }else { i++; var str = "<h3 style='margin-left: 12px;'>读卡成功 + " + i + "</h3><hr>"; str += "<p style='margin-left: 12px;'>姓名:<span style='color:red;'>" + data.info.name + "</span></p>"; str += "<p style='margin-left: 12px;'>工号:<span style='color:red;'>" + data.info.number + "</span></p>"; str += "<p style='margin-left: 12px;'>卡ID:<span style='color:red;'>" + data.cardid + "</span></p>"; $('#showinfo').html(str); } khf() } }) }else{ var t2 = new Date().getTime() - datetime; if(t2>10000){ $('#showinfo').html("<h4 style='color:red;margin-left: 12px;'>读卡完成</h4>"); $('.button1').removeAttr('disabled'); return; } khf() } } }) } function ck(){ $('.button1').attr('disabled', 'disabled'); $('#showinfo').html("<h4 style='color:red;margin-left: 12px;'>请将卡放置在卡机上</h4>"); datetime = new Date().getTime(); khf(); }
#去评论一下
标签:#记录代码
版权声明:本博客的所有原创内容皆为作品作者所有
转载请注明:来自ZJBLOG 链接:www.zjhuiwan.cn
+1
「万物皆有时,比如你我相遇」
感谢大佬打赏【请选择支付宝或微信,再选择金额】
使用微信扫描二维码完成支付