Java调用海康HCUsbSDK制卡刷卡读卡

2024-02-19 13:18

本文主要是介绍Java调用海康HCUsbSDK制卡刷卡读卡,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

根据HCUsbSDK接口文档和JAVADEMO开发的一个发卡、读卡、刷卡的程序

淘宝买的空白UID卡,卡里需要存入员工工号和卡编号,在web后台来操作制卡、刷卡

简单记录下,方便以后开发相似的功能可以直接拿去用

发卡器型号是【海康威视DS-K1F100-D8E】

卡.jpg

Mifare卡操作

image.png

登录设备、激活卡、密码验证

/*** @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 {@Overridepublic 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();
}

 

 

 

 

这篇关于Java调用海康HCUsbSDK制卡刷卡读卡的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/724785

相关文章

Java实现Excel与HTML互转

《Java实现Excel与HTML互转》Excel是一种电子表格格式,而HTM则是一种用于创建网页的标记语言,虽然两者在用途上存在差异,但有时我们需要将数据从一种格式转换为另一种格式,下面我们就来看看... Excel是一种电子表格格式,广泛用于数据处理和分析,而HTM则是一种用于创建网页的标记语言。虽然两

java图像识别工具类(ImageRecognitionUtils)使用实例详解

《java图像识别工具类(ImageRecognitionUtils)使用实例详解》:本文主要介绍如何在Java中使用OpenCV进行图像识别,包括图像加载、预处理、分类、人脸检测和特征提取等步骤... 目录前言1. 图像识别的背景与作用2. 设计目标3. 项目依赖4. 设计与实现 ImageRecogni

Java中Springboot集成Kafka实现消息发送和接收功能

《Java中Springboot集成Kafka实现消息发送和接收功能》Kafka是一个高吞吐量的分布式发布-订阅消息系统,主要用于处理大规模数据流,它由生产者、消费者、主题、分区和代理等组件构成,Ka... 目录一、Kafka 简介二、Kafka 功能三、POM依赖四、配置文件五、生产者六、消费者一、Kaf

Java访问修饰符public、private、protected及默认访问权限详解

《Java访问修饰符public、private、protected及默认访问权限详解》:本文主要介绍Java访问修饰符public、private、protected及默认访问权限的相关资料,每... 目录前言1. public 访问修饰符特点:示例:适用场景:2. private 访问修饰符特点:示例:

详解Java如何向http/https接口发出请求

《详解Java如何向http/https接口发出请求》这篇文章主要为大家详细介绍了Java如何实现向http/https接口发出请求,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用Java发送web请求所用到的包都在java.net下,在具体使用时可以用如下代码,你可以把它封装成一

SpringBoot使用Apache Tika检测敏感信息

《SpringBoot使用ApacheTika检测敏感信息》ApacheTika是一个功能强大的内容分析工具,它能够从多种文件格式中提取文本、元数据以及其他结构化信息,下面我们来看看如何使用Ap... 目录Tika 主要特性1. 多格式支持2. 自动文件类型检测3. 文本和元数据提取4. 支持 OCR(光学

Java内存泄漏问题的排查、优化与最佳实践

《Java内存泄漏问题的排查、优化与最佳实践》在Java开发中,内存泄漏是一个常见且令人头疼的问题,内存泄漏指的是程序在运行过程中,已经不再使用的对象没有被及时释放,从而导致内存占用不断增加,最终... 目录引言1. 什么是内存泄漏?常见的内存泄漏情况2. 如何排查 Java 中的内存泄漏?2.1 使用 J

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

Java 字符数组转字符串的常用方法

《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu

java脚本使用不同版本jdk的说明介绍

《java脚本使用不同版本jdk的说明介绍》本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用... 目录Java脚本使用不同版本jdk的说明1.使用ScriptEngine执行javascript2.