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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca