hardware_cmd.cpp 45.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
#include "stdafx.h"

#include "etradeclient/hardware/hardware_cmd.h"

#include <sstream>

#include <boost/algorithm/string.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/foreach.hpp>

#include "etradeclient/boost_patch/property_tree/json_parser.hpp" // WARNIING! Make sure to include our patched version.
#include "etradeclient/utility/logging.h"
#include "etradeclient/utility/string_converter.h"
#include "etradeclient/utility/application_config.h"

#include "etradeclient/hardware/pin_pad.h"
#include "etradeclient/hardware/id_card_reader.h"
#include "etradeclient/hardware/dili_card_device.h"
#include "etradeclient/hardware/bank_card_reader.h"
#include "etradeclient/hardware/password_machine.h"
#include "ETradeClient/utility/openssl_aes_cbc.h"
#include "ETradeClient/utility/DLBmpManager.h"
#include "ETradeClient/utility/string_converter.h"
#include "ETradeClient/utility/DLDes.h"
#include <vector>

namespace StatusCode
{
	static const std::string OK = ""; // 操作成功.

	static const std::string PINPAD_CONNECT_FAILED = "100"; // 连接密码键盘失败. 
	static const std::string PINPAD_TIMEOUT = "101"; // 用户密码输入超时. 
	static const std::string PINPAD_CANCELLED = "102"; // 用户取消密码输入. 
	static const std::string PINPAD_READ_FAILED = "103"; // 读取密码失败. 

	static const std::string ID_CARD_READER_CONNECT_FAILED = "200"; // 连接身份证读卡器失败. 
	static const std::string ID_CARD_READER_VERIFY_FAILED = "201"; // 身份证验证失败.
	static const std::string ID_CARD_READER_READ_FAILED = "202"; // 读取身份证信息失败.

	static const std::string CPU_CARD_DEVICE_CONNECT_FAILED = "300"; // 打开CPU卡读卡器失败. 
	static const std::string CPU_CARD_DEVICE_CANNOT_FIND_CARD = "301"; // 无法找到卡片,请放卡到读卡器上(或重新放置卡片).
	
	static const std::string DILI_CARD_DEVICE_ACTIVATE_CARD_FAILED = "302"; // 卡片激活失败, 请检查该卡是否已处于激活状态.
	static const std::string DILI_CARD_DEVICE_RESET_CARD_FAILED = "303"; // 卡片撤销激活失败, 请检查该卡是否已处于未激活状态.
	static const std::string DILI_CARD_DEVICE_READ_BASIC_INFO_FAILED = "304"; // 读取卡片基本信息失败.
	static const std::string DILI_CARD_DEVICE_READ_SERVICE_INFO_FAILED = "305"; // 读取卡片业务信息失败.
	static const std::string DILI_CARD_DEVICE_WRITE_SERVICE_INFO_FAILED = "306"; // 写入卡片业务信息失败.
	static const std::string DILI_CARD_DEVICE_WRITE_UNMATCHED_CARD = "307"; // 写卡卡片的序列号不匹配.
	static const std::string DILI_CARD_DEVICE_NEED_UPDATE = "308"; //卡片需要升级,请升级后继续使用。

	static const std::string PWD_MACHINE_CONNECT_FAILED = "401"; // 连接加密机失败.
	static const std::string PWD_MACHINE_GET_KEY_FAILED = "402"; // 从加密机读取密钥失败.

	static const std::string BANK_CARD_READ_CARD_NUM_FAILED = "501"; // 读取银行卡卡号失败.

	static const std::string PRINT_PARSE_DATA_FAILED = "1001"; //解析打印数据失败
	static const std::string PRINT_GET_MACHINE_DATA_FAILED = "1002"; //获取打印机参数失败
}

namespace EncryptTools
{
	int Encrypt(unsigned char* pSrc, unsigned char u8Len, unsigned char* pKey, unsigned char* pCiphertText)
	{
		int iResult = 0;

		uint8_t au8DataBlock[50][8] = { 0 };

		int iBlockCount = 0, iCoverPos = 0, iBlockNum = 0;
		iBlockCount = u8Len / 8;
		iCoverPos = u8Len % 8;

		while (iBlockCount > 0)
		{
			memcpy(au8DataBlock[iBlockNum], pSrc, 8);
			pSrc += 8;
			--iBlockCount;
			++iBlockNum;
		}

		if (iCoverPos)
		{
			memcpy(au8DataBlock[iBlockNum], pSrc, iCoverPos);
			au8DataBlock[iBlockNum][iCoverPos] = 0x80;
			++iCoverPos;
			for (int index = iCoverPos; iCoverPos < 8; ++iCoverPos)
			{
				au8DataBlock[iBlockNum][iCoverPos] = 0x00;
			}
		}
		else
		{
			--iBlockNum;
		}

		uint8_t au8KeyL[8] = { 0 }, au8KeyR[8] = { 0 };
		memcpy(au8KeyL, pKey, 8);
		memcpy(au8KeyR, pKey, 8);
		for (int index = 0; index <= iBlockNum; ++index)
		{
			uint8_t au8Cipher1[8] = { 0 }, au8Cipher2[8] = { 0 };
			DES(au8KeyL, au8DataBlock[index], au8Cipher1);
			_DES(au8KeyR, au8Cipher1, au8Cipher2);
			DES(au8KeyL, au8Cipher2, &pCiphertText[index * 8]);
		}

		return iResult;
	}

	bool HexToChar(unsigned char* pHex, int iHexLen, unsigned char* pChar)
	{
		bool bResult = true;
		if (pHex && iHexLen && pChar)
		{
			int iCharCount = 0;
			for (int index = 0; index < iHexLen; ++index)
			{
				char cNum[3] = { 0 };
				if (pHex[index] <= 0x0f)
				{
					pChar[iCharCount] = '0';
					++iCharCount;
					sprintf_s(cNum, "%X", pHex[index]);
					pChar[iCharCount] = cNum[0];
					++iCharCount;
				}
				else
				{
					sprintf_s(cNum, "%2X", pHex[index]);
					pChar[iCharCount] = cNum[0];
					++iCharCount;
					pChar[iCharCount] = cNum[1];
					++iCharCount;
				}
			}
		}
		return bResult;
	}

	bool CharToHex(unsigned char* pStr, unsigned char& cHex)
	{
		bool bResult = true;

		unsigned char aHex[2] = { 0 }, cTemp = 0;
		if (pStr)
		{
			int iCount = 2;
			do
			{
				char cStr = tolower(pStr[iCount - 1]);
				switch (cStr)
				{
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
				{
					cTemp = atoi(&cStr);
					break;
				}
				case 'a':
				{
					cTemp = 10;
					break;
				}
				case 'b':
				{
					cTemp = 11;
					break;
				}
				case 'c':
				{
					cTemp = 12;
					break;
				}
				case 'd':
				{
					cTemp = 13;
					break;
				}
				case 'e':
				{
					cTemp = 14;
					break;
				}
				case 'f':
				{
					cTemp = 15;
					break;
				}
				}
				aHex[iCount - 1] = cTemp;
				--iCount;
			} while (iCount);

			cHex = (aHex[0] << 4) + aHex[1];
		}
		else
		{
			bResult = false;
		}
		return bResult;
	}

	bool StringToHex(unsigned char* pStr, int iLen, unsigned char* pHex)
	{
		bool bResult = true;

		int iStrIndex = 0;
		int index = 0;
		while (bResult && iStrIndex < iLen)
		{
			bResult = CharToHex(&pStr[iStrIndex], pHex[index]);
			++index;
			iStrIndex += 2;
		}

		if (!bResult)
		{
			throw std::exception("9999");
		}
		/*for (int index = 0, iStrIndex = 0; iStrIndex < iLen; ++index, iStrIndex += 2)
		{
		CharToHex(&pStr[iStrIndex], pHex[index]);
		}*/

		return bResult;
	}
}

namespace 
{
	const PINPad& PINPad_()
	{
		static PINPad pin_pad;
		return pin_pad;
	}

	IDCardReader& IDCardReader_()
	{
		static IDCardReader id_card_reader;
		return id_card_reader;
	}

	const DILICard::RWDevice& DILICardRWDevice()
	{
		static DILICard::RWDevice dili_card_device;
		return dili_card_device;
	}

	const PWDMachine& PWDMachine_()
	{
		static PWDMachine pwd_machine;
		return pwd_machine;
	}

	const BankCardReader& BankCardReader_()
	{
		static BankCardReader bank_card_reader;
		return bank_card_reader;
	}

	std::string g_sCardNum;//用于办卡时,保证操作的卡片是同一张
}

ReadPINPadCmd::Reply ReadPINPadCmd::Execute(const std::string& input)
{
	LOG_TRACE(L"读取用户输入密码。");
	const uint8_t PWD_MAX_LEN = ApplicationConfig::Instance().PINPadPWDLen();
	const uint8_t TIMEOUT = ApplicationConfig::Instance().PINPadTimeout();
	auto& pin_pad = PINPad_();
	std::string pwd("");
	Reply reply;
	do
	{
		try
		{
			if (!pin_pad.Connect())
			{
				LOG_ERROR(L"连接密码键盘失败。");
				reply.error_code = StatusCode::PINPAD_CONNECT_FAILED;
				break;
			}
			pin_pad.DisplayBuiltInText(PINPad::BuiltInText::kEnterPWD);
			pin_pad.PlayVoice(PINPad::BuiltInVoice::kEnterPWD);
			pin_pad.SetPWDMaxLen(PWD_MAX_LEN);
			PINPad::StatusCode res = pin_pad.ReadUserInputPWD(PINPad::DispMode::kEncrypted, PINPad::DispLine::kL2, TIMEOUT, pwd);
			if (PINPad::StatusCode::kCancelled == res)
			{
				reply.error_code = StatusCode::PINPAD_CANCELLED;
				LOG_ERROR(L"用户取消密码输入。");
			}
			else if (PINPad::StatusCode::kTimeout == res)
			{
				reply.error_code = StatusCode::PINPAD_TIMEOUT;
				LOG_ERROR(L"用户输入密码超时。");
			}
			else if (PINPad::StatusCode::kUnknown == res)
			{
				reply.error_code = StatusCode::PINPAD_READ_FAILED;
				LOG_ERROR(L"读取用户输入密码失败,请确认密码键盘连接正常!");
			}
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取用户输入密码发生异常,异常信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::PINPAD_READ_FAILED;
			break;
		}
	} while (0);
	pin_pad.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"读取用户输入密码成功。");

	reply.data.put("password", pwd);
	return reply;
}

ReadPINPadCmd::Reply ReadIDCardCmd::Execute(const std::string& input)
{
	LOG_TRACE(L"读取身份证信息。");
	auto& id_card_reader = IDCardReader_();
	Reply reply;
	IDCardInfo id_card_info;

	uint8_t u8IDReaderType = ApplicationConfig::Instance().IDReaderType();

	switch (u8IDReaderType)
	{
	case 0:
	{
		do
		{
			try
			{
				if (!id_card_reader.Connect())
				{
					LOG_ERROR(L"建立身份证读卡器连接失败!");
					reply.error_code = StatusCode::ID_CARD_READER_CONNECT_FAILED;
					break;
				}
				if (!id_card_reader.VerifyCard())
				{
					LOG_ERROR(L"未找到身份证或身份证验证失败!");
					reply.error_code = StatusCode::ID_CARD_READER_VERIFY_FAILED;
					break;
				}
				id_card_info = id_card_reader.ReadCard();
			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"读取身份证信息失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::ID_CARD_READER_READ_FAILED;
				break;
			}
		} while (0);
		id_card_reader.Disconnect();
	}
	break;
	case 1:
	{
		do
		{
			try
			{
				if (!id_card_reader.SynConnect())
				{
					LOG_ERROR(L"建立身份证读卡器连接失败!");
					reply.error_code = StatusCode::ID_CARD_READER_CONNECT_FAILED;
					break;
				}
				if (!id_card_reader.SynFindCard())
				{
					LOG_ERROR(L"未找到身份证或身份证验证失败!");
					reply.error_code = StatusCode::ID_CARD_READER_VERIFY_FAILED;
					break;
				}
				id_card_info = id_card_reader.SynReadCard();
			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"读取身份证信息失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::ID_CARD_READER_READ_FAILED;
				break;
			}
		} while (0);
		id_card_reader.SynDisConnect();
	}
	break;
	}
	
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"读取身份证信息成功。");

	CDLBmpManager cBmp;
	string sBmpData = cBmp.ReadBmp(wstr_2_str(id_card_info.portrait_img_path).c_str());
	switch (u8IDReaderType)
	{
		case 0:
		{
			DeleteFile(id_card_info.portrait_img_path.c_str());
			wstring sPath = id_card_info.portrait_img_path.substr(0, id_card_info.portrait_img_path.size() - 6);
			DeleteFile((sPath + L"wz.txt").c_str());
			DeleteFile((sPath + L"xp.wlt").c_str());
		}
		break;
		case 1:
		{
			DeleteFile(id_card_info.portrait_img_path.c_str());
		}
		break;
	}
	

	reply.data.put("id", wstr_2_str(id_card_info.id_code));
	reply.data.put("name", wstr_2_str(id_card_info.name)); // Use 'wstr_2_str' to convert to UTF-8 string.
	reply.data.put("gender", wstr_2_str(id_card_info.gender));
	reply.data.put("nation", wstr_2_str(id_card_info.nation));
	reply.data.put("birthday", wstr_2_str(id_card_info.birth_date));
	reply.data.put("address", wstr_2_str(id_card_info.address));
	reply.data.put("portrait_img_path", wstr_2_str(id_card_info.portrait_img_path));
	reply.data.put("depart", wstr_2_str(id_card_info.depart));
	reply.data.put("start_date", wstr_2_str(id_card_info.start_date));
	reply.data.put("end_date", wstr_2_str(id_card_info.end_date));
	reply.data.put("img_data", sBmpData);
	return reply;
}

ReadPINPadCmd::Reply ActivateDILICardCmd::Execute(const std::string& input)
{
	Reply reply;
	LOG_TRACE(L"卡片激活。");
	
	std::string card_sn;
	std::string key_DCCK, key_F0015_DACK, key_F0015_DEAK, key_F0015_DAMK1, key_F0005_DAMK1;
	DILICard::BasicInfo card_basic_info;
	SecurityLevel slLevel = (SecurityLevel)ApplicationConfig::Instance().SecurityLevel();
	EncryptType etEncrypType = (EncryptType)ApplicationConfig::Instance().EncryptType();
	auto& dili_card_device = DILICardRWDevice();
	do 
	{
		try
		{
			dili_card_device.Connect();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"连接读卡器失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
			break;
		}
		try
		{
			dili_card_device.FindCard();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
		}

		DILICard::BasicInfo stuCardBasicInfo;
		try { stuCardBasicInfo = dili_card_device.ReadCardBasicInfo(); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取卡片基本信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_READ_BASIC_INFO_FAILED;
			break;
		}

		LOG_TRACE(L"计算SN。");
		card_sn = stuCardBasicInfo.chip_num + std::string("44494c49") + stuCardBasicInfo.chip_num;

		if (slLevel == HardwareCmd::SL_0)
		{
			stuCardBasicInfo.device_id = card_sn;
			card_basic_info = stuCardBasicInfo;
			reply.error_code = StatusCode::OK;
			break;
		}

		if (etEncrypType == ET_PWM)
		{
			LOG_TRACE(L"加密机模式计算主控秘钥。");
			const std::string PWD_MACHINE_IP = ApplicationConfig::Instance().PWDMachineIP();
			const uint32_t PWD_MACHINE_PORT = ApplicationConfig::Instance().PWDMachinePort();
			const uint8_t TIMEOUT = ApplicationConfig::Instance().PWDMachineTimeout();

			auto& pwd_machine = PWDMachine_();

			if (!pwd_machine.Connect(PWD_MACHINE_IP, PWD_MACHINE_PORT))
			{
				LOG_ERROR(L"连接加密机失败!");
				reply.error_code = StatusCode::PWD_MACHINE_CONNECT_FAILED;
			}

			try
			{
				key_DCCK = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kDCCK>(), card_sn, TIMEOUT);
				key_F0015_DACK = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DACK>(), card_sn, TIMEOUT);
				key_F0015_DEAK = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DEAK>(), card_sn, TIMEOUT);
				key_F0015_DAMK1 = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DAMK1>(), card_sn, TIMEOUT);
				key_F0005_DAMK1 = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DAMK1>(), card_sn, TIMEOUT);
			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"从加密机读取密钥失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
				break;
			}

			pwd_machine.Disconnect();
		}
		else if (etEncrypType == ET_DES)
		{
			LOG_TRACE(L"软加密模式计算主控秘钥。");
			try
			{
				const char* pDCCKDL = "43434bff43434bff";
				const char* pDACKDL = "41434bff41434bff";
				const char* pDEAKDL = "45414bff45414bff";
				const char* pDAMKDL = "414d4b31414d4b31";

				unsigned char aucCardSNHex[16] = { 0 };
				unsigned char aucDCCKDL[8] = { 0 }, aucDACKDL[8] = { 0 }, aucDEAKDL[8] = { 0 }, aucDAMKDL[8] = { 0 };
				EncryptTools::StringToHex((unsigned char*)pDCCKDL, 16, aucDCCKDL);
				EncryptTools::StringToHex((unsigned char*)pDACKDL, 16, aucDACKDL);
				EncryptTools::StringToHex((unsigned char*)pDEAKDL, 16, aucDEAKDL);
				EncryptTools::StringToHex((unsigned char*)pDAMKDL, 16, aucDAMKDL);
				EncryptTools::StringToHex((unsigned char*)card_sn.c_str(), 32, aucCardSNHex);

				unsigned char aucNewDAMKHex[16] = { 0 }, aucNewDCCKHex[16] = { 0 }, aucNewDACKHex[16] = { 0 }, aucNewDEAKHex[16] = { 0 };
				unsigned char aucNewDAMK[32] = { 0 }, aucNewDCCK[32] = { 0 }, aucNewDACK[32] = { 0 }, aucNewDEAK[32] = { 0 };

				EncryptTools::Encrypt(aucCardSNHex, 16, aucDAMKDL, aucNewDAMKHex);
				EncryptTools::Encrypt(aucCardSNHex, 16, aucDCCKDL, aucNewDCCKHex);
				EncryptTools::Encrypt(aucCardSNHex, 16, aucDACKDL, aucNewDACKHex);
				EncryptTools::Encrypt(aucCardSNHex, 16, aucDEAKDL, aucNewDEAKHex);

				EncryptTools::HexToChar(aucNewDAMKHex, 16, aucNewDAMK);
				EncryptTools::HexToChar(aucNewDCCKHex, 16, aucNewDCCK);
				EncryptTools::HexToChar(aucNewDACKHex, 16, aucNewDACK);
				EncryptTools::HexToChar(aucNewDEAKHex, 16, aucNewDEAK);

				std::string sDAMKKey((char*)aucNewDAMK, 32);
				std::string sDCCKKey((char*)aucNewDCCK, 32);
				std::string sDACKKey((char*)aucNewDACK, 32);
				std::string sDEAKKey((char*)aucNewDEAK, 32);

				key_F0005_DAMK1 = key_F0015_DAMK1 = sDAMKKey;
				key_DCCK = sDCCKKey;
				key_F0015_DACK = sDACKKey;
				key_F0015_DEAK = sDEAKKey;
				
			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"软加密密钥失败");
				reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
				break;
			}
		}

		try
		{
			dili_card_device.ActivateCard(card_sn, key_DCCK, key_F0015_DACK, key_F0015_DEAK, key_F0015_DAMK1);
			card_basic_info = dili_card_device.ReadCardBasicInfo();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"卡片激活失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_ACTIVATE_CARD_FAILED;
			break;
		}
		
	} while (0);
	
	dili_card_device.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"卡片激活成功。");

	reply.data.put("chipNo", card_basic_info.chip_num);
	reply.data.put("deviceId", card_basic_info.device_id);
	reply.data.put("type", card_basic_info.type_code);
	reply.data.put("issuerCode", card_basic_info.issuer_code);
	reply.data.put("verifyCode", card_basic_info.verify_code);
	return reply;
}

ReadPINPadCmd::Reply ResetDILICardCmd::Execute(const std::string& input)
{
	//const uint8_t BEEP_TIME = 20; // 20 * 10ms
	

	LOG_TRACE(L"卡片撤销激活。");
	auto& dili_card_device = DILICardRWDevice();
	
	Reply reply;
	std::string card_sn;
	std::string key_DCCK, key_F0015_DACK;
	DILICard::BasicInfo card_basic_info;

	SecurityLevel slLevel = (SecurityLevel)ApplicationConfig::Instance().SecurityLevel();
	EncryptType etEncrypType = (EncryptType)ApplicationConfig::Instance().EncryptType();

	do
	{
		try
		{
			dili_card_device.Connect();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"连接读卡器失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
			break;
		}
		try
		{
			dili_card_device.FindCard();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
		}

		DILICard::BasicInfo stuCardBasicInfo;
		try { stuCardBasicInfo = dili_card_device.ReadCardBasicInfo(); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取卡片基本信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_READ_BASIC_INFO_FAILED;
			break;
		}
		
		if (slLevel == HardwareCmd::SL_0)
		{
			card_basic_info = stuCardBasicInfo;
			reply.error_code = StatusCode::OK;
			break;
		}

		//card_sn = stuCardBasicInfo.device_id;

		LOG_TRACE(L"计算SN。");
		if (slLevel == HardwareCmd::SL_1)
		{
			card_sn = stuCardBasicInfo.device_id;
		}
		else if (slLevel == HardwareCmd::SL_2)
		{
			card_sn = stuCardBasicInfo.chip_num + "44494c49" + stuCardBasicInfo.chip_num;
		}

		if (etEncrypType == ET_PWM)
		{
			LOG_TRACE(L"加密机模式计算主控秘钥。");
			const std::string PWD_MACHINE_IP = ApplicationConfig::Instance().PWDMachineIP();
			const uint32_t PWD_MACHINE_PORT = ApplicationConfig::Instance().PWDMachinePort();
			const uint8_t TIMEOUT = ApplicationConfig::Instance().PWDMachineTimeout();

			auto& pwd_machine = PWDMachine_();

			if (!pwd_machine.Connect(PWD_MACHINE_IP, PWD_MACHINE_PORT))
			{
				LOG_ERROR(L"连接加密机失败!");
				reply.error_code = StatusCode::PWD_MACHINE_CONNECT_FAILED;
			}

			try
			{
				key_DCCK = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kDCCK>(), card_sn, TIMEOUT);
				key_F0015_DACK = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DACK>(), card_sn, TIMEOUT);
			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"从加密机读取密钥失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
				break;
			}

			pwd_machine.Disconnect();
		}
		else if (etEncrypType == ET_DES)
		{
			LOG_TRACE(L"软加密模式计算主控秘钥。");
			try
			{
				const char* pDCCKDL = "43434bff43434bff";
				const char* pDACKDL = "41434bff41434bff";

				unsigned char aucCardSNHex[16] = { 0 };
				unsigned char aucDCCKDL[8] = { 0 }, aucDACKDL[8] = { 0 };
				EncryptTools::StringToHex((unsigned char*)pDCCKDL, 16, aucDCCKDL);
				EncryptTools::StringToHex((unsigned char*)pDACKDL, 16, aucDACKDL);
				EncryptTools::StringToHex((unsigned char*)card_sn.c_str(), 32, aucCardSNHex);

				unsigned char aucNewDCCKHex[16] = { 0 }, aucNewDACKHex[16] = { 0 };
				unsigned char aucNewDCCK[32] = { 0 }, aucNewDACK[32] = { 0 };

				EncryptTools::Encrypt(aucCardSNHex, 16, aucDCCKDL, aucNewDCCKHex);
				EncryptTools::Encrypt(aucCardSNHex, 16, aucDACKDL, aucNewDACKHex);

				EncryptTools::HexToChar(aucNewDCCKHex, 16, aucNewDCCK);
				EncryptTools::HexToChar(aucNewDACKHex, 16, aucNewDACK);

				std::string sDCCKKey((char*)aucNewDCCK, 32);
				std::string sDACKKey((char*)aucNewDACK, 32);

				key_DCCK = sDCCKKey;
				key_F0015_DACK = sDACKKey;

			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"软加密密钥失败");
				reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
				break;
			}
		}

		if (slLevel == HardwareCmd::SL_2)
		{
			LOG_TRACE(L"验证卡片。");
			if (!dili_card_device.AuthenticationKey(key_DCCK))
			{
				LOG_FATAL(L"秘钥验证失败,卡片需要升级!");
				reply.error_code = StatusCode::DILI_CARD_DEVICE_NEED_UPDATE;
				break;
			}
		}
		

		try
		{
			dili_card_device.ResetCard(key_DCCK, key_F0015_DACK);
			card_basic_info = dili_card_device.ReadCardBasicInfo();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"卡片撤销激活失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_RESET_CARD_FAILED;
			break;
		}
	} while (0);
	dili_card_device.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"卡片撤销激活成功。");

	reply.data.put("chipNo", card_basic_info.chip_num);
	reply.data.put("deviceId", card_basic_info.device_id);
	reply.data.put("type", card_basic_info.type_code);
	reply.data.put("issuerCode", card_basic_info.issuer_code);
	reply.data.put("verifyCode", card_basic_info.verify_code);
	return reply;
}

ReadPINPadCmd::Reply ReadDILICardBasicInfoCmd::Execute(const std::string& input)
{
	LOG_TRACE(L"读取卡片基本信息。");
	auto& dili_card_device = DILICardRWDevice();
	Reply reply;
	DILICard::BasicInfo card_basic_info;
	do
	{
		try 
		{ 
			dili_card_device.Connect(); 
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"连接读卡器失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
			break;
		}
		try
		{
			dili_card_device.FindCard();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
		}

		try { card_basic_info = dili_card_device.ReadCardBasicInfo(); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取卡片基本信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_READ_BASIC_INFO_FAILED;
			break;
		}

		
		if (SL_2 == ApplicationConfig::Instance().SecurityLevel())
		{
			LOG_TRACE(L"计算主控秘钥。");
			std::string sSN = card_basic_info.chip_num + "44494c49" + card_basic_info.chip_num;
			std::string sDCCK;

			if (ET_DES == ApplicationConfig::Instance().EncryptType())
			{
				LOG_TRACE(L"软加密模式计算主控秘钥。");
				const char* pDCCKDL = "43434bff43434bff";

				unsigned char aucCardSNHex[16] = { 0 };
				unsigned char aucDCCKDL[8] = { 0 };
				EncryptTools::StringToHex((unsigned char*)pDCCKDL, 16, aucDCCKDL);
				EncryptTools::StringToHex((unsigned char*)sSN.c_str(), 32, aucCardSNHex);

				unsigned char aucNewDCCKHex[16] = { 0 };
				unsigned char aucNewDCCK[32] = { 0 };

				EncryptTools::Encrypt(aucCardSNHex, 16, aucDCCKDL, aucNewDCCKHex);

				EncryptTools::HexToChar(aucNewDCCKHex, 16, aucNewDCCK);

				std::string sDCCKKey((char*)aucNewDCCK, 32);
				
				sDCCK = sDCCKKey;
			}
			else if (ET_PWM == ApplicationConfig::Instance().EncryptType())
			{
				LOG_TRACE(L"加密机模式计算主控秘钥。");
				const std::string PWD_MACHINE_IP = ApplicationConfig::Instance().PWDMachineIP();
				const uint32_t PWD_MACHINE_PORT = ApplicationConfig::Instance().PWDMachinePort();
				const uint8_t TIMEOUT = ApplicationConfig::Instance().PWDMachineTimeout();

				auto& pwd_machine = PWDMachine_();

				if (!pwd_machine.Connect(PWD_MACHINE_IP, PWD_MACHINE_PORT))
				{
					LOG_ERROR(L"连接加密机失败!");
					reply.error_code = StatusCode::PWD_MACHINE_CONNECT_FAILED;
				}

				try
				{
					sDCCK = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kDCCK>(), sSN, TIMEOUT);
				}
				catch (std::exception& ex)
				{
					LOG_FATAL(L"从加密机读取密钥失败,错误信息: " + str_2_wstr(ex.what()));
					reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
					break;
				}
				pwd_machine.Disconnect();
			}

			LOG_TRACE(L"验证卡片。");
			if (!dili_card_device.AuthenticationKey(sDCCK))
			{
				LOG_FATAL(L"秘钥验证失败,卡片需要升级!");
				reply.error_code = StatusCode::DILI_CARD_DEVICE_NEED_UPDATE;
				break;
			}

		}
		
	} while (0);
	dili_card_device.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"读取卡片基本信息成功。");

	reply.data.put("chipNo", card_basic_info.chip_num);
	reply.data.put("deviceId", card_basic_info.device_id);
	reply.data.put("type", card_basic_info.type_code);
	reply.data.put("issuerCode", card_basic_info.issuer_code);
	reply.data.put("verifyCode", card_basic_info.verify_code);
	g_sCardNum = card_basic_info.device_id;
	return reply;
}

ReadPINPadCmd::Reply ReadDILICardServiceInfoCmd::Execute(const std::string& input)
{
	SecurityLevel slLevel = (SecurityLevel)ApplicationConfig::Instance().SecurityLevel();
	EncryptType etEncrypType = (EncryptType)ApplicationConfig::Instance().EncryptType();
	LOG_TRACE(L"读取卡片业务信息。");
	auto& dili_card_device = DILICardRWDevice();
	
	Reply reply;

	//安全等级都为0了,还读个毛的业务信息,直接返回!
	if (slLevel == HardwareCmd::SL_0)
	{
		reply.error_code == StatusCode::OK;
		LOG_TRACE(L"读取卡片业务信息成功。");
		return reply;
	}

	std::string key_r;
	std::string service_data;
	do
	{
		try
		{
			dili_card_device.Connect();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"连接读卡器失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
			break;
		}
		try
		{
			dili_card_device.FindCard();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
		}

		DILICard::BasicInfo stuCardBasicInfo;
		try { stuCardBasicInfo = dili_card_device.ReadCardBasicInfo(); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取卡片基本信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_READ_BASIC_INFO_FAILED;
			break;
		}

		LOG_TRACE(L"计算SN。");
		std::string sSN;
		if (slLevel == HardwareCmd::SL_1)
		{
			sSN = stuCardBasicInfo.device_id;
		}
		else if (slLevel == HardwareCmd::SL_2)
		{
			sSN = stuCardBasicInfo.chip_num + "44494c49" + stuCardBasicInfo.chip_num;
		}

		if (etEncrypType == ET_PWM)
		{
			LOG_TRACE(L"加密机模式计算主控秘钥。");
			auto& pwd_machine = PWDMachine_();
			const std::string PWD_MACHINE_IP = ApplicationConfig::Instance().PWDMachineIP();
			const uint32_t PWD_MACHINE_PORT = ApplicationConfig::Instance().PWDMachinePort();
			const uint8_t TIMEOUT = ApplicationConfig::Instance().PWDMachineTimeout();

			if (!pwd_machine.Connect(PWD_MACHINE_IP, PWD_MACHINE_PORT))
			{
				LOG_ERROR(L"连接加密机失败!");
				reply.error_code = StatusCode::PWD_MACHINE_CONNECT_FAILED;
				break;
			}

			try { key_r = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DEAK>(), sSN, TIMEOUT); }
			catch (std::exception& ex)
			{
				LOG_FATAL(L"从加密机读取密钥失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
				break;
			}

			pwd_machine.Disconnect();
		}
		else if (etEncrypType == ET_DES)
		{
			LOG_TRACE(L"软加密模式计算主控秘钥。");
			const char* pDEAKDL = "45414bff45414bff";

			unsigned char aucCardSNHex[16] = { 0 };
			unsigned char aucDEAKDL[8] = { 0 };
			EncryptTools::StringToHex((unsigned char*)pDEAKDL, 16, aucDEAKDL);
			EncryptTools::StringToHex((unsigned char*)sSN.c_str(), 32, aucCardSNHex);

			unsigned char aucNewDEAKHex[16] = { 0 };
			unsigned char aucNewDEAK[32] = { 0 };

			EncryptTools::Encrypt(aucCardSNHex, 16, aucDEAKDL, aucNewDEAKHex);

			EncryptTools::HexToChar(aucNewDEAKHex, 16, aucNewDEAK);

			std::string sDEAKKey((char*)aucNewDEAK, 32);

			key_r = sDEAKKey;
		}

		try { service_data = dili_card_device.ReadCardServiceInfo(key_r); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取卡片业务信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_READ_SERVICE_INFO_FAILED;
			break;
		}
	} while (0);
	
	dili_card_device.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"读取卡片业务信息成功。");

	reply.data.put("", service_data);
	return reply;
}

ReadPINPadCmd::Reply WriteDILICardServiceInfoCmd::Execute(const std::string& input)
{
	const char DATA_SPLITER = ':';
	SecurityLevel slLevel = (SecurityLevel)ApplicationConfig::Instance().SecurityLevel();
	EncryptType etEncrypType = (EncryptType)ApplicationConfig::Instance().EncryptType();

	LOG_TRACE(L"写入卡片业务信息。");
	auto& dili_card_device = DILICardRWDevice();
	
	Reply reply;
	//std::string card_sn;
	std::string key_w;
	do
	{
		try
		{
			dili_card_device.Connect();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"连接读卡器失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
			break;
		}

		//安全等级都为0了,还写个毛的业务信息,直接返回!
		if (slLevel == HardwareCmd::SL_0)
		{
			reply.error_code == StatusCode::OK;
			LOG_TRACE(L"读取卡片业务信息成功。");
			return reply;
		}

		try
		{
			dili_card_device.FindCard();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
		}

		DILICard::BasicInfo stuCardBasicInfo;
		try { stuCardBasicInfo = dili_card_device.ReadCardBasicInfo(); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取卡片基本信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_READ_BASIC_INFO_FAILED;
			break;
		}
		//card_sn = stuCardBasicInfo.device_id;

		LOG_TRACE(L"计算SN。");
		std::string sSN;
		if (slLevel == HardwareCmd::SL_1)
		{
			sSN = stuCardBasicInfo.device_id;
		}
		else if (slLevel == HardwareCmd::SL_2)
		{
			sSN = stuCardBasicInfo.chip_num + "44494c49" + stuCardBasicInfo.chip_num;
		}


		std::size_t index = input.find(DATA_SPLITER);
		if (std::string::npos == index) // NOT found.
		{
			LOG_ERROR(L"写入卡片业务信息失败,错误信息:请求数据错误。");
			reply.error_code = StatusCode::DILI_CARD_DEVICE_WRITE_SERVICE_INFO_FAILED;
			break;
		}
		std::string device_id = g_sCardNum;//用于办卡时,保证操作的卡片是同一张;
		std::string service_data = input.substr(index + 1, input.size() - index - 1);

		// 验证操作的是否是同一张卡,即device_id是否匹配
		if (!boost::iequals(sSN, device_id))
		{
			LOG_ERROR(L"写卡卡片的序列号不匹配!");
			reply.error_code = StatusCode::DILI_CARD_DEVICE_WRITE_UNMATCHED_CARD;
			break;
		}

		if (etEncrypType == ET_PWM)
		{
			LOG_TRACE(L"加密机模式计算主控秘钥。");
			auto& pwd_machine = PWDMachine_();

			const std::string PWD_MACHINE_IP = ApplicationConfig::Instance().PWDMachineIP();
			const uint32_t PWD_MACHINE_PORT = ApplicationConfig::Instance().PWDMachinePort();
			const uint8_t TIMEOUT = ApplicationConfig::Instance().PWDMachineTimeout();

			if (!pwd_machine.Connect(PWD_MACHINE_IP, PWD_MACHINE_PORT))
			{
				LOG_ERROR(L"连接加密机失败!");
				reply.error_code = StatusCode::PWD_MACHINE_CONNECT_FAILED;
				break;
			}

			try { key_w = pwd_machine.GetCardPassword(DILICard::CardKeyCode<DILICard::KeyCode::kF0015_DAMK1>(), sSN, TIMEOUT); }
			catch (std::exception& ex)
			{
				LOG_FATAL(L"从加密机读取密钥失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::PWD_MACHINE_GET_KEY_FAILED;
				break;
			}

			pwd_machine.Disconnect();
		}
		else if (etEncrypType == ET_DES)
		{
			LOG_TRACE(L"软加密模式计算15写秘钥。");
			const char* pDAMKDL = "414d4b31414d4b31";

			unsigned char aucCardSNHex[16] = { 0 };
			unsigned char aucDAMKDL[8] = { 0 };
			EncryptTools::StringToHex((unsigned char*)pDAMKDL, 16, aucDAMKDL);
			EncryptTools::StringToHex((unsigned char*)sSN.c_str(), 32, aucCardSNHex);

			unsigned char aucNewDAMKHex[16] = { 0 };
			unsigned char aucNewDAMK[32] = { 0 };

			EncryptTools::Encrypt(aucCardSNHex, 16, aucDAMKDL, aucNewDAMKHex);

			EncryptTools::HexToChar(aucNewDAMKHex, 16, aucNewDAMK);

			std::string sDAMKKey((char*)aucNewDAMK, 32);

			key_w = sDAMKKey;
		}
		
		try { dili_card_device.WriteCardServiceInfo(key_w, service_data); }
		catch (std::exception& ex)
		{
			LOG_FATAL(L"写入卡片业务信息失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::DILI_CARD_DEVICE_WRITE_SERVICE_INFO_FAILED;
			break;
		}

		
	} while (0);
	
	dili_card_device.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"写入卡片业务信息成功。");
	reply.data.put("", "");
	return reply;
}

ReadPINPadCmd::Reply ReadBankCardNumCmd::Execute(const std::string& input)
{
	LOG_TRACE(L"读取银行卡号。");
	auto& bank_card_reader = BankCardReader_();
	std::string bank_card_no("");
	Reply reply;
	do
	{
		try
		{
			if (!bank_card_reader.Connect())
			{
				LOG_ERROR(L"连接银行卡读卡器失败。");
				reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
				break;
			}
			bank_card_no = bank_card_reader.ReadBankCardNum();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取银行卡号失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::BANK_CARD_READ_CARD_NUM_FAILED;
			break;
		}
	} while (0);
	bank_card_reader.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"读取银行卡号成功。");

	reply.data.put("chipNo", bank_card_no);
	return reply;
}

ReadPINPadCmd::Reply ReadDILIAndBankCardNumCmd::Execute(const std::string& input)
{
	LOG_TRACE(L"读取园区卡或银行卡。");
	Reply reply;
	auto& dili_card_device = DILICardRWDevice();
	DILICard::BasicInfo card_basic_info;
	std::string sCardNum;
	do 
	{
		try
		{
			dili_card_device.Connect();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"连接读卡器失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CONNECT_FAILED;
			break;
		}
		try
		{
			dili_card_device.FindCard();
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
		}

		try 
		{
			card_basic_info = dili_card_device.ReadCardBasicInfo(); 
			sCardNum = card_basic_info.chip_num;
		}
		catch (std::exception& ex)
		{
			LOG_FATAL(L"读取园区卡卡片基本信息失败,错误信息: " + str_2_wstr(ex.what()));
			/*try
			{
			dili_card_device.FindCard();
			}
			catch (std::exception& ex)
			{
			LOG_FATAL(L"寻卡失败,错误信息: " + str_2_wstr(ex.what()));
			reply.error_code = StatusCode::CPU_CARD_DEVICE_CANNOT_FIND_CARD;
			break;
			}*/
			try
			{
				sCardNum = dili_card_device.ReadBankCardNum();

			}
			catch (std::exception& ex)
			{
				LOG_FATAL(L"读取银行卡号失败,错误信息: " + str_2_wstr(ex.what()));
				reply.error_code = StatusCode::BANK_CARD_READ_CARD_NUM_FAILED;
				break;
			}

		}
	} while (0);
	dili_card_device.Disconnect();
	if (boost::iequals(reply.error_code, StatusCode::OK))
		LOG_TRACE(L"读取卡片基本信息成功。");

	reply.data.put("chipNo", sCardNum);
	reply.data.put("deviceId", card_basic_info.device_id);
	reply.data.put("type", card_basic_info.type_code);
	reply.data.put("issuerCode", card_basic_info.issuer_code);
	reply.data.put("verifyCode", card_basic_info.verify_code);

	return reply;
}

const CString StatementNoText = L"结算单号:";
const CString TradeTimeText = L"交易时间:";
const CString BuyerNameText = L"买家姓名:";
const CString SalerNameText = L"卖家姓名:";
const CString CommNameText = L"商品名称";
const CString PriceText = L"单价";
const CString CountText = L"数量";
const CString SubtotalText = L"小计/元";
const CString ClerkText = L"结算员:";
const CString TotalMoneyText = L"总计:";


StylusPrinterCmd::Reply StylusPrinterCmd::Execute(const std::string& input)
{
	LOG_TRACE(L"开始打印");
	Reply reply;
	reply.error_code = StatusCode::OK;

	std::vector<OrderInfo> comm_vector;
	do 
	{
		LOG_TRACE(L"解析打印数据!");
		reply.error_code = ParseInput(const_cast<std::string&>(input), comm_vector);
		if (reply.error_code.compare(StatusCode::OK) != 0)
		{
			break;
		}
		reply.error_code = Print(comm_vector);
	} while (0);


	return reply;
}

std::string StylusPrinterCmd::Print(std::vector<OrderInfo> &order_vector)
{
	HDC print_dc;
	DOCINFO docin;

	//设置打印机相关参数
	docin.cbSize = sizeof(DOCINFO);
	docin.lpszDocName = L"ETrade";
	docin.lpszOutput = NULL;
	CPrintDialog print_dialog(TRUE, PD_ALLPAGES | PD_NOPAGENUMS, NULL);
	PRINTDLG *print_dlg_info = &print_dialog.m_pd;
	AfxGetApp()->GetPrinterDeviceDefaults(print_dlg_info);
	DEVMODE* lpDevMode = (DEVMODE*)::GlobalLock(print_dlg_info->hDevMode);
	if (!lpDevMode)
	{
		return StatusCode::PRINT_GET_MACHINE_DATA_FAILED;
	}
	::GlobalUnlock(print_dlg_info->hDevMode);
	lpDevMode->dmFields |= -1; 
	lpDevMode->dmPaperLength = 1397; //设定纸长为 139.7mm 
	lpDevMode->dmPaperWidth = 2410; //设定纸宽为 241mm 
	print_dc = print_dialog.CreatePrinterDC(); // 返回一个打印DC句柄 
	CDC *dc = new CDC;
	dc->Attach(print_dc);
	CFont title_font;
	title_font.CreatePointFont(350, L"宋体");
	CFont normal_font;
	normal_font.CreatePointFont(200, L"宋体");
	//
	
	const int FirstPageCommCount = 5;	//如果有多页第一页商品数为6
	const int NormalPageCommCount = 10;	//非第一页和最后一页,其他页的商品数目
	const int LastPageCommCount = 9;	//最后一页最多商品数量

	const int TitleCtrlHIBig = 700;		//表头不同组别控件横向间隔
	const int TitleCtrlHISmall = 150;	//表头同组别控件横向间隔
	const int TitleCtrlVI = 50;			//表头控件纵向间隔
	const int LineStartX = 100;			//横线起点x坐标
	const int LineLength = 1600;		//横线长度
	const int CommStartX = 200;			//商品信息起始x坐标
	const int CommToLineVI = 30;		//商品距横线纵向间隔
	const int NormalCommStartY = 40;	//非第一页商品信息起始y坐标
	const int CommHI = 300;				//商品信息横向间隔
	const int CommVI = 80;				//商品信息纵向间隔
	const CPoint PagePoint(1200, 870);	//页码坐标
	const CPoint TitleStartPoint(600, 50);//表名起始坐标
	const CPoint TitleCtrlStartPoint(100, 150);//表头控件起始坐标
	
	//开始打印
	StartDoc(print_dc, &docin); // 启动打印工作 
	for (auto iter : order_vector)
	{
		//打印阶段单头部信息
		StartPage(print_dc);

		int y_point = TitleCtrlStartPoint.y;
		int x_point = TitleCtrlStartPoint.x;

		dc->SelectObject(&title_font);
		dc->TextOut(TitleStartPoint.x, TitleStartPoint.y, iter.doc_name);

		dc->SelectObject(&normal_font);
		dc->TextOut(TitleCtrlStartPoint.x, TitleCtrlStartPoint.y, StatementNoText);
		x_point += TitleCtrlHISmall;
		dc->TextOut(x_point, y_point, iter.statements_no);

		x_point += TitleCtrlHIBig;
		dc->TextOut(x_point, y_point, TradeTimeText);
		x_point += TitleCtrlHISmall;
		dc->TextOut(x_point, y_point, iter.trade_time);

		x_point = TitleCtrlStartPoint.x;
		y_point += TitleCtrlVI;
		dc->TextOut(x_point, y_point, BuyerNameText);
		x_point += TitleCtrlHISmall;
		dc->TextOut(x_point, y_point, iter.buyer_name);

		x_point += TitleCtrlHIBig;
		dc->TextOut(x_point, y_point, SalerNameText);
		x_point += TitleCtrlHISmall;
		dc->TextOut(x_point, y_point, iter.seller_name);

		y_point += TitleCtrlVI;
		dc->MoveTo(LineStartX, y_point);
		x_point += LineLength;
		dc->LineTo(x_point, y_point);
		//

		//打印商品信息头
		x_point = CommStartX;
		y_point += CommToLineVI;
		dc->TextOut(x_point, y_point, CommNameText);
		x_point += CommHI;
		dc->TextOut(x_point, y_point, PriceText);
		x_point += CommHI;
		dc->TextOut(x_point, y_point, CountText);
		x_point += CommHI;
		dc->TextOut(x_point, y_point, SubtotalText);
		//

		//计算页数
		int comm_count = iter.comm_vector.size();
		int page_count = 0;
		if (comm_count <= FirstPageCommCount)
		{
			page_count = 1;
		}
		else 
		{
			page_count = (comm_count - FirstPageCommCount - 1) / NormalPageCommCount + 2;
		}
		//

		CString pagination;//页码文本

		// 打印第一页
		int first_page_comm = page_count > 1 ? FirstPageCommCount + 1 : comm_count; //第一页不分页最多有5条商品,分页最多有6条商品
		int comm_index = 0;
		for (; comm_index < first_page_comm; ++comm_index)
		{
			y_point += CommVI;
			x_point = CommStartX;
			dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].comm_name);
			x_point += CommHI;
			dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].price);
			x_point += CommHI;
			dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].count);
			x_point += CommHI;
			dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].total_money);
		}

		if (page_count > 1)
		{
			pagination.Format(L"%d/%d", 1, page_count);
			dc->TextOut(PagePoint.x, PagePoint.y, pagination);
			dc->EndPage();
		}
		//

		//打印除第一页和最后一页的其余页数
		for (int index = 1; index < page_count - 1; ++index)
		{
			StartPage(print_dc);
			y_point = NormalCommStartY;
			for (int comm = 0; comm < NormalPageCommCount; ++comm, ++comm_index)
			{
				x_point = CommStartX;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].comm_name);
				x_point += CommHI;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].price);
				x_point += CommHI;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].count);
				x_point += CommHI;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].total_money);
				y_point += CommVI;
			}
			pagination.Format(L"%d/%d", index + 1, page_count);
			dc->TextOut(PagePoint.x, PagePoint.y, pagination);
			dc->EndPage();
		}
		//

		//打印最后一页
		if (page_count > 1)
		{
			StartPage(print_dc);
			y_point = NormalCommStartY;
			for (; comm_index < comm_count; ++comm_index)
			{
				x_point = CommStartX;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].comm_name);
				x_point += CommHI;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].price);
				x_point += CommHI;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].count);
				x_point += CommHI;
				dc->TextOut(x_point, y_point, iter.comm_vector[comm_index].total_money);
				y_point += CommVI;
			}
		}
		
		x_point = LineStartX;
		y_point += CommVI;
		dc->MoveTo(x_point, y_point);
		x_point += LineLength;
		dc->LineTo(x_point, y_point);

		x_point = TitleCtrlStartPoint.x;
		y_point += CommToLineVI;
		dc->TextOut(x_point, y_point, ClerkText);
		x_point += TitleCtrlHISmall;
		dc->TextOut(x_point, y_point, iter.settlement_clerk);

		x_point += TitleCtrlHIBig;
		dc->TextOut(x_point, y_point, TotalMoneyText);
		x_point += TitleCtrlHISmall;
		dc->TextOut(x_point, y_point, iter.total_money);

		pagination.Format(L"%d/%d", page_count, page_count);
		dc->TextOut(PagePoint.x, PagePoint.y, pagination);

		EndPage(print_dc);
	}

	title_font.DeleteObject();
	normal_font.DeleteObject();
	
	EndDoc(print_dc);//结束打印
	DeleteDC(print_dc);
	delete dc;

	return StatusCode::OK;
}


static const std::string JSON_TAG_TITLE = "title";
static const std::string JSON_TAG_ORDERS = "orders";
static const std::string JSON_TAG_ORDER_ID = "orderId";
static const std::string JSON_TAG_PRODUCT_NAME = "productName";
static const std::string JSON_TAG_PRICE = "price";
static const std::string JSON_TAG_AMOUNT = "amount";
static const std::string JSON_TAG_MONEY = "money";
static const std::string JSON_TAG_STATEMENT_ID = "statementId";
static const std::string JSON_TAG_TRADE_TIME = "tradeTime";
static const std::string JSON_TAG_TRADE_BUYER_NAME = "buyerName";
static const std::string JSON_TAG_TRADE_SELLER_NAME = "sellerName";
static const std::string JSON_TAG_TRADE_USER_NAME = "userName";
static const std::string JSON_TAG_TRADE_TOTAL_MONEY = "totalMoney";
static const std::string JSON_TAG_TRADE_PRODUCTS = "products";


std::string StylusPrinterCmd::ParseInput(std::string &input, std::vector<OrderInfo> &order_vector)
{
	std::string result = StatusCode::OK;

	namespace PT = boost::property_tree;
	try //Parse the configuration file
	{
		PT::ptree ptree;
		std::stringstream ss;
		ss << input;
		PT::read_json(ss, ptree);
		std::string title = ptree.get<std::string>(JSON_TAG_TITLE);
		PT::ptree order_tree = ptree.get_child(JSON_TAG_ORDERS);

		BOOST_FOREACH(PT::ptree::value_type &v, order_tree)
		{
			OrderInfo order;
			order.doc_name = title.c_str();
			order.statements_no = v.second.get<std::string>(JSON_TAG_STATEMENT_ID).c_str();
			order.trade_time = v.second.get<std::string>(JSON_TAG_TRADE_TIME).c_str();
			order.buyer_name = v.second.get<std::string>(JSON_TAG_TRADE_BUYER_NAME).c_str();
			order.seller_name = v.second.get<std::string>(JSON_TAG_TRADE_SELLER_NAME).c_str();
			order.settlement_clerk = v.second.get<std::string>(JSON_TAG_TRADE_USER_NAME).c_str();
			order.total_money = v.second.get<std::string>(JSON_TAG_TRADE_TOTAL_MONEY).c_str();

			PT::ptree products_ptree = v.second.get_child(JSON_TAG_TRADE_PRODUCTS);
			BOOST_FOREACH(PT::ptree::value_type &v, products_ptree)
			{
				CommInfo comm_info;
				comm_info.comm_id = v.second.get<long>(JSON_TAG_ORDER_ID);
				comm_info.comm_name = v.second.get<std::string>(JSON_TAG_PRODUCT_NAME).c_str();
				comm_info.price = v.second.get<std::string>(JSON_TAG_PRICE).c_str();
				comm_info.count = v.second.get<std::string>(JSON_TAG_AMOUNT).c_str();
				comm_info.total_money = v.second.get<std::string>(JSON_TAG_MONEY).c_str();
				order.comm_vector.push_back(comm_info);
			}
			order_vector.push_back(order);
		}
	}
	catch (...)
	{
		LOG_ERROR(L"解析服务器返回的打印信息时出错!请确认返回数据不为空,返回的数据格式为正确的Json格式!");
		result = StatusCode::PRINT_PARSE_DATA_FAILED;
	}
	return result;
}