防止以后要用,记录下
后端代码
@Controller
@RequestMapping(value = "cardMake")
public class CardMakeController extends BaseController {private String menuId ; // 菜单地址(权限用)@Resource(name = "memberService")private MemberManager memberService;@Resource(name = "cardRecordService")private CardRecordManager cardRecordService;private String msg ="";/*** @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 {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));}/*** Hex字符串转byte** @param inHex 待转换的Hex字符串* @return 转换后的byte*/public static byte hexToByte(String inHex) {return (byte)Integer.parseInt(inHex, 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;}/*** hex字符串转byte数组** @param inHex 待转换的Hex字符串* @return 转换后的byte数组结果*/public static byte[] hexToByteArray(String inHex) {int hexlen = inHex.length();byte[] result;if (hexlen % 2 == 1) {// 奇数hexlen++;result = new byte[(hexlen / 2)];inHex = "0" + inHex;} else {// 偶数result = new byte[(hexlen / 2)];}int j = 0;for (int i = 0; i < hexlen; i += 2) {result[j] = hexToByte(inHex.substring(i, i + 2));j++;}return result;}private static final char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};public static void main(String[] args) throws UnsupportedEncodingException {/* NativeLong lUserID = login();active(lUserID);valid(lUserID);Long cardNo = Tools.getUniqueId();System.out.println("写入卡号:" + cardNo);write(lUserID, str2HexStr("1101-1"));read(lUserID);Boolean ss =hcusbsdk.USB_SDK_Logout(lUserID);System.out.println("退出登录:"+ss);*/String hexStr ="0000000000000000000000000001880c";char[] chars = hexStr.toCharArray();int len = chars.length/2;byte[] bytes = new byte[len];for (int i = 0; i < len; i++) {int x = i*2;bytes[i] = (byte)Integer.parseInt(String.valueOf(new char[]{chars[x], chars[x+1]}), 16);}System.out.println(bytes);String str = bytes2hexStr(bytes);System.out.println(str);long a = Long.parseLong(str,16);System.out.println(a);}/*** @param: [content]* @return: int* @description: 十六进制转十进制*/public static int covert(String content){int number=0;String [] HighLetter = {"A","B","C","D","E","F"};Map<String,Integer> map = new HashMap<>();for(int i = 0;i <= 9;i++){map.put(i+"",i);}for(int j= 10;j<HighLetter.length+10;j++){map.put(HighLetter[j-10],j);}String[]str = new String[content.length()];for(int i = 0; i < str.length; i++){str[i] = content.substring(i,i+1);}for(int i = 0; i < str.length; i++){number += map.get(str[i])*Math.pow(16,str.length-1-i);}return number;}/** byte[]数组转十六进制*/public static String bytes2hexStr(byte[] bytes) {int len = bytes.length;if (len == 0) {return null;}char[] cbuf = new char[len * 2];for (int i = 0; i < len; i++) {int x = i * 2;cbuf[x] = HEX_CHARS[(bytes[i] >>> 4) & 0xf];cbuf[x + 1] = HEX_CHARS[bytes[i] & 0xf];}return new String(cbuf);}@RequestMapping(value = "/toEdit.do")public ModelAndView toEdit() {ModelAndView mv = this.getModelAndView();PageData pd = this.getPageData();try {pd = memberService.findById(pd.getString("id"));mv.setViewName("jjc/member/make");mv.addObject("pd", pd);} catch (Exception e) {logger.error(e.toString(), e);}return mv;}@RequestMapping(value = "/toShow.do")public ModelAndView toShow() {ModelAndView mv = this.getModelAndView();PageData pd = this.getPageData();try {mv.setViewName("jjc/member/show");mv.addObject("pd", pd);} catch (Exception e) {logger.error(e.toString(), e);}return mv;}@RequestMapping(value = "/toShowRecord.do")public ModelAndView toShowRecord() {ModelAndView mv = this.getModelAndView();PageData pd = this.getPageData();try {mv.setViewName("jjc/member/showRecord");mv.addObject("pd", pd);} catch (Exception e) {logger.error(e.toString(), e);}return mv;}@RequestMapping(value = "/showmakeRecord.do")@ResponseBodypublic 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;}@RequestMapping(value = "/getKh.do")@ResponseBodypublic 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 = "/logout.do")@ResponseBodypublic Object logout() {PageData pd = this.getPageData();Boolean ss =hcusbsdk.USB_SDK_Logout(new NativeLong(Long.valueOf(pd.getString("lUserID"))));System.out.println("退出登录:"+ss);return Ret.ok("获取成功").data(true).build();}@RequestMapping(value = "/make.do")@ResponseBodypublic 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 = "/showmake.do")@ResponseBodypublic Object showmake() {Map<String, Object> map = new HashMap<String, Object>();PageData pd = this.getPageData();NativeLong lUserID = login();try {String readKh = active(lUserID);if(Tools.isEmpty(readKh)){map.put("cardid", "");}else{valid(lUserID);String cardid = read(lUserID);System.out.println("读卡内容:"+cardid);if(Tools.notEmpty(cardid)&&!cardid.equals("0")){pd.put("number", cardid.substring(0,4));List<PageData> list = memberService.listAll(pd);map.put("info", list.get(0));map.put("cardid", cardid);}else{map.put("cardid", "0");}}Boolean ss =hcusbsdk.USB_SDK_Logout(lUserID);} catch (Exception e) {hcusbsdk.USB_SDK_Logout(lUserID);logger.error(e.toString(), e);}return map;}
读卡前端代码
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();}
写卡前端代码
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');}}