WmAceKG-x86.cpp 107 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <atlbase.h>
#include <atlconv.h>
#include <sqlite3.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/pkcs12.h>
#include <HPSocket.h>
#include <fstream>
#include <cassert>
#include <string>
#include <queue>
#include <map>
#include <time.h>
#include <sys/timeb.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <algorithm>
zzx's avatar
zzx committed
20 21
#include <cmath>

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <direct.h>
#include <WinSock2.h>
#include <Iphlpapi.h>
//#include <thread>
//#include <mutex>
#include "CppSQLite3.h"
#include "libhnsw.h"
#include "WmAceKG-x86.h"
#include "CommonTools.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/pointer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "DirectoryDel.h"
#include "SocketServer.h"
#include "SocketClient.h"
#include "ThreadPool.h"
#include "spdlog/spdlog.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "ini.h"
#include "videopipe.h"
zzx's avatar
zzx committed
45
#include "libretri.h"
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include "CharacterConversion.h"
#include "MarkSave.h"
#include <vector>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

#include <ncnn/benchmark.h>
#include <ncnn/platform.h>
#include <ncnn/net.h>
#include "libstrret.h"
  // #undef NCNN_VULKAN

#pragma comment(lib, "IPHLPAPI.lib")

zzx's avatar
zzx committed
62 63
#define ERROR_SIMILARITY 0.95//纠错的相似度
#define FEATURE_COUNT 128 //特征的个数
64 65 66 67
#define DATABASE_SIZE 120000  //索引大小
#define APPOINT_LIBRARY 0  //指定目录
#define NCNN_USING 1		//ncnn

68 69 70
#define FRESH_DETECT 0
#define PREVENT_LOSS 1

zzx's avatar
zzx committed
71 72
//纠错存 code和id
unordered_map<string, int>reassion;
73
string realProductCodes[10];
74 75
int rest_in = 0;
int rest_out = 0;
76 77 78 79 80
using namespace std;
using namespace cv;
using namespace rapidjson;


zzx's avatar
zzx committed
81
struct VIDEO_FRAME_INFO
82 83 84 85 86 87 88 89 90 91 92 93 94 95
{
	UINT64 timestamp; // 时间戳
	Mat img;
};

struct DETECT_RESULT
{
	char productCodes[100];
	char sessionId[100];
	bool state;
};

struct FOOD_PARAM_DATA
{
zzx's avatar
zzx committed
96 97 98 99 100 101 102 103 104 105 106
	Mat back;													// 用于创建算法的初始化图像,一般是裁剪具有标志物的空秤盘
	string back_mat_path;										// 加载temp的路径

	bool end_thread;											// 控制视频流线程

	Rect roi;													// 识别区域
	bool has_roi;												// 是否启用识别区域

	int max_in_frame_queue;										// 最大缓存图片数
	queue<VIDEO_FRAME_INFO> frame_in;							// q1
	queue<libvideopipe::FOOD_VIDEOPIPE_INPUT>  videopipe_in;	// q2
107
	vector<VIDEO_FRAME_INFO>  frame_out;	// q2
zzx's avatar
zzx committed
108 109 110 111 112 113 114 115 116

	HANDLE hMutex;												//互斥量
	bool debug_mode;											// 是否启用调试 

	libvideopipe::MotionVideoPipe* mvp;							//追踪器

	queue<DETECT_RESULT> result_queue;							//结果队列
	int queue_max;												//结果队列上限

zzx's avatar
zzx committed
117
	string detect_image_path;
zzx's avatar
zzx committed
118
	bool scan;													//是否扫描
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
};

//返回结果
DETECT_RESULT result;
// step0: 初始化param
FOOD_PARAM_DATA param_in;

//文件的路径
const char* gszFile = "featurexYz.db";
const char* log_path = "logs/daily.txt";
std::shared_ptr<spdlog::logger> logger;
vector<float>solve_cost;
//索引
libhnsw::Index* idx = nullptr;

// 测试提交
// api列表
// 租户
string tenantStr;
// mac地址
string macAddr;
// 开发版本
string dev;
float filterScore = 0.85f;
float markDownScoreLimit = 0.9f;
144 145 146

int mode;

147 148 149 150 151 152 153 154 155 156 157 158 159 160
// 版本文本
const char* dev_ini_path = "dev.ini";
// 租户json
const char* json_tenant_path = "tenant.json";
// posId json
const char* posId_json_path = "posId.json";
// pos机注册api
const char* wmpos_bind_url = "%s.wmdigit.com/%s/newretail/api/pos/machine/bind";
// pos机解绑api
const char* wmpos_unbind_url = "%s.wmdigit.com/%s/newretail/api/pos/machine/unbind?mac=%s&snNo=%s";
// 保存称重记录
const char* save_record_url = "%s.wmdigit.com/%s/newretail/api/search/product/saveImageIdentify";
// 上传文件
const char* upload_file_url = "%s.wmdigit.com/%s/newretail/api/dfs/upload";
161 162
// 上传视频流的照片文件
const char* upload_file1_url = "%s.wmdigit.com/%s/newretail/api/dfs/upload2";
163 164 165 166 167 168
// 重置mac地址为有线网卡的mac 地址
const char* reset_mac_url = "%s.wmdigit.com/%s/newretail/api/pos/machine/updateMacByOld";
// 验证租户是否正确
const char* query_tenant_url = "%s.wmdigit.com/0/newretail/api/sys/org/queryTenant?tenantCode=%s";
// pos机试用api
const char* wmpos_probation_url = "%s.wmdigit.com/free-sample/newretail/api/pos/probationSdk/download?macAddress=%s";
zzx's avatar
zzx committed
169 170
//自动配图
const char* pictured_json_url = "%s.wmdigit.com/%s/newretail/api/mall/productMatch/match";
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

// 是否连接网络
bool connectNet = true;

//用于打开摄像头
cv::VideoCapture cap;
//// 一帧图片
//cv::Mat frame;
// 三帧图片
cv::Mat frame_pipe;
cv::Mat frame_one;
cv::Mat frame_two;
cv::Mat frame_thr;
// 裁剪的坐标值
int x, y, width, height;
int ai_x, ai_y, ai_width, ai_height;
// 摄像头序号
int cameraNum;
// 存储的json文件路径
const char* json_path = "coordinate.json";

// 是否验证过
bool authed = false;

195
string wmphoto_path = "WMPhoto";
196 197 198

// 获取dll所在目录
EXTERN_C IMAGE_DOS_HEADER __ImageBase;//申明为全局变量
199

200 201 202 203 204 205 206 207

// posId
string posId;

string mac_date = "2021-11-24 14:00:00";

libbm25::Index *match_map = nullptr;

zzx's avatar
zzx committed
208
//视频流算法参数
209 210
float MarkThreshold;
float AiMarkThreshold;
211

zzx's avatar
zzx committed
212 213

//是否使用gpu和ai
214
bool using_ai = true;
215
bool drive_ai = 1;
zzx's avatar
zzx committed
216 217

//元芒加速库句柄
218
void* handle = nullptr;
zzx's avatar
zzx committed
219 220

//debug模式
221
bool debug = false;
zzx's avatar
zzx committed
222 223

//抓图线程安全
224
HANDLE PhotoMutex;
zzx's avatar
zzx committed
225 226

//视频流是否正在处理图片(因为出现过处理一帧需要2s的问题,改了算法逻辑,添加了该参数)
227
bool in_image = false;
zzx's avatar
zzx committed
228 229

//是否已经返回前端结果(因为前端node的线程问题,添加了改参数,防止一直访问结果队列。(待优化???))
230
bool re_ret = false;
zzx's avatar
zzx committed
231 232 233

//扫描开始,停止视频流
bool plu_input_stop_video = false;
234 235 236

//视频流是否初始化完成
bool g_video_init = false;
237

238
//防止多次初始化
239
bool init_finish = false;
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
/*******************************Socket相关************************************/
bool openSync = false;
// TCP服务端口
int port = 10083;
// 最大连接数
const int maxConnectionCount = 20;
// 真实Ip
char realIp[16];
// 连接Ids
vector<CONNID> connIds;

// udp节点
UdpNodeListenerImpl udpNodeListener;
CUdpNodePtr udp_node(&udpNodeListener);

// tcp客户端
ClientListenerImpl clientListener;
CTcpPackClientPtr s_pclient(&clientListener);

// tcp服务端
ServerListenerImpl serverListener;
CTcpPackServerPtr s_pserver(&serverListener);


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
void getFiles(string path, vector<string>& files)
{
	//文件句柄
	intptr_t hFile = 0;
	//文件信息
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

//删除日志
int delete_daily()
{
	string filePath = "logs\\";
	vector<string> files;

	getFiles(filePath, files);

	int size = files.size();
	sort(files.begin(), files.end());
	if (size > 7) {
		for (int i = 0; i < size - 7; i++) {
			remove(files[i].c_str());
		}
	}
	return 0;
}

307 308 309 310 311 312 313 314 315 316
float average_cost()
{
	if(solve_cost.size() == 0 && (!in_image))
	{
		return 67;
	}
	while (solve_cost.size() == 0 && in_image)
	{
		Sleep(100);
	}
317
	float ret = solve_cost[0];
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
	solve_cost.erase(solve_cost.begin());
	if (ret < 67) 
	{
		ret = 67;
	}
	return ret;
}


void sendTcpServerCreateBroadCast(const char* data) {
	BOOL result = udp_node->SendCast((const BYTE*)data, strlen(data));
	if (!result) {
		int code = SYS_GetLastError();
		logger->info("当前ip:{},发送广播消息失败,错误码:{}", realIp, code);
	}
	else {
		logger->info("ip:{},UDP广播消息:{},发送成功", realIp, data);
	}
}

void createUdpNode() {
	if (!udp_node->Start(char2TCAHR(realIp), 11184, CM_BROADCAST, L"255.255.255.255")) {
		int code = GetLastError();
		logger->info("当前ip:{},创建udp节点错误,错误码:{}", realIp, code);
	}
	else {
		logger->info("ip:{},UDP节点创建成功", realIp);
	}
}

void createClient(LPCTSTR remoteAddress) {
	if (s_pclient->HasStarted()) {
		s_pclient->Stop();
	}
	// 3. Start component object
	s_pclient->SetMaxPackSize(1024 * 100);
	if (!s_pclient->Start(remoteAddress, port)) {
		int code = GetLastError();
		logger->info("当前ip:{},socket客户端启动失败,错误码:{}", realIp, code);
	}
	else {
		logger->info("ip:{},socket客户端启动成功", realIp);
	}
}

// 1 代表索引添加 2 代表商品模型关系添加 
//{\"type\":1,\"feature\":\"1\",\"productCode\":\"1\",\"modelCodes\":[{\"modelCode\":1,\"productCode\":\"123\"},{\"modelCode\":2,\"productCode\":\"345\"}]}
void sendClientModelMessage(vector<int> modelCodes, vector<string> productCodes) {
	if (modelCodes.size() == 0) {
		return;
	}
	// 等待2秒客户端连接
	Sleep(2000);
	if (s_pclient->HasStarted()) {
		Document d;
		Document::AllocatorType& a = d.GetAllocator();
		Value a1(kArrayType);
		for (unsigned int i = 0; i < modelCodes.size(); i++)
		{
			Value o1(kObjectType);
			o1.AddMember("productCode", Value(productCodes[i], a), a);
			o1.AddMember("modelCode", Value(modelCodes[i]), a);
			a1.PushBack(o1, a);
		}
		Pointer("/type").Set(d, 2);
		Pointer("/modelCodes").Set(d, a1);
		StringBuffer buffer;
		Writer<StringBuffer> writer(buffer);
		d.Accept(writer);

		logger->info(buffer.GetString());
		s_pclient->Send((const BYTE*)buffer.GetString(), buffer.GetLength());
	}
	else if (s_pserver->HasStarted()) {
		Document d;
		Document::AllocatorType& a = d.GetAllocator();
		Value a1(kArrayType);
		for (unsigned int i = 0; i < modelCodes.size(); i++)
		{
			Value o1(kObjectType);
			o1.AddMember("productCode", Value(productCodes[i], a), a); 
			o1.AddMember("modelCode", Value(modelCodes[i]), a); 
			a1.PushBack(o1, a);
		}
		Pointer("/type").Set(d, 2);
		Pointer("/modelCodes").Set(d, a1);
		StringBuffer buffer;
		Writer<StringBuffer> writer(buffer);
		d.Accept(writer);

		logger->info(buffer.GetString());

		for (unsigned long i = 0; i < connIds.size(); i++)
		{
412
			s_pserver->Send(connIds[i], (const BYTE*)buffer.GetString(), buffer.GetLength());
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
		}
	}
	else {
		// do nothing
	}
}

int initTcpServer()
{
	if (!openSync) {
		return 0;
	}
	// 设置真实ip
	GetIp(realIp);

	// 创建udp节点
	createUdpNode();

	// 创建tcp服务
	s_pserver->SetMaxConnectionCount(maxConnectionCount);
	s_pserver->SetMaxPackSize(1024 * 100);
	if (!s_pserver->Start(char2TCAHR(realIp), port)) {
		int code = GetLastError();
		logger->info("当前ip:{},socket服务端启动失败,错误码:{}", realIp, code);
	}
	else {
		logger->info("当前ip:{},socket服务端启动成功", realIp);
		sendTcpServerCreateBroadCast("hello i am tcp server");
	}
	return 0;
}

// 获取mac地址
void GetMacByGetAdaptersAddresses(std::string& macOUT)
{
	bool ret = false;

	ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
	PIP_ADAPTER_INFO pAdapterInfo = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
	if (pAdapterInfo == NULL)
		return;

	if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
	{
		free(pAdapterInfo);
		pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
		if (pAdapterInfo == NULL)
			return;
	}
	if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == NO_ERROR)
	{
		for (PIP_ADAPTER_INFO pAdapter = pAdapterInfo; pAdapter != NULL; pAdapter = pAdapter->Next)
		{
			// 确保是以太网
			if (pAdapter->Type != MIB_IF_TYPE_ETHERNET || pAdapter->Type == 71 || strstr(pAdapter->Description, "Bluetooth") > 0)
				continue;
			
			// 过滤vpn 和 虚拟机
			if (strstr(pAdapter->Description, "VPN") > 0 || strstr(pAdapter->Description, "Virtual") > 0 || strstr(pAdapter->Description, "UU") > 0) {
				continue;
			}

			// 确保MAC地址的长度为 00-00-00-00-00-00
			if (pAdapter->AddressLength != 6)
				continue;

			char acMAC[32];
			sprintf_s(acMAC, 32, "%02X-%02X-%02X-%02X-%02X-%02X",
				int(pAdapter->Address[0]),
				int(pAdapter->Address[1]),
				int(pAdapter->Address[2]),
				int(pAdapter->Address[3]),
				int(pAdapter->Address[4]),
				int(pAdapter->Address[5]));

			cout << "找到了有线网卡: " << acMAC << endl;
			cout << "当前类型为: " << pAdapter->Type << endl;
			cout << "当前描述为: " << pAdapter->Description << endl;
			macOUT = acMAC;
			ret = true;
		}
		// 没有找到有线网卡 开始设置无线网卡
		if (!ret) {
			for (PIP_ADAPTER_INFO pAdapter = pAdapterInfo; pAdapter != NULL; pAdapter = pAdapter->Next)
			{
				// 确保是以太网
				if (pAdapter->Type == MIB_IF_TYPE_ETHERNET || pAdapter->Type != 71 || strstr(pAdapter->Description, "Bluetooth") > 0)
					continue;

				// 过滤vpn 和 虚拟机
				if (strstr(pAdapter->Description, "VPN") > 0 || strstr(pAdapter->Description, "Virtual") > 0 || strstr(pAdapter->Description, "UU") > 0) {
					continue;
				}

				// 确保MAC地址的长度为 00-00-00-00-00-00
				if (pAdapter->AddressLength != 6)
					continue;

				char acMAC[32];
				sprintf_s(acMAC, 32, "%02X-%02X-%02X-%02X-%02X-%02X",
					int(pAdapter->Address[0]),
					int(pAdapter->Address[1]),
					int(pAdapter->Address[2]),
					int(pAdapter->Address[3]),
					int(pAdapter->Address[4]),
					int(pAdapter->Address[5]));

				cout << "找到了无线网卡: " << acMAC << endl;
				cout << "当前类型为: " << pAdapter->Type << endl;
				cout << "当前描述为: " << pAdapter->Description << endl;
				macOUT = acMAC;
				break;
			}
		}
	}
	free(pAdapterInfo);
}

/**
 * 字符分割算法 ,
 * @param str
 * @param data
 * @return
 */
void split(char* str, float* data) {
	const char* regex = ",";
	str = strtok(str, regex);
	int i = 0;
	while (str) {
		data[i] = atof(str);
		i++;
		str = strtok(NULL, regex);
	}
}

inline bool exists_file(const std::string& name) {
	if (FILE* file = fopen(name.c_str(), "r")) {
		fclose(file);
		return true;
	}
	else {
		return false;
	}
}

/**
 * 字符分割算法 int
 * @param str
 * @param data
 * @return
 */
void splitStringColon(char* str, string* data) {
	const char* regex = ":";
	str = strtok(str, regex);
	int i = 0;
	while (str) {
		data[i] = str;
		i++;
		str = strtok(NULL, regex);
	}
}

/**
 * 字符分割算法 int
 * @param str
 * @param data
 * @return
 */
void splitString(char* str, string* data) {
	const char* regex = ",";
	str = strtok(str, regex);
	int i = 0;
	while (str) {
		data[i] = str;
		i++;
		str = strtok(NULL, regex);
	}
}

// 读取文件
string readTxt(string file)
{
	ifstream infile;
	infile.open(file.data());   //将文件流对象与文件连接起来 
	assert(infile.is_open());   //若失败,则输出错误消息,并终止程序运行 

	string s;
	while (getline(infile, s))
	{
		cout << s << endl;
	}
	infile.close();             //关闭文件输入流 
	return s;
}

void del_rod(char* src)
{
	char* fp = src;
	while (*src) {
		if (*src != '-') {
			*fp = *src;
			fp++;
		}
		src++;
	}
	*fp = '\0'; //封闭字符串
}

void del_rod(string& str)
{
	// 因为str.c_str() 是const的,不能直接修改,
	// 所以要复制一个临时的,然后修改后换回去
	char tmp[18 + 1];
	memcpy(&tmp, str.c_str(), str.size() + 1);
	del_rod(tmp);    // 重载del_rod,调用C风格的函数
	str = tmp;
}

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
std::string tool_get_dll_path()
{
	char dir[_MAX_DIR];
	char drive[_MAX_DRIVE];
	char DllPath[MAX_PATH];
	GetModuleFileNameA((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath));


	//截取DLL所在目录(去掉DLL文件名)
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];
	_splitpath(DllPath, drive, dir, fname, ext);

	std::string new_dir = std::string(drive) + std::string(dir);
	return new_dir;
}

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
time_t StringToDatetime(string str)
{
	char* cha = (char*)str.data();             // 将string转换成char*。
	tm tm_;                                    // 定义tm结构体。
	int year, month, day, hour, minute, second;// 定义时间的各个int临时变量。
	sscanf(cha, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);// 将string存储的日期时间,转换为int临时变量。
	tm_.tm_year = year - 1900;                 // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。
	tm_.tm_mon = month - 1;                    // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。
	tm_.tm_mday = day;                         // 日。
	tm_.tm_hour = hour;                        // 时。
	tm_.tm_min = minute;                       // 分。
	tm_.tm_sec = second;                       // 秒。
	tm_.tm_isdst = 0;                          // 非夏令时。
	time_t t_ = mktime(&tm_);                  // 将tm结构体转换成time_t格式。
	return t_;                                 // 返回值。
}

int GetFileInfo(string& strPath,time_t& createTime)
{
	struct _stat tmpInfo;
	if (_stat(strPath.c_str(), &tmpInfo) != 0)
	{
		return FALSE;
	}
	createTime = tmpInfo.st_ctime;
	return TRUE;
}


// 私钥解密  
std::string rsa_pri_decrypt(const std::string& cipherText, const std::string& priKey)
{
	std::string strRet;
	RSA* rsa = RSA_new();
	BIO* keybio;
	// keybio = BIO_new_mem_buf((unsigned char*)priKey.c_str(), -1);
	keybio = BIO_new_file(priKey.c_str(), "r");

	// 此处有三种方法
	// 1, 读取内存里生成的密钥对,再从内存生成rsa
	// 2, 读取磁盘里生成的密钥对文本文件,在从内存生成rsa
	// 3,直接从读取文件指针生成rsa
	rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);

	int len = RSA_size(rsa);
	char* decryptedText = (char*)malloc(len + 1);
	memset(decryptedText, 0, len + 1);

	// 解密函数
	int ret = RSA_private_decrypt(cipherText.length(), (const unsigned char*)cipherText.c_str(), (unsigned char*)decryptedText, rsa, RSA_PKCS1_PADDING);
	if (ret >= 0)
		strRet = std::string(decryptedText, ret);

	// 释放内存
	free(decryptedText);
	BIO_free_all(keybio);
	RSA_free(rsa);

	return strRet;
}

static inline bool is_base64(unsigned char c) {
	return (isalnum(c) || (c == '+') || (c == '/'));
}

// base64 解码
std::string base64Decode(std::string const& encoded_string) {
	std::string base64_chars =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz"
		"0123456789+/";
	size_t in_len = encoded_string.size();
	int i = 0;
	int j = 0;
	int in_ = 0;
	unsigned char char_array_4[4], char_array_3[3];
	std::string ret;

	while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
		char_array_4[i++] = encoded_string[in_]; in_++;
		if (i == 4) {
			for (i = 0; i < 4; i++)
				char_array_4[i] = base64_chars.find(char_array_4[i]) & 0xff;

			char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
			char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
			char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

			for (i = 0; (i < 3); i++)
				ret += char_array_3[i];
			i = 0;
		}
	}

	if (i) {
		for (j = 0; j < i; j++)
			char_array_4[j] = base64_chars.find(char_array_4[j]) & 0xff;

		char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
		char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);

		for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
	}

	return ret;
}

void loadIndexFromDB(CppSQLite3DB& db, libhnsw::Index* newIndex) {
	double start_time = clock();//1计时开始
	if (db.tableExists("feature_code")) {
758
		CppSQLite3Query q = db.execQuery("select id,feature from feature_code where deleted = 0");
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
		while (!q.eof())
		{
			float features[FEATURE_COUNT];
			int id = q.getIntField(0);
			const char* sql_feature = q.getStringField(1);
			char* c = const_cast<char*>(sql_feature);
			split(c, features);
			newIndex->Addsample(features, id - 1);
			q.nextRow();
		}
		q.finalize();
	}
	double end_time = clock();//1计时开始
	logger->info("load index elapsed {}ms\n", end_time - start_time);
}

zzx's avatar
zzx committed
775
int retri_Init() {
776 777 778
	logger->info("初始化元芒图像加速库");
	int ret = 0;
	if (drive_ai == 0) {
779
		ret = RETRI_Init(NULL, RETRI_DEVICE::RETRI_GPU, &handle);
780 781 782
	}
	else
	{
783
		ret = RETRI_Init(NULL, RETRI_DEVICE::RETRI_CPU, &handle);
784 785
	}
	if (ret != 0) {
786
		logger->info("初始化元芒图像加速库失败:{0:x}",ret);
787 788 789 790 791 792 793 794 795 796 797
		return -1;
	}
	else {
		logger->info("初始化元芒图像加速库成功");
		return 0;
	}
}
/**
 * 初始化faiss索引
 */
int WMAI_API Init() {
798

799 800 801 802 803 804
	if (init_finish == true)
	{
		logger->info("二次初始化");
		return 0;
	}

805 806 807 808 809 810 811 812 813 814 815 816 817
#if APPOINT_LIBRARY
	char DllPath[MAX_PATH] = { 0 };
	GetModuleFileNameA((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath));
	//截取DLL所在目录(去掉DLL文件名)
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];
	_splitpath(DllPath, drive, dir, fname, ext);

	string new_dir = string(drive) + dir;
	char* ini_path = new char[MAX_PATH];
	strcpy(ini_path, (new_dir + "dev.ini").c_str());
	dev_ini_path = ini_path;

818

819
	char* gsz_file = new char[MAX_PATH];
820 821 822
	string ascll_gsz_file = new_dir + "featurexYz.db";
	string utf_8_gsz_file = ASCII2UTF_8(ascll_gsz_file);
	strcpy(gsz_file, utf_8_gsz_file.c_str());
823 824
	gszFile = gsz_file;

825 826 827 828 829 830 831 832

	char* imagePath = new char[MAX_PATH];
	string ascll_imagePath = new_dir + "AiImageWmAceKG.db";
	string utf_8_imagePath = ASCII2UTF_8(ascll_imagePath);
	strcpy(imagePath, utf_8_imagePath.c_str());
	wmimage = imagePath;


833 834 835 836
	char* tenant_path = new char[MAX_PATH];
	strcpy(tenant_path, (new_dir + "tenant.json").c_str());
	json_tenant_path = tenant_path;

837

838 839 840 841
	char* posId_path = new char[MAX_PATH];
	strcpy(posId_path, (new_dir + "posId.json").c_str());
	posId_json_path = posId_path;

842

843 844 845 846
	char* coordinate = new char[MAX_PATH];
	strcpy(coordinate, (new_dir + "coordinate.json").c_str());
	json_path = coordinate;

847

848
	char* logPath = new char[MAX_PATH];
849
	strcpy(logPath, (new_dir + "logs/daily.txt").c_str());
850 851
	log_path = logPath;

852

853 854 855 856 857 858 859
	char* wmphotoPath = new char[MAX_PATH];
	strcpy(wmphotoPath, (new_dir + "WMphoto").c_str());
	wmphoto_path = wmphotoPath;

#else
	// do nothing
#endif // 0
860

861 862 863 864
	if (logger == nullptr)
	{
		logger = spdlog::daily_logger_mt("daily_logger", log_path, 2, 7);
		logger->flush_on(spdlog::level::info);
865
		delete_daily();
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

	FILE* fp = fopen(json_path, "rb"); // 非 Windows 平台使用 "r"
	if (fp) {
		char readBuffer[65536];
		FileReadStream is(fp, readBuffer, sizeof(readBuffer));
		Document d;
		d.ParseStream(is);
		x = d["x"].GetInt();
		y = d["y"].GetInt();
		width = d["width"].GetInt();
		height = d["height"].GetInt();
		ai_x = d["ai_x"].GetInt();
		ai_y = d["ai_y"].GetInt();
		ai_width = d["ai_width"].GetInt();
		ai_height = d["ai_height"].GetInt();
		cameraNum = d["cameraNum"].GetInt();
		fclose(fp);
	}
	FILE* fp2 = fopen(json_tenant_path, "rb"); // 非 Windows 平台使用 "r"
	if (fp2) {
		char readBuffer2[65536];
		FileReadStream is2(fp2, readBuffer2, sizeof(readBuffer2));
		Document d2;
		d2.ParseStream(is2);
		tenantStr = d2["demo"].GetString();
		fclose(fp2);
	}
	FILE* fp3 = fopen(posId_json_path, "rb"); // 非 Windows 平台使用 "r"
	if (fp3) {
		char readBuffer3[65536];
		FileReadStream is3(fp3, readBuffer3, sizeof(readBuffer3));
		Document d3;
		d3.ParseStream(is3);
		posId = d3["posId"].GetString();
		fclose(fp3);
	}
	GetMacByGetAdaptersAddresses(macAddr);
	del_rod(macAddr);
	mINI::INIFile file(dev_ini_path);
	mINI::INIStructure ini;
	file.read(ini);
	dev = ini["default"]["dev"];
909 910
	mode = atoi(ini["default"]["mode"].c_str());
	drive_ai = atoi(ini["default"]["drive_ai"].c_str());
911 912 913 914 915
	openSync = atoi(ini["default"]["openSync"].c_str());
	filterScore = atof(ini["default"]["filterScore"].c_str());

	// 开始创建tcp服务端
	initTcpServer();
zzx's avatar
zzx committed
916

917
	//初始化图形加速库
zzx's avatar
zzx committed
918 919 920
	int ret = retri_Init();
	logger->info("图形加速库初始化结果:{0:x}", ret);

921 922 923 924 925
	//添加索引
	float idx_start = clock();
	CppSQLite3DB db;
	db.open(gszFile);
	db.setBusyTimeout(5000);
926 927 928 929 930 931 932 933 934 935 936 937

	if (db.tableExists("feature_code")) {
		CppSQLite3Query queryColumn3 = db.execQuery("select * from sqlite_master where name='feature_code' and sql like '%deleted%';");
		if (queryColumn3.eof()) {
			//没有 "列名" 列
			//新增列
			db.execDML("ALTER TABLE feature_code ADD COLUMN deleted INTEGER DEFAULT 0;");
		}
	}


	idx =  new libhnsw::Index(FEATURE_COUNT, DATABASE_SIZE, libhnsw::BRUTE_FORCE_KNN_CF,libhnsw::INNER_PRODUCT);
938 939 940 941 942 943 944 945 946 947 948 949 950
	loadIndexFromDB(db, idx);
	float idx_end = clock();
	logger->info("idx init cost:{}",idx_end - idx_start);

	if (db.tableExists("product_record")) {
		CppSQLite3Buffer deleteProductRecord;
		deleteProductRecord.format("delete from product_record;");
		int row = db.execDML(deleteProductRecord);
		logger->info("{} row product_record has been deleted", row);
	}

	db.execDML("CREATE TABLE IF NOT EXISTS product_model (id integer PRIMARY KEY AUTOINCREMENT, product_code text NOT NULL, model_code integer NOT NULL);");
	db.execDML("CREATE TABLE IF NOT EXISTS product_model_counting (id integer PRIMARY KEY AUTOINCREMENT, product_code text NOT NULL, model_code integer NOT NULL, num integer NOT NULL);");
951
	db.execDML("CREATE TABLE IF NOT EXISTS feature_code (id integer PRIMARY KEY AUTOINCREMENT, code text NOT NULL, feature text NOT NULL, update_time TIMESTAMP DEFAULT NULL, deleted integer DEFAULT NULL);");
952
	db.execDML("CREATE TABLE IF NOT EXISTS feed_back_record (id integer PRIMARY KEY AUTOINCREMENT, code text NOT NULL, session_id text NOT NULL, hit integer NOT NULL);");
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


	//检测表单
	if (!db.tableExists("record_count")) {
		db.execDML("CREATE TABLE IF NOT EXISTS record_count (id integer PRIMARY KEY AUTOINCREMENT, count integer NOT NULL);");;
	}

	//检测record_count表达数据
	CppSQLite3Buffer measure;
	measure.format("select count(*) from record_count;");
	CppSQLite3Query q = db.execQuery(measure);
	ret = 0;
	while (!q.eof())
	{
		ret = q.getIntField(0);
		break;
	}
	q.finalize();
	logger->info("record_count ret :{}", ret);
	if (ret == 0)
	{
		int count = 1;
		CppSQLite3Buffer insert;
		insert.format("insert into record_count(count) values (%d)", count);
		db.execDML(insert);
	}

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
	if (!db.tableExists("product_record")) {
		db.execDML("CREATE TABLE IF NOT EXISTS product_record (id integer PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, model_code INTEGER NOT NULL, score REAL NOT NULL,feature_value TEXT NOT NULL,image_path TEXT NOT NULL,product_ids TEXT NOT NULL,real_codes TEXT NOT NULL,time TEXT NOT NULL);");
		db.execDML("CREATE INDEX session_id_index ON product_record(session_id);");
	}
	// sqlite_master 为sqlite隐藏系统表
	CppSQLite3Query queryColumn = db.execQuery("select * from sqlite_master where name='product_record' and sql like '%real_codes%';");
	if (queryColumn.eof()) {
		//没有 "列名" 列
		//新增列
		db.execDML("ALTER TABLE product_record ADD COLUMN real_codes TEXT NOT NULL;");
	}
	CppSQLite3Query queryColumn2 = db.execQuery("select * from sqlite_master where name='feature_code' and sql like '%update_time%';");
	if (queryColumn2.eof()) {
		//没有 "列名" 列
		//新增列
		db.execDML("ALTER TABLE feature_code ADD COLUMN update_time TIMESTAMP DEFAULT NULL;");
		CppSQLite3Buffer updateFeatureCodeTime;
997
		updateFeatureCodeTime.format("update feature_code set update_time = datetime('now','localtime');");
998 999 1000 1001 1002
		db.execDML(updateFeatureCodeTime);
	}
	queryColumn.finalize();
	queryColumn2.finalize();
	db.close();
1003 1004

	string dir_path = tool_get_dll_path();
1005
	wmphoto_path = dir_path + "WMPhoto";
1006
	DeleteDirectory(wmphoto_path.c_str());
1007 1008

	init_finish = true;
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
	logger->info("init end");
	return  0;
}



// Tenengrad模糊检测
float TenengradBlurDetect(const cv::Mat& srcimg) {
	cv::Mat x_grad, y_grad, src_gray;
	cv::cvtColor(srcimg, src_gray, 6);
	cv::Sobel(src_gray, x_grad, CV_16S, 1, 0, 3);
	cv::Sobel(src_gray, y_grad, CV_16S, 0, 1, 3);

	cv::Mat abs_grad_x, abs_grad_y;

	int width = srcimg.cols;
	int height = srcimg.rows;
	int step = srcimg.step;
	cv::convertScaleAbs(x_grad, abs_grad_x);
	cv::convertScaleAbs(y_grad, abs_grad_y);

	uchar* udata_x = abs_grad_x.data;
	uchar* udata_y = abs_grad_y.data;
	float sum = 0;
	for (int j = 0; j < height; j++) {
		for (int i = 0; i < width; i++) {
			float udata_x_d = udata_x[j * width + i] / 255;
			float udata_y_d = udata_y[j * width + i] / 255;
			sum = sum + udata_x_d * udata_x_d + udata_y_d * udata_y_d;
		}
	}
	// printf("TenengradBlurDetect=%f ms\n", ti);
	return 100 * sum / (width * height);
}

// 获取mac地址
bool checkMac(std::string& decryptText)
{
	bool ret = false;

	ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
	PIP_ADAPTER_ADDRESSES pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
	if (pAddresses == NULL)
		return false;
	// Make an initial call to GetAdaptersAddresses to get the necessary size into the ulOutBufLen variable
	if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW)
	{
		free(pAddresses);
		pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
		if (pAddresses == NULL)
			return false;
	}

	if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &outBufLen) == NO_ERROR)
	{
		// If successful, output some information from the data we received
		for (PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses; pCurrAddresses != NULL; pCurrAddresses = pCurrAddresses->Next)
		{
			// 确保MAC地址的长度为 00-00-00-00-00-00
			if (pCurrAddresses->PhysicalAddressLength != 6)
				continue;
			char acMAC[32];
			sprintf(acMAC, "%02X-%02X-%02X-%02X-%02X-%02X",
				int(pCurrAddresses->PhysicalAddress[0]),
				int(pCurrAddresses->PhysicalAddress[1]),
				int(pCurrAddresses->PhysicalAddress[2]),
				int(pCurrAddresses->PhysicalAddress[3]),
				int(pCurrAddresses->PhysicalAddress[4]),
				int(pCurrAddresses->PhysicalAddress[5]));
			if (decryptText == acMAC) {
				ret = true;
				break;
			}
		}
	}

	free(pAddresses);
	return ret;
}


// 判断是否授权
bool probationAuth() {
	logger->info("没有找到正式密钥 开始使用试用密钥");
#if APPOINT_LIBRARY
	string new_dir = string(drive) + dir;
1095 1096
	string pprikey = new_dir + "pprikey.pem";
	string pwmkey = new_dir + "pwmkey.wm";
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
#else
	string pprikey = "pprikey.pem";
	string pwmkey = "pwmkey.wm";
#endif // 0

	if (!exists_file(pprikey) || !exists_file(pwmkey)) {
		return false;
	}
	string str = readTxt(pwmkey);
	string encryptText = base64Decode((char*)str.c_str());
	string decryptText = rsa_pri_decrypt(encryptText, pprikey);

	string macTime[2];
	char* decryptStr = const_cast<char*>(decryptText.c_str());
1111
	logger->info("decryptStr:{}", decryptStr);
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
	splitStringColon(decryptStr, macTime);
	// 校验mac地址
	bool authorize = checkMac(macTime[0]);
	if (!authorize) {
		// mac不一致直接过期
		return authorize;
	}
	// 校验有效期
	long expireTime;
	std::stringstream sstr;
	sstr << macTime[1];
	sstr >> expireTime;
	// 过期时间unix时间戳 - 当前unix时间戳 > 0 || 过期时间unix时间戳 - 当前unix时间戳 > 15
	std::time_t t = std::time(0);
	long timeSpace = expireTime - t;
	if (timeSpace > 0 && timeSpace <= 15 * 86400) {
		int lastDays = timeSpace / 86400;
		logger->info("剩余使用天数为{}", lastDays);
		return true;
	}
	return false;
}

// 判断是否授权
bool authorize() {
#if APPOINT_LIBRARY
	string new_dir = string(drive) + dir;
	string prikey = new_dir + "prikey.pem";
	string wmkey = new_dir + "wmkey.wm";
#else
	string prikey = "prikey.pem";
	string wmkey = "wmkey.wm";
#endif // 0

	if (!exists_file(prikey) || !exists_file(wmkey)) {
		return probationAuth();
	}
	string str = readTxt(wmkey);
	string encryptText = base64Decode((char*)str.c_str());
	string decryptText = rsa_pri_decrypt(encryptText, prikey);
	bool authorize = checkMac(decryptText);
	return authorize;
}

1156
static int k;
1157
int detect_squeezenet(const cv::Mat& bgr, std::vector<float>& cls_scores, float* rhs)
1158 1159 1160 1161 1162 1163 1164
{
	// step1:初始化handle
	logger->info("进入元芒图像加速库");
	if (handle == nullptr) {
		logger->info("初始化元芒图像加速库");
		int hr = 0;
		if (drive_ai == 0) {
zzx's avatar
zzx committed
1165
			hr = RETRI_Init(NULL, RETRI_DEVICE::RETRI_CPU, &handle);
1166 1167 1168
		}
		else
		{
1169
			hr = RETRI_Init(NULL, RETRI_DEVICE::RETRI_CPU, &handle);
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
		}
		if (hr != 0)
		{
			logger->info("元芒图形加速库初始化失败!error code:{0:x}\n", hr);
			return -1;
		}
		else
		{
			logger->info("元芒图形加速库初始化成功");
		}
	}
	// step2:推理
zzx's avatar
zzx committed
1182
	RETRI_INPUT in_img;
1183
	in_img.img = bgr.clone();
zzx's avatar
zzx committed
1184
	RETRI_OUTPUT clsretri_output;
1185 1186
	cv::imwrite("input.jpg", in_img.img);
	string inimg = tool_get_dll_path()+"in-image";
1187
	
1188 1189 1190 1191 1192 1193 1194
	_mkdir(inimg.c_str());
	char image_name[120] = {};
	sprintf(image_name, "\\%lld.jpg", k);
	std::string dir_path = inimg+"\\"+image_name;
	imwrite(dir_path, in_img.img);
	k++;

1195
	int s_time = clock();
zzx's avatar
zzx committed
1196
	int hr = RETRI_Process(in_img, &clsretri_output, handle);
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
	int e_time = clock();
	if (hr != 0)
	{
		logger->info("元芒图形加速库推理失败!error code:{}\n", hr);
		return -2;
	}
	logger->info("元芒图形加速库耗时:{}ms\n", e_time - s_time);

	//step3.返回结果
	for (int i = 0; i < FEATURE_COUNT; i++)
	{
		rhs[i] = clsretri_output.feat[i];
	}
	return 0;
}

// 保存top10条记录 并且打印
int save_topk(const std::vector<float>& cls_scores, int topk, int* index, float* scores)
{
	//index = new int[topk];
	//scores = new float[topk];
	std::vector< std::pair<float, int> > vec;
	// partial sort topk with index
	int size = cls_scores.size();
	vec.resize(size);
	for (int i = 0; i < size; i++)
	{
		vec[i] = std::make_pair(cls_scores[i], i);
	}

	std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
		std::greater< std::pair<float, int> >());

	// print topk and score
	for (int i = 0; i < topk; i++)
	{
		scores[i] = vec[i].first;
		index[i] = vec[i].second;
		//float score = vec[i].first;
		//int index = vec[i].second;
		//logger->info("{} = {}\n", index[i], scores[i]);
	}
	return 0;
}

float calculSimilar(float v1[], float v2[], int size) {
	// assert(v1.size() == v2.size());
	double ret = 0.0, mod1 = 0.0, mod2 = 0.0;
	for (int i = 0; i < size; ++i) {
		ret += v1[i] * v2[i];
		mod1 += v1[i] * v1[i];
		mod2 += v2[i] * v2[i];
	}
	if (mod1 == 0 || mod2 == 0) return 0;
	return (ret / sqrt(mod1) / sqrt(mod2) + 1) / 2.0;
}

1254

1255 1256 1257 1258 1259 1260 1261 1262
int compare_feature_faiss(float* rhs, string* code, int& biggerNinety) {
	try {
		CppSQLite3DB db;
		db.open(gszFile);
		if (!db.tableExists("feature_code")) {
			return 0;
		}
		//  ============ 搜索 ===================
zzx's avatar
zzx committed
1263
		reassion.clear();
1264
		double startTime1 = clock();//1计时开始
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275

		//logger->info("detect feature:{}", rhs);

		//char rhs_data[FEATURE_COUNT * 10] = { };
	/*	for (int i = 0; i < FEATURE_COUNT; ++i)
		{
			sprintf(rhs_data + strlen(rhs_data), "%f,", rhs[i]);
		}
		logger->info("detect feature:{}", rhs_data);*/
		
		std::vector<std::pair<float, int>>res = idx->Search(rhs,6);
1276 1277 1278
		for (unsigned int j = 0; j < res.size(); j++)
		{
			std::pair<float, int> r = res[j];
1279
			//logger->info("res[{}]:id {},prob {}\n", j, r.second, 1-r.first);
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
			int number = r.second;

			// 商品向量
			float features[FEATURE_COUNT];
			//获得对应的商品代码

			number = number + 1;

			CppSQLite3Buffer selectFeatureCode;
			selectFeatureCode.format("select code,feature,id from feature_code where id = %d;", number);
			CppSQLite3Query q = db.execQuery(selectFeatureCode);
			string sql_code;
			int id;
			while (!q.eof())
			{
				sql_code = q.getStringField(0);
				const char* sql_feature = q.fieldValue(1);
				id = q.getIntField(2);
				char* c = const_cast<char*>(sql_feature);
				split(c, features);
				q.nextRow();
1301
				//logger->info("idx;{} feature:{}", j, sql_feature);
1302 1303
			}
			q.finalize();
1304 1305 1306 1307 1308 1309

			float sim = calculSimilar(rhs, features, FEATURE_COUNT);
			
			logger->info("{} is {}", sql_code.c_str(), sim);
			if (sim > filterScore)
			{
1310
				code[j + 3] = sql_code;
zzx's avatar
zzx committed
1311
				reassion.emplace(sql_code, id);
1312 1313
				// 如果大于过滤值 说明该向量最近被使用 修改最后更新时间
				CppSQLite3Buffer updateFeatureCode;
1314
				updateFeatureCode.format("update feature_code set update_time = datetime('now','localtime') where id = %d", id);
1315 1316
				db.execDML(updateFeatureCode);
			}
1317 1318
			if (j == 0 && sim > 0.9) {
				logger->info("第一个向量大于0.9的置信度 置换第一个商品代码");
1319 1320
				biggerNinety = 1;
			}
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
			// scores[j+3] = feature;
		}
		db.close();

		for (int i = 0; i < 10; i++)
		{
			if (code[i].empty() || code[i] == "0") {
				continue;
			}
			for (int j = i + 1; j < 10; j++)
			{
				if (code[j].empty() || code[j] == "0") {
					continue;
				}
				if (code[i] == code[j]) {
					code[j] = "0";
				}
			}
		}

		double endTime1 = clock();//1计时结束
		double elasped = endTime1 - startTime1;
		logger->info("index time : elapsed {}ms\n", elasped);
	}
	catch (...) {
		logger->info("compare_feature_faiss failed");
	}
	return 0;
}

const char* getMaxLimpidPic(const char* imagepath1, const char* imagepath2, const char* imagepath3, int count) {
	if (count == 1) {
		return imagepath1;
	}
	if (count == 2) {
		return imagepath2;
	}
	if (count == 3) {
		return imagepath3;
	}
	throw "imread read error";
}

cv::Mat getMaxMat(const char* imagepath1, const char* imagepath2, const char* imagepath3, int& count) {
	cv::Mat m1 = cv::imread(imagepath1, 1);
	if (m1.empty())
	{
		logger->info("cv::imread {} failed\n", imagepath1);
		throw "cv::imread failed";
	}
	float f1 = TenengradBlurDetect(m1);
	cv::Mat m2 = cv::imread(imagepath2, 1);
	if (m2.empty())
	{
		logger->info("cv::imread {} failed\n", imagepath2);
		throw "cv::imread failed";
	}
	float f2 = TenengradBlurDetect(m2);
	cv::Mat m3 = cv::imread(imagepath3, 1);
	if (m3.empty())
	{
		logger->info("cv::imread {} failed\n", imagepath3);
		throw "cv::imread failed";
	}
	float f3 = TenengradBlurDetect(m3);
	float fmax = max(max(f1, f2), f3);
	if (fmax == f1) {
		count = 1;
		return m1;
	}
	else if (fmax == f2) {
		count = 2;
		return m2;
	}
	else if (fmax == f3) {
		count = 3;
		return m3;
	}
	else {
		throw "cv::imread failed";
	}
}

// 保存打称记录
int save_record(std::string sessionId, int index, float score, float time, string imagepath, string features, string productcode, string codes) {
	try {
		CppSQLite3DB db;
		db.open(gszFile);
		CppSQLite3Buffer insertProductCode;
		insertProductCode.format("insert into product_record(session_id, model_code, score,feature_value,image_path,product_ids,real_codes,time) values (%Q,%d,%f,%Q,%Q,%Q,%Q,%f);", sessionId.c_str(), index, score, features.c_str(), imagepath.c_str(), productcode.c_str(), codes.c_str(), time);
		db.execDML(insertProductCode);
		db.close();
		return 0;
	}
	catch (...) {
		logger->info("save_record failed");
		return -1;
	}
}

// 获取10位sessionId
string get_session_id()
{
	char prefix[50];
	time_t nowTime;
	tm* now;
	time(&nowTime);				//获取系统当前时间戳
	now = localtime(&nowTime);	//将时间戳转化为时间结构体

	srand((int)time(0));
	long l = rand() % 9000000000 + 1000000000;
	ostringstream os;
	os << l;
	string result;
	istringstream is(os.str());
	is >> result;

	sprintf(prefix, "%d%d%d%d%d%d%d%d", macAddr.c_str(), now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
		now->tm_hour + 8, now->tm_min, now->tm_sec, result.c_str());
	string s(prefix, prefix + strlen(prefix));
	return s;
}


int convert_model_code(int* index, float* scores, string* productcode) {
	CppSQLite3DB db;
	db.open(gszFile);
	if (!db.tableExists("product_model")) {
		for (int i = 0; i < 10; i++)
		{
			productcode[i] = "0";
		}
		return 0;
	}
	vector<string> indexProductCodes = { "0","0" ,"0" ,"0" ,"0" ,"0" ,"0" };
	CppSQLite3Query q;
	int count = 0;
	for (int i = 0; i < 10; i++)
	{
		if (count > 6) {
			break;
		}
		if (scores[i] > 0.01) {
			CppSQLite3Buffer selectProductCode;
			selectProductCode.format("select product_code from product_model where model_code = %d;", index[i]);
			cout << selectProductCode << endl;
			q = db.execQuery(selectProductCode);
			while (!q.eof())
			{
				if (count > 6) {
					break;
				}
				string productCode = q.getStringField(0);
				indexProductCodes[count] = productCode;
				++count;
				q.nextRow();
			}
		}
	}
	q.finalize();
	db.close();
	for (int i = 0; i < 10; i++)
	{
		if (productcode[i] != "") {
			continue;
		}
		if (i < 3) {
			productcode[i] = indexProductCodes[i];
		}
		else {
			productcode[i] = indexProductCodes[i - 3];
		}
	}
	return 0;
}

void saveImg(string pic_Name, cv::Mat mat) {
	cv::imwrite(pic_Name, mat);
}

// 拍照
cv::Mat getScaleBitmap(char* rawPath, char* cropPath, bool saveRawImg) {
	cv::Mat returnFrame, frame1, frame2, frame3;
	double startTime1, endTime1, elasped;
	startTime1 = clock();//1计时开始
	char pic_Name[128] = {};     //照片名称
	char raw_pic_Name[128] = {};     //照片名称
	if (!cap.isOpened())
	{
		logger->info("The camera open failed!");
		return returnFrame;
	}
	if (frame_one.empty() || frame_thr.empty() || frame_two.empty()) {
		logger->info("camera not init,please wait");
		return returnFrame;
	}
	time_t nowTime;
	tm* now;
	WaitForSingleObject(PhotoMutex, INFINITE);
	frame1= frame_one.clone();
	frame2= frame_two.clone();
	frame3 =frame_thr.clone();
	ReleaseMutex(PhotoMutex);
	endTime1 = clock();
	elasped = endTime1 - startTime1;
	logger->info("camera load elapsed {}ms\n", elasped);
	time(&nowTime);				//获取系统当前时间戳
	now = localtime(&nowTime);	//将时间戳转化为时间结构体

1532
	_mkdir(wmphoto_path.c_str());
1533 1534 1535 1536 1537 1538 1539
	if (saveRawImg) {
#if APPOINT_LIBRARY
		string new_dir = wmphoto_path;
		char photoPath[MAX_PATH];
		strcpy(photoPath, (new_dir + "\\raw%d%d%d%d%d%d.jpg").c_str());
#else
		char photoPath[MAX_PATH];
1540
		std::strcpy(photoPath, (wmphoto_path+"\\raw%d%d%d%d%d%d.jpg").c_str());
1541 1542 1543 1544
#endif // 0
		sprintf(raw_pic_Name, photoPath, now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
			now->tm_hour + 8, now->tm_min, now->tm_sec);
		cv::imwrite(raw_pic_Name, frame1);
1545
		std::strcpy(rawPath, raw_pic_Name);
1546 1547 1548 1549 1550 1551 1552 1553
	}
	if (x && y && width && height) {
#if APPOINT_LIBRARY
		string new_dir = wmphoto_path;
		char photoPath[MAX_PATH];
		strcpy(photoPath, (new_dir + "\\%d%d%d%d%d%d.jpg").c_str());
#else
		char photoPath[MAX_PATH];
1554
		std::strcpy(photoPath, (wmphoto_path+"\\%d%d%d%d%d%d.jpg").c_str());
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
#endif // 0
		sprintf(pic_Name, photoPath, now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
			now->tm_hour + 8, now->tm_min, now->tm_sec);
		cv::Mat catImage1 = frame1(cv::Rect(x, y, width, height));
		cv::Mat catImage2 = frame2(cv::Rect(x, y, width, height));
		cv::Mat catImage3 = frame3(cv::Rect(x, y, width, height));

		float f1 = TenengradBlurDetect(catImage1);
		float f2 = TenengradBlurDetect(catImage2);
		float f3 = TenengradBlurDetect(catImage3);
		float maxF = max(max(f1, f2), f3);
		if (maxF == f1) {
			returnFrame = catImage1.clone();
			if (saveRawImg) {
				// 如果是主动拍照 路径同步返回
				cv::imwrite(pic_Name, catImage1);
			}
			else {
				std::thread t(saveImg, string(pic_Name), catImage1);	//将Mat数据写入文件
				t.detach();
			}
		}
		if (maxF == f2) {
			returnFrame = catImage2.clone();
			if (saveRawImg) {
				// 如果是主动拍照 路径同步返回
				cv::imwrite(pic_Name, catImage2);
			}
			else {
				std::thread t(saveImg, string(pic_Name), catImage2);	//将Mat数据写入文件
				t.detach();
			}
		}
		if (maxF == f3) {
			returnFrame = catImage3.clone();
			if (saveRawImg) {
				// 如果是主动拍照 路径同步返回
				cv::imwrite(pic_Name, catImage3);
			}
			else {
				std::thread t(saveImg, string(pic_Name), catImage3);	//将Mat数据写入文件
				t.detach();
			}
		}
1599
		std::strcpy(cropPath, pic_Name);
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
	}
	endTime1 = clock();//1计时开始
	elasped = endTime1 - startTime1;
	logger->info("camera all elapsed {}ms\n", elasped);
	return returnFrame;
}

void _stringCpy(string* des,string* rec,int len) {
	for (size_t i = 0; i < len; i++)
	{
		des[i] = rec[i];
	}
}

// 主动识别接口
int MatDetect(Mat& imageFrame, char* productcodes, char* sessionId) {
	if (!authed) {
		authed = authorize();
		if (!authed) {
			cout << "验证失败" << endl;
			return -1;
		};
	}

	int use_gpu = 0;
#if NCNN_VULKAN
	// ncnn::create_gpu_instance(); 
#endif // NCNN_VULKAN
	cv::Mat m = imageFrame.clone();
	if (m.empty())
	{
		logger->info("cv::imread failed\n");
		return -1;
	}
	int biggerNinety = 0;
	string productcode[10];
	std::vector<float> cls_scores;
	float rhs[FEATURE_COUNT];
	double start_time = ncnn::get_current_time();

1640
	detect_squeezenet(m, cls_scores, rhs);
1641 1642 1643 1644 1645 1646
	std::thread t(compare_feature_faiss, rhs, productcode, ref(biggerNinety));
	t.join();
	double elasped = ncnn::get_current_time() - start_time;
	logger->info("category elapsed {}ms\n", elasped);

	string newSessionId = get_session_id().c_str();
1647
	std::strcpy(sessionId, newSessionId.c_str());
1648 1649 1650 1651

	string imagePath = "WMPhoto\\" + newSessionId + ".jpg";
	std::thread t3(saveImg, string(imagePath), m);	//将Mat数据写入文件
	t3.detach();
1652 1653

	//param_in.detect_image_path = imagePath;
1654

zzx's avatar
zzx committed
1655
	double save_record_start_time = clock();//1计时开始
1656 1657 1658 1659
	// 组装返回的商品代码
	char codes[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
zzx's avatar
zzx committed
1660
		if (productcode[i].empty() || productcode[i] == "0") {
1661 1662
			continue;
		}
zzx's avatar
zzx committed
1663
		sprintf(codes + strlen(codes), "%s,", productcode[i].c_str());
1664
	}
zzx's avatar
zzx committed
1665
	logger->info("productcodes:{}", codes);
1666
	std::strcpy(productcodes, codes);
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
	// 将图片向量进行逗号组装
	char featureValue[FEATURE_COUNT * 10] = { };
	for (int i = 0; i < FEATURE_COUNT; ++i)
	{
		sprintf(featureValue + strlen(featureValue), "%f,", rhs[i]);
	}
	// 组装productIds
	char productIds[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
zzx's avatar
zzx committed
1677 1678 1679
		if (productcode[i].empty()) {
			continue;
		}
1680 1681
		sprintf(productIds + strlen(productIds), "%s,", productcode[i].c_str());
	}
zzx's avatar
zzx committed
1682 1683 1684 1685 1686

	save_record(newSessionId, 0, 0, elasped, imagePath, string(featureValue), string(productIds), string(codes));

	double save_record_end_time = clock();//1计时开始
	logger->info("save record elapsed {}ms\n", save_record_end_time - save_record_start_time);
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
	return 0;
}

// 主动识别接口
int WMAI_API DemoDetect(const char* imagePath, char* productcodes, char* sessionId) {
	double all_start_time = clock();//1计时开始
	if (!authed) {
		authed = authorize();
		if (!authed) {
			cout << "验证失败" << endl;
			return -1;
		};
	}
	int use_gpu = 0;

#if NCNN_VULKAN
	// ncnn::create_gpu_instance(); 
#endif // NCNN_VULKAN
	cv::Mat m = cv::imread(imagePath, 1);
	if (m.empty())
	{
		logger->info("cv::imread {} failed\n", imagePath);
		return -1;
	}

	int biggerNinety = 0;
	string productcode[10];
	std::vector<float> cls_scores;
	float rhs[FEATURE_COUNT];
	double start_time = ncnn::get_current_time();
1717
	int ret = detect_squeezenet(m, cls_scores, rhs);
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
	if (ret != 0) {
		logger->info("元芒图形加速识别失败,error:ret",ret);
		return -2004;
	}
	std::thread t(compare_feature_faiss, rhs, productcode, ref(biggerNinety)); 
	t.join();
	double elasped = ncnn::get_current_time() - start_time;
	logger->info("category elapsed %.2fms\n", elasped);

	double save_record_start_time = clock();//1计时开始
	string newSessionId = get_session_id().c_str();
1729
	std::strcpy(sessionId, newSessionId.c_str());
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
	// 0 1 2 3 4 5 6 7 8 9
	// 3 0 1 2 4 5 6 7 8 9
	string returnCodes[10];
	_stringCpy(returnCodes, productcode, 10);
	if (biggerNinety) {
		string codeFour;
		for (int i = 3; i > 0; i--)
		{
			if (i == 3) {
				codeFour = returnCodes[i];
			}
			returnCodes[i] = returnCodes[i - 1];
		}
		returnCodes[0] = codeFour;
	}
	// 去重returnCodes
	for (int i = 0; i < 10; i++)
	{
		if (returnCodes[i].empty() || returnCodes[i] == "0") {
			continue;
		}
		for (int j = i + 1; j < 10; j++)
		{
			if (returnCodes[j].empty() || returnCodes[j] == "0") {
				continue;
			}
			if (returnCodes[i] == returnCodes[j]) {
				returnCodes[j] = "0";
			}
		}
	}
	// 组装返回的商品代码
	char codes[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
		if (returnCodes[i].empty() || returnCodes[i] == "0") {
			continue;
		}
		sprintf(codes + strlen(codes), "%s,", returnCodes[i].c_str());
	}
zzx's avatar
zzx committed
1770
	logger->info("productcodes:{}", codes);
1771
	std::strcpy(productcodes, codes);
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
	// 将图片向量进行逗号组装
	char featureValue[FEATURE_COUNT * 10] = { };
	for (int i = 0; i < FEATURE_COUNT; ++i)
	{
		sprintf(featureValue + strlen(featureValue), "%f,", rhs[i]);
	}
	// 组装productIds
	char productIds[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
		sprintf(productIds + strlen(productIds), "%s,", productcode[i].c_str());
	}

	double save_record_end_time = clock();//1计时开始
1786
	std::thread t1(save_record, newSessionId, 0, 0, elasped, string(imagePath), string(featureValue), string(productIds), string(codes));
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
	t1.detach();
	logger->info("save record elapsed {}ms\n", save_record_end_time - save_record_start_time);
	double all_end_time = clock();//1计时开始
	logger->info("all time elapsed {}ms\n", all_start_time - all_end_time);
	return 0;
}

// 零食识别
int doSnacksAutoDetect(char* productcodes, char* sessionId, char* image) {
	double all_start_time = clock();//1计时开始
	if (!authed) {
		authed = authorize();
		if (!authed) {
			logger->info("验证失败");
			return -2001;
		};
	}
	if (!x && !y && !width && !height) {
		logger->info("没有设置摄像头剪辑坐标");
		return -2009;
	}
	int thread = 4;
	int use_gpu = 0;

#if NCNN_VULKAN
	// ncnn::create_gpu_instance(); 
#endif // NCNN_VULKAN
	char rawPath[128];
	char cropPath[128];
	cv::Mat m = getScaleBitmap(rawPath, cropPath, false);
	if (m.empty())
	{
		logger->info("cv::imread failed\n");
		return -2002;
	}
	int biggerNinety = 0;
	// 拷贝图片地址
	strncpy(image, cropPath, 128);
	string productcode[10];
	std::vector<float> cls_scores;
	float rhs[FEATURE_COUNT];
	double start_time = ncnn::get_current_time();
1829
	int ret = detect_squeezenet(m, cls_scores, rhs);
1830 1831 1832 1833 1834 1835
	double elasped = ncnn::get_current_time() - start_time;
	logger->info("category elapsed {}ms\n", elasped);
	compare_feature_faiss(rhs, productcode, ref(biggerNinety));

	double save_record_start_time = clock();//1计时开始
	string newSessionId = get_session_id();
1836
	std::strcpy(sessionId, newSessionId.c_str());
1837 1838 1839 1840 1841 1842 1843 1844 1845
	// 组装返回的商品代码
	char codes[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
		if (productcode[i].empty() || productcode[i] == "0") {
			continue;
		}
		sprintf(codes + strlen(codes), "%s,", productcode[i].c_str());
	}
zzx's avatar
zzx committed
1846
	logger->info("productcodes:{}", codes);
1847
	std::strcpy(productcodes, codes);
1848 1849 1850 1851 1852

	string  product_codes = productcodes;
	
	char* realIds = const_cast<char*>(product_codes.c_str());
	splitString(realIds, realProductCodes);
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
	// 将图片向量进行逗号组装
	char featureValue[FEATURE_COUNT * 10] = { };
	for (int i = 0; i < FEATURE_COUNT; ++i)
	{
		sprintf(featureValue + strlen(featureValue), "%f,", rhs[i]);
	}
	// 组装productIds
	char productIds[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
		if (productcode[i].empty()) {
			continue;
		}
		sprintf(productIds + strlen(productIds), "%s,", productcode[i].c_str());
	}
	
	save_record(newSessionId, 0, 0, elasped, string(cropPath), string(featureValue), string(productIds), string(codes));

	double save_record_end_time = clock();//1计时开始
	logger->info("save record elapsed {}ms\n", save_record_end_time - save_record_start_time);
	double all_end_time = clock();//1计时开始
	logger->info("all time elapsed {}ms\n", all_start_time - all_end_time);
	return 0;
}

// 主动识别接口
1879 1880
int WMAI_API AutoDetect(char* productcodes, char* sessionId) 
{
1881 1882
	
	char image[128];
1883 1884
	int ret = doSnacksAutoDetect(productcodes, sessionId, image);
	return ret;
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929

}

int getTopNo(string* productCodes, const char* code) {
	for (int i = 0; i < 10; i++)
	{
		if (productCodes[i] == code) {
			return i + 1;
		}
	}
	return -1;
}

string getNowDate() {
	char prefix[50];
	time_t nowTime;
	tm* now;
	time(&nowTime);				//获取系统当前时间戳
	now = localtime(&nowTime);	//将时间戳转化为时间结构体
	sprintf(prefix, "%4d-%02d-%02d %02d:%02d:%02d.000", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
		now->tm_hour, now->tm_min, now->tm_sec);
	return prefix;
}

int saveHnswCount = 0;

void saveHnswIndex(string featureValue,int id) {
	try {
		//将数据加入索引
		float features[FEATURE_COUNT];
		char c[FEATURE_COUNT * 10];
		strcpy_s(c, featureValue.c_str());
		split(c, features);

		idx->Addsample(features, id - 1);
		logger->info("cover label is {}", id - 1);
		logger->info("index size is {}", idx->get_cur_element_count());
	}catch(...){
		logger->info("add simple error");
	}
}

void saveDbIndex(CppSQLite3DB& db, const char* code, std::string& featureValue)
{
	db.setBusyTimeout(3000);
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954

	//检测feature_code表达数据
	int size_f = 0;
	CppSQLite3Buffer measure;
	measure.format("select count(*) from feature_code;");
	CppSQLite3Query q = db.execQuery(measure);
	while (!q.eof())
	{
		size_f = q.getIntField(0);
		break;
	}
	q.finalize();

	//查询表单大小,确认是否有未使用的id
	CppSQLite3Buffer measureCount;
	measureCount.format("select count(*) from record_count;");
	CppSQLite3Query q1 = db.execQuery(measureCount);
	int size_r = 0;
	while (!q1.eof())
	{
		size_r = q1.getIntField(0);
		break;
	}
	q1.finalize();

1955 1956
	int lastId = idx->get_cur_element_count();
	logger->info("lastId is {}", lastId);
1957
	if (size_f >= 30000) {
1958 1959
		// 找到时间最小的向量 进行替换
		int id = 0;
1960
		int count = 0;
1961
		// 找到第一个code的商品 替换他 
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
		CppSQLite3Buffer selectCount;
		if (size_r > 1) {
			//有积存id,取最后一条
			selectCount.format("select id , count from record_count order by id desc limit 1;");
			CppSQLite3Query q = db.execQuery(selectCount);
			while (!q.eof())
			{
				id = q.getIntField(0);
				count = q.getIntField(1);
				break;
			}
			q.finalize();
			logger->info("id:{}", id);
			logger->info("count:{}", count);

			//覆盖删除值
			CppSQLite3Buffer updateFeatureCode;
			updateFeatureCode.format("update feature_code set code = %Q,feature= %Q,update_time = datetime('now','localtime') ,deleted = 0 where id = %d;", code, featureValue.c_str(), count);
			db.execDML(updateFeatureCode);
			logger->info("覆盖成功");

			//删除用掉的id的记录
			CppSQLite3Buffer delCount;
			selectCount.format("delete from record_count where id = %d;", id);
			db.execDML(selectCount);
		}
		else
1989
		{
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
			//没有积存id,读取标记
			selectCount.format("select count from record_count where id = 1;");
			CppSQLite3Query q = db.execQuery(selectCount);
			while (!q.eof())
			{
				count = q.getIntField(0);
				break;
			}
			q.finalize();

			//判断是否超出上限
			if (count > 30000) {
				CppSQLite3Buffer overDelete;
				overDelete.format("update record_count set count = 1 where id = 1");
				count = 1;
				CppSQLite3Buffer updateCount;
				updateCount.format("update record_count set count = 1 where id = 1");
				db.execDML(updateCount);
			}

			// 直接覆盖
			CppSQLite3Buffer updateFeatureCode;
			updateFeatureCode.format("update feature_code set feature = %Q,code = %Q,update_time = datetime('now','localtime'),deleted = 0 where id = %d", featureValue.c_str(), code, count);
			db.execDML(updateFeatureCode);
2014
		}
2015 2016
		logger->info("count :{}", count);

2017 2018 2019
		// 删除label
		// idx->Removesample(id - 1);
		// 保存索引
2020 2021 2022 2023 2024 2025
		//hnswExecutor->enqueue(saveHnswIndex, string(featureValue), id);
		saveHnswIndex(string(featureValue), count);

		CppSQLite3Buffer updateCount;
		updateCount.format("update record_count set count = count + 1 where id = 1");
		db.execDML(updateCount);
2026 2027 2028
	}
	else {
		// 记录feature 和 商品代码之间的关系 到sqlite 和 faiss索引
2029 2030 2031
		CppSQLite3Buffer insertFeatureCode;	
		insertFeatureCode.format("insert into feature_code(code, feature,update_time,deleted) values (%Q,%Q,datetime('now','localtime'),0);", code, featureValue.c_str());	
		db.execDML(insertFeatureCode);	
2032

2033 2034
	
		int count = db.execScalar("select last_insert_rowid() from feature_code;");	
2035 2036 2037
		logger->info("db add id is {}", count);
		//将数据加入索引
		// 保存索引
2038 2039
		//hnswExecutor->enqueue(saveHnswIndex, string(featureValue), count);
		saveHnswIndex(string(featureValue), count);	
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
	}
}

void saveDbIndex2(CppSQLite3DB& db, const char* code, std::string& featureValue)
{
	db.setBusyTimeout(3000);
	int lastId = idx->get_cur_element_count();
	logger->info("lastId is {}", lastId);
	if (lastId >= 50000) {
		// 找到时间最小的向量 进行替换
		int id = 0;
		// 找到第一个code的商品 替换他 
		CppSQLite3Buffer selectFeatureCode;
		selectFeatureCode.format("select id,min(update_time) from feature_code;");
		CppSQLite3Query q = db.execQuery(selectFeatureCode);
		while (!q.eof())
		{
			id = q.getIntField(0);
			break;
		}
		q.finalize();
		// 直接覆盖
		CppSQLite3Buffer updateFeatureCode;
2063
		updateFeatureCode.format("update feature_code set feature = %Q,code = %Q,update_time = datetime('now','localtime') where id = %d", featureValue.c_str(), code, id);
2064 2065 2066 2067 2068 2069 2070
		db.execDML(updateFeatureCode);
		// 保存索引
		saveHnswIndex(string(featureValue), id);
	}
	else {
		// 记录feature 和 商品代码之间的关系 到sqlite 和 faiss索引
		CppSQLite3Buffer insertFeatureCode;
2071
		insertFeatureCode.format("insert into feature_code(code, feature,update_time) values (%Q,%Q,datetime('now','localtime'));", code, featureValue.c_str());
2072 2073 2074 2075
		db.execDML(insertFeatureCode);

		float features[FEATURE_COUNT];
		char c[FEATURE_COUNT * 10];
2076
		std::strcpy(c, featureValue.c_str());
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
		split(c, features);

		int count = db.execScalar("select last_insert_rowid() from feature_code;");
		logger->info("db add id is {}", count);
		// 保存索引
		saveHnswIndex(string(featureValue), count);
	}
}


void sendClientFeatureMessage(const char* productCode, string featureValue) {
	if (s_pclient->HasStarted()) {
		Document d;

		Document::AllocatorType& allocator = d.GetAllocator();

		Value str_val;
		char strBuffer[FEATURE_COUNT * 10];
		int len = sprintf(strBuffer, featureValue.c_str());
		str_val.SetString(strBuffer, len, allocator);

		Pointer("/type").Set(d, 1);
		Pointer("/productCode").Set(d, productCode);
		Pointer("/feature").Set(d, str_val, allocator);
		StringBuffer buffer;
		Writer<StringBuffer> writer(buffer);
		d.Accept(writer);
		logger->info(buffer.GetString());
		s_pclient->Send((const BYTE*)buffer.GetString(), buffer.GetLength());
	}
	else if (s_pserver->HasStarted()) {
		Document d;

		Document::AllocatorType& allocator = d.GetAllocator();

		Value str_val;
		char strBuffer[FEATURE_COUNT * 10];
		int len = sprintf(strBuffer, featureValue.c_str());
		str_val.SetString(strBuffer, len, allocator);

		Pointer("/type").Set(d, 1);
		Pointer("/productCode").Set(d, productCode);
		Pointer("/feature").Set(d, str_val, allocator);
		StringBuffer buffer;
		Writer<StringBuffer> writer(buffer);
		d.Accept(writer);
		logger->info(buffer.GetString());

		for (long i = 0; i < connIds.size(); i++)
		{
			logger->info("client connId is {}", connIds[i]);
			s_pserver->Send(connIds[i], (const BYTE*)buffer.GetString(), buffer.GetLength());
		}
	}
	else {
		// do nothing
	}
}

int getNumByScore(float score) {
	return score >= markDownScoreLimit ? 1 : 0;
}

// 生鲜回传
int doFruitsSetFeedBack(const char* code, char* sessionId, bool hit, char* productName) {
	CppSQLite3DB db;
	db.open(gszFile);
	// 回传记录保存
	CppSQLite3Buffer insertFeedBackRecord;
	insertFeedBackRecord.format("insert into feed_back_record(code, session_id,hit) values (%Q,%Q,%d);", code, sessionId, hit);
	db.execDML(insertFeedBackRecord);
	// 根据sessionId查询对应的打称记录 如果置信度>0.85 那么将商品代码 模型代码的计数器+1 如果计数器>=2 将商品模型的关系记录
	// 首先查询根据sessionId查询product_record 得到模型代码 和 置信度
	if (!db.tableExists("product_record")) {
		logger->info("product_record not found , please check AutoDetect success");
		db.close();
		return -2004;
	}
	int modelCode = 0;
	float score;
	string featureValue;
	string imagePath;
	string productIds;
	string time;
	string realCodes;
	for (int i = 0; i < 5; i++)
	{
		CppSQLite3Buffer selectProductRecord;
		selectProductRecord.format("select model_code,score,feature_value,image_path,product_ids,time,real_codes from product_record where session_id = %Q;", sessionId);
		CppSQLite3Query q = db.execQuery(selectProductRecord);
		while (!q.eof())
		{
			modelCode = q.getIntField(0);
			score = q.getFloatField(1);
			featureValue = q.getStringField(2);
			imagePath = q.getStringField(3);
			productIds = q.getStringField(4);
			time = q.getStringField(5);
			realCodes = q.getStringField(6);
			q.nextRow();
		}
		q.finalize();
		if (!modelCode) {
			logger->info("sessionId not found , wait 200ms, times:{}", i + 1);
			Sleep(200);
			continue;
		}
		else {
			break;
		}
	}
	if (!modelCode) {
		logger->info("sessionId not found after 5 times");
		db.close();
		return -2005;
	}
zzx's avatar
zzx committed
2193 2194 2195 2196 2197

	if (featureValue.empty())
	{
		return -2005;
	};
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
	// 首先查询商品模型表是否有该数据
	string productCodes[10];
	char* cIds = const_cast<char*>(productIds.c_str());
	splitString(cIds, productCodes);
	int topNo = getTopNo(productCodes, code);

	string realProductCodes[10];
	char* realIds = const_cast<char*>(realCodes.c_str());
	splitString(realIds, realProductCodes);
	int realTopNo = getTopNo(realProductCodes, code);
	logger->info("sessionId is {},hit top {},real hit top is {}", sessionId, topNo, realTopNo);
	// 打标
	markDown(code, db, modelCode, score);
	//}
2212
	if (!hit|| !realProductCodes[1].empty()) {
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
		saveDbIndex(db, code, featureValue);
		sendClientFeatureMessage(code, featureValue);
	}
	db.close();

	if (connectNet) {
		Document d;
		string response;
		char uploadUrl[200];
		sprintf(uploadUrl, upload_file_url, dev.c_str(), tenantStr.c_str());
		logger->info("upload url is {},imagePath is {}", uploadUrl, imagePath.c_str());
		int curlCode = CommonTools::upload_file(uploadUrl, imagePath.c_str(), response);
		logger->info("response is {},curl code is {}", response.c_str(), curlCode);
		if (curlCode != 0) {
			connectNet = false;
			logger->info("设备未联网不再上传");
			return 0;
		}
		d.Parse(response.c_str());
		int resultCode = d["code"].GetInt();
		if (resultCode == 0) {
			Value& s1 = d["data"]["url"];
			if (s1.IsNull()) {
				logger->info("上传失败");
				return 0;
			}
			string imageUrl = s1.GetString();
			d.Clear();

			Pointer("/recommendTime").Set(d, time);
			Pointer("/productCode").Set(d, code);
			Pointer("/productName").Set(d, productName);
			Pointer("/weightingStartTime").Set(d, getNowDate());
			Pointer("/sessionId").Set(d, sessionId);
			Pointer("/weighImageUrl").Set(d, imageUrl);
			Pointer("/aiType").Set(d, "WINMORE");
			Pointer("/topNo").Set(d, realTopNo);
			Pointer("/identifyCode/code").Set(d, to_string(modelCode));
			Pointer("/identifyCode/accuracy").Set(d, score);
			StringBuffer buffer;
			Writer<StringBuffer> writer(buffer);
			d.Accept(writer);

			char url[100];
			sprintf(url, save_record_url, dev.c_str(), tenantStr.c_str());
			logger->info("url2:{}", url);
			string response2;
			CommonTools::HttpPost(url, buffer.GetString(), response2, 3);
			cout << response2 << endl;
		}
		else {
			logger->info("upload error url is {}, error code is {}", uploadUrl, resultCode);
			connectNet = false;
		}
	}
	return 0;
}

void markDown(const char* code, CppSQLite3DB& db, int modelCode, float score)
{
	// 1.查商品code product_model_counting 是否有记录
	int id;
	string countProductCode;
	int countModelCode = 0;
	int num;
	// 3.根据商品Id查询计数器
	CppSQLite3Buffer selectProductModelCountByProductCode;
	selectProductModelCountByProductCode.format("select id,product_code,model_code,num from product_model_counting where product_code = %Q;", code);
	CppSQLite3Query productModelCountByProductCode = db.execQuery(selectProductModelCountByProductCode);
	while (!productModelCountByProductCode.eof())
	{
		id = productModelCountByProductCode.getIntField(0);
		countProductCode = productModelCountByProductCode.getStringField(1);
		countModelCode = productModelCountByProductCode.getIntField(2);
		num = productModelCountByProductCode.getIntField(3);
		productModelCountByProductCode.nextRow();
	}
	// 2.如果没有记录 判断 top1置信度 >= 0.9 计数器 = 1 置信度< 0.9 计数器 = 0 记录 code modelCode 如果 记录到product_model_counting
	if (!countModelCode) {
		CppSQLite3Buffer insertProductModelCount;
		insertProductModelCount.format("insert into product_model_counting(product_code, model_code, num) values (%Q,%d,%d);", code, modelCode, getNumByScore(score));
		db.execDML(insertProductModelCount);
	}
	else {
		// 3.如果有记录 并且modelCode = top1code 置信度>=0.9 计数器+1 更新
		if (countModelCode == modelCode && score >= markDownScoreLimit) {
			++num;
			CppSQLite3Buffer updateProductModelCountNum;
			updateProductModelCountNum.format("update product_model_counting set num = %d where id = %d", num, id);
			db.execDML(updateProductModelCountNum);
		}
		else if (countModelCode != modelCode && num <= 3) {
			CppSQLite3Buffer updateProductModelCountNum;
			updateProductModelCountNum.format("update product_model_counting set num = %d,model_code = %d where id = %d", getNumByScore(score), modelCode, id);
			db.execDML(updateProductModelCountNum);
		}
		else if (countModelCode != modelCode && num > 3) {
			num = num - 3;
			CppSQLite3Buffer updateProductModelCountNum;
			updateProductModelCountNum.format("update product_model_counting set num = %d,model_code = %d where id = %d", num, modelCode, id);
			db.execDML(updateProductModelCountNum);
		}
		else {
			logger->info("do nothing countModelCode is {} modelCode is {} score is {}", countModelCode, modelCode, score);
		}
	}
}

// 零食回传
int doSnacksSetFeedBack(const char* code, char* sessionId, bool hit, char* productName) {
	CppSQLite3DB db;
	db.open(gszFile);
	// 回传记录保存
	CppSQLite3Buffer insertFeedBackRecord;
	insertFeedBackRecord.format("insert into feed_back_record(code, session_id,hit) values (%Q,%Q,%d);", code, sessionId, hit);
	db.execDML(insertFeedBackRecord);
	// 根据sessionId查询对应的打称记录 如果置信度>0.85 那么将商品代码 模型代码的计数器+1 如果计数器>=2 将商品模型的关系记录
	// 首先查询根据sessionId查询product_record 得到模型代码 和 置信度
	if (!db.tableExists("product_record")) {
		logger->info("product_record not found , please check AutoDetect success");
		return -2004;
	}
	int modelCode = 0;
	float score;
	string featureValue;
	string imagePath;
	string productIds;
	string time;
	string realCodes;
2342 2343 2344
	int realTopNo;
	
	if (!hit|| !realProductCodes[1].empty())
zzx's avatar
zzx committed
2345
	{
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
		CppSQLite3Buffer selectProductRecord;
		selectProductRecord.format("select model_code,score,feature_value,image_path,product_ids,time,real_codes from product_record where session_id = %Q;", sessionId);
		CppSQLite3Query q = db.execQuery(selectProductRecord);
		
		while (!q.eof())
		{
			modelCode = q.getIntField(0);
			score = q.getFloatField(1);
			featureValue = q.getStringField(2);
			imagePath = q.getStringField(3);
			productIds = q.getStringField(4);
			time = q.getStringField(5);
			realCodes = q.getStringField(6);
			q.nextRow();
		}
		q.finalize();
		if (featureValue.empty())
		{
			return -2005;
		};
2366

2367 2368 2369 2370 2371
		// 获得topNo
		string productCodes[10];
		char* cIds = const_cast<char*>(productIds.c_str());
		splitString(cIds, productCodes);
		int topNo = getTopNo(productCodes, code);
2372

2373 2374 2375 2376 2377
		string realProductCodes[10];
		char* realIds = const_cast<char*>(realCodes.c_str());
		splitString(realIds, realProductCodes);
		realTopNo = getTopNo(realProductCodes, code);
		logger->info("sessionId is {},hit top {},real hit top is {}", sessionId, topNo, realTopNo);
2378

2379 2380
		saveDbIndex(db, code, featureValue);
		sendClientFeatureMessage(code, featureValue);
2381

2382 2383
		db.close();
	}
2384 2385 2386 2387 2388 2389
	if (connectNet) {
		Document d;
		string response;
		char uploadUrl[200];
		sprintf(uploadUrl, upload_file_url, dev.c_str(), tenantStr.c_str());
		logger->info("upload url is {},imagePath is {}", uploadUrl, imagePath.c_str());
2390
		int resultCode = CommonTools::upload_file(uploadUrl, imagePath.c_str(), response); 
2391 2392 2393 2394 2395
		if (resultCode != 0) {
			connectNet = false;
			logger->info("设备未联网不再上传");
			return 0;
		}
2396 2397
		
		d.Parse(response.c_str()); 
2398 2399 2400 2401 2402 2403 2404 2405 2406
		if (d["code"].GetInt() == 0) {
			Value& s1 = d["data"]["url"];
			if (s1.IsNull()) {
				logger->info("上传失败");
				return 0;
			}
			string imageUrl = s1.GetString();
			d.Clear();

2407
			Pointer("/recommendTime").Set(d, time); 
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
			Pointer("/productCode").Set(d, code);
			Pointer("/productName").Set(d, productName);
			Pointer("/weightingStartTime").Set(d, getNowDate());
			Pointer("/sessionId").Set(d, sessionId);
			Pointer("/weighImageUrl").Set(d, imageUrl);
			Pointer("/aiType").Set(d, "WINMORE");
			Pointer("/topNo").Set(d, realTopNo);
			Pointer("/identifyCode/code").Set(d, to_string(modelCode));
			Pointer("/identifyCode/accuracy").Set(d, score);
			StringBuffer buffer;
			Writer<StringBuffer> writer(buffer);
2419
			d.Accept(writer); 
2420

2421 2422
			char url[100] = {};
			
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
			sprintf(url, save_record_url, dev.c_str(), tenantStr.c_str());

			string response2;
			CommonTools::HttpPost(url, buffer.GetString(), response2, 3);
		}
	}
	return 0;
}

// 保存未识别商品
int WMAI_API SetFeedBack(const char* code, char* sessionId, bool hit, char* productName)
{
	logger->info("code is {} sessionId is {} hit is {} productName is {}", code, sessionId,hit, productName);
	logger->info("start feed back");
2437
	int result = doSnacksSetFeedBack(code, sessionId, hit, productName);
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
	logger->info("end feed back");
	return result;
}


int checkTenant(char* tenant) {
	Document d2;
	StringBuffer buffer2;
	Writer<StringBuffer> writer2(buffer2);
	d2.Accept(writer2);

	string response2;
	char tenantUrl[100];
	sprintf(tenantUrl, query_tenant_url, dev.c_str(), tenant);
	logger->info("tenantUrl is {}", tenantUrl);
	CommonTools::HttpGet(tenantUrl, response2, 3);
2454
	logger->info("reponse is {}", UTF_82ASCII(response2));
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
	d2.Parse(response2.c_str());
	Value& s2 = d2["code"];
	if (s2.GetInt() != 0) {
		logger->info("tenantCode:{} 没有找到", tenant);
		return -4004;
	}
	else {
		bool tenantTrue = d2["data"].GetBool();
		if (!tenantTrue) {
			logger->info("tenantCode:{} 没有找到", tenant);
			return -4004;
		}
	}
	return 0;
}
zzx's avatar
zzx committed
2470

2471 2472
// 注册pos机
int WMAI_API InitPos(char* tenant, char* posCode, char* snNo) {
2473
	logger->info("{},{},{}", tenant, posCode, snNo);
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
	int checkTenantCode = checkTenant(tenant);
	if (checkTenantCode != 0) {
		return checkTenantCode;
	}

	Document d;
	Pointer("/code").Set(d, posCode);
	string mac = "";
	GetMacByGetAdaptersAddresses(mac);
	Pointer("/macAddress").Set(d, mac);
	Pointer("/snNo").Set(d, snNo);
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);

	char url[100];
	sprintf(url, wmpos_bind_url, dev.c_str(), tenant);
	logger->info("url is {}", url);

	string response;
	CommonTools::HttpPut(url, buffer.GetString(), response, 3);
2495
	logger->info("reponse is {}", UTF_82ASCII(response));
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
	d.Parse(response.c_str());
	Value& s = d["code"];
	if (s.GetInt() == 0) {
		string wmKeyUrl = d["data"]["wmKeyUrl"].GetString();
		string privateKeyUrl = d["data"]["privateKeyUrl"].GetString();
		posId = d["data"]["id"].GetString();

#if APPOINT_LIBRARY
		string new_dir = string(drive) + dir;
		char wmkey_path[MAX_PATH];
		strcpy(wmkey_path, (new_dir + "wmkey.wm").c_str());
		const char* wmkey = wmkey_path;
		char prikey_path[MAX_PATH];
		strcpy(prikey_path, (new_dir + "prikey.pem").c_str());
		const char* prikey = prikey_path;
#else
		const char* wmkey = "wmkey.wm";
		const char* prikey = "prikey.pem";
#endif // 0
		CommonTools::download_file(wmKeyUrl.c_str(), wmkey);
		CommonTools::download_file(privateKeyUrl.c_str(), prikey);

		tenantStr = tenant;
		if (!tenantStr.empty()) {
			Document d2;
			Pointer("/demo").Set(d2, tenant);
			FILE* fp = fopen(json_tenant_path, "wb");// 非 Windows 平台使用 "w"
			char writeBuffer[65536];
			FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
			Writer<FileWriteStream> writer(os);
			d2.Accept(writer);
			fclose(fp);
		}

		Document d3;
		Pointer("/posId").Set(d3, posId);
		FILE* fp2 = fopen(posId_json_path, "wb"); // 非 Windows 平台使用 "w"
		char writeBuffer2[65536];
		FileWriteStream os2(fp2, writeBuffer2, sizeof(writeBuffer2));
		Writer<FileWriteStream> writer2(os2);
		d3.Accept(writer2);
		fclose(fp2);
		return 0;
	}
	else if (s.GetInt() == 65014) {
		logger->info("snCode没有找到{}", snNo);
		return -4001;
	}
	else if (s.GetInt() == 65017) {
		logger->info("该posCode:{},已经绑定过,并且绑定的mac地址和传入的mac地址不一致", posCode);
		return -4002;
	}
	else if (s.GetInt() == 65006) {
		logger->info("此POS的MAC地址:{} 绑定过其它POS机,请联系管理员确认POS机编号!", mac.c_str());
		return -4003;
	}
	else {
		logger->info("initPos failed errorCode: {}", s.GetInt());
		return -2006;
	}
}

// 注册pos机
int WMAI_API UnBindPos(char* tenant, char* snNo) {
	int checkTenantCode = checkTenant(tenant);
	if (checkTenantCode != 0) {
		return checkTenantCode;
	}

2565 2566
	const char* pwmkey = "pwmkey.wm";
	const char* pprikey = "pprikey.pem";
2567

2568 2569 2570
	remove(pwmkey);
	remove(pprikey);

2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
	string mac;
	GetMacByGetAdaptersAddresses(mac);

	Document d;
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);

	char url[200];
	sprintf(url, wmpos_unbind_url, dev.c_str(), tenant, mac.c_str() ,snNo);
	logger->info("url is {}", url);

	string response;
	CommonTools::HttpGet(url, response, 3);
2585
	logger->info("reponse is {}", UTF_82ASCII(response));
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
	d.Parse(response.c_str());
	Value& s = d["code"];
	if (s.GetInt() == 0) {
#if APPOINT_LIBRARY
		string new_dir = string(drive) + dir;
		char wmkey_path[MAX_PATH];
		strcpy(wmkey_path, (new_dir + "wmkey.wm").c_str());
		const char* wmkey = wmkey_path;
		char prikey_path[MAX_PATH];
		strcpy(prikey_path, (new_dir + "prikey.pem").c_str());
		const char* prikey = prikey_path;
#else
		const char* wmkey = "wmkey.wm";
		const char* prikey = "prikey.pem";
2600

2601 2602 2603 2604
#endif // 0

		remove(wmkey);
		remove(prikey);
2605

2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
		return 0;
	}else if (s.GetInt() == 65014) {
		logger->info("snCode没有找到{}", snNo);
		return -4001;
	}
	else if (s.GetInt() == 65019) {
		logger->info("snCode:{}并未绑定无需解绑", snNo);
		return -4005;
	}
	else if (s.GetInt() == 65017) {
		logger->info("该pos现在的mac地址和服务器记录的mac地址不一致 无法解绑");
		return -4006;
	}
	else {
		logger->info("initPos failed errorCode: {}", s.GetInt());
		return -2006;
	}
}

void getNowMat() {

	int i = 1;
2628
	while (cap.isOpened())
2629 2630 2631 2632
	{
		cap >> frame_pipe;
		if (frame_pipe.empty())
		{
2633
			logger->info("frame_pipe empty");
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
			continue;
		}
		WaitForSingleObject(PhotoMutex, INFINITE);
		if (i == 1) {
			frame_one = frame_pipe.clone();            //读取当前帧
			++i;
		}
		else if (i == 2) {
			frame_two = frame_pipe.clone();            //读取当前帧
			++i;
		}
		else if (i == 3) {
			frame_thr = frame_pipe.clone();            //读取当前帧
			i = 1;
		}
		ReleaseMutex(PhotoMutex);
2650
		if (cv::waitKey(30)) { 	 //延时30ms		
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
			continue;
		}
	}
	return;
}

// 设置摄像头序号
int WMAI_API SetCameraId(int num) {
	static int i=0;
	logger->info("开始打开摄像头:{}",i);
	cameraNum = num;
	Document d;

	logger->info("x:{},y:{},width:{},height:{}", x, y, width, height);
	if (width && height) {
		Pointer("/x").Set(d, x);
		Pointer("/y").Set(d, y);
		Pointer("/width").Set(d, width);
		Pointer("/height").Set(d, height);
		Pointer("/ai_x").Set(d, ai_x);
		Pointer("/ai_y").Set(d, ai_y);
		Pointer("/ai_width").Set(d, ai_width);
		Pointer("/ai_height").Set(d, ai_height);
	}
	Pointer("/cameraNum").Set(d, cameraNum);

	FILE* fp = fopen(json_path, "wb"); // 非 Windows 平台使用 "w"
	char writeBuffer[65536];
	FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
	Writer<FileWriteStream> writer(os);
	d.Accept(writer);
	fclose(fp);
	PhotoMutex =CreateMutex(NULL, FALSE, (LPCWSTR)"PhotoMutex");

	if (!cap.isOpened()) {
		cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);//宽度 
		cap.set(cv::CAP_PROP_FRAME_HEIGHT, 480);//高度
		cap.set(cv::CAP_PROP_FPS, 30);
		logger->info("准备打开摄像头序号{}", cameraNum);
		cap.open(cameraNum, CAP_DSHOW);
		std::thread t(getNowMat);
		t.detach();
	}
	Sleep(3000);
	logger->info("结束打开摄像头");
	return 0;
}

int WMAI_API GetScaleSetting(int &x1, int &y1, int &width1, int &height1) {
	x1 = x;
	y1 = y;
	width1 = width;
	height1 = height;
	return 0;
}

int WMAI_API SaveScaleSetting(int x1, int y1, int width1, int height1) {
	if (!(width1 && height1))
	{
		logger->info("coordinate error");
		return -2008;
	}

	if (x1 + width1 > 640 || y1 + height1 > 480) {
		logger->info("Scale not match 640*480 x={},y={},w={},h={}", x1, y1, width1, height1);
		return -2008;
	}
	x = x1;
	y = y1;
	width = width1;
	height = height1;

	Document d;

	Pointer("/x").Set(d, x);
	Pointer("/y").Set(d, y);
	Pointer("/width").Set(d, width);
	Pointer("/height").Set(d, height);
	Pointer("/ai_x").Set(d, ai_x);
	Pointer("/ai_y").Set(d, ai_y);
	Pointer("/ai_width").Set(d, ai_width);
	Pointer("/ai_height").Set(d, ai_height);
	Pointer("/cameraNum").Set(d, cameraNum);

	FILE* fp = fopen(json_path, "wb"); // 非 Windows 平台使用 "w"
	char writeBuffer[65536];
	FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
	Writer<FileWriteStream> writer(os);
	d.Accept(writer);
	fclose(fp);
	return 0;
}

int WMAI_API GetScaleBitmap(char* rawPath, char* cropPath) {
	getScaleBitmap(rawPath, cropPath, true);
	return 0;
}

int WMAI_API SetNoRecommend(const char* code) {
	logger->info("开始清除商品:{}的学习记录", code);
	//计时开始
	double start_time = clock();
	CppSQLite3DB db;
	db.open(gszFile);
2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773

	//记录需要删除的id
	int id = 0;
	CppSQLite3Buffer selectFeatureCode;
	selectFeatureCode.format("select id from feature_code where code = %Q;", code);
	CppSQLite3Query q = db.execQuery(selectFeatureCode);
	while (!q.eof())
	{
		id = q.getIntField(0);

		CppSQLite3Buffer insert;
		insert.format("insert into record_count(count) values (%d)", id);
		db.execDML(insert);

		q.nextRow();
	}
	q.finalize();

	// 清除数据库
2774 2775
	if (db.tableExists("feature_code")) {
		CppSQLite3Buffer deleteSql;
2776
		deleteSql.format("update feature_code set deleted = 1 where code = %Q;", code);
2777
		db.execDML(deleteSql);
2778
}
2779 2780 2781 2782 2783
	if (db.tableExists("product_model")) {
		CppSQLite3Buffer deleteSql;
		deleteSql.format("delete from product_model where product_code = %Q", code);
		db.execDML(deleteSql);
	}
2784

2785 2786 2787 2788 2789 2790 2791
	// 清除map
	// productModelMap.erase(code);

	// 重置索引
	delete idx;
	idx = new libhnsw::Index(FEATURE_COUNT, DATABASE_SIZE, libhnsw::BRUTE_FORCE_KNN_CF);
	if (db.tableExists("feature_code")) {
2792
		CppSQLite3Query q = db.execQuery("select id,feature from feature_code where deleted = 0");
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
		while (!q.eof())
		{
			float features[FEATURE_COUNT];
			int id = q.getIntField(0);
			const char* sql_feature = q.getStringField(1);
			char* c = const_cast<char*>(sql_feature);
			split(c, features);
			idx->Addsample(features, id - 1);
			q.nextRow();
		}
		q.finalize();
	}
	db.close();
	double end_time = clock();
	logger->info("all elapsed {}ms\n", end_time - start_time);
	return 0;
}

2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
int WMAI_API ExportData(char* path)
{
#if APPOINT_LIBRARY
	string new_dir = string(drive) + dir;
	char data_path[128] = {};
	std::strcpy(data_path, (new_dir+"data-copy").c_str());

	ifstream in(gszFile, ios::binary);
	ofstream out(data_path, ios::binary);
	if (!in) {
		printf("open file error");
		return -2007;
	}
	if (!out) {
		printf("open file error");
		return -2007;
	}
	char flush[8];
	while (!in.eof()) {
		in.read(flush, 8);
		out.write(flush, in.gcount());
	}
	in.close();
	strcpy(path, data_path);
#else
	ifstream in(gszFile, ios::binary);
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
	ofstream out("data-copy", ios::binary);
	if (!in) {
		printf("open file error");
		return -2007;
	}
	if (!out) {
		printf("open file error");
		return -2007;
	}
	char flush[8];
	while (!in.eof()) {
		in.read(flush, 8);
		out.write(flush, in.gcount());
	}
	in.close();
2852 2853
	std::strcpy(path, "data-copy");
#endif // APPOINT_LIBRARY
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037
	return 0;
}

int WMAI_API ImportData(char* path) {
	// 首先删除文件
	remove("featurexYz.db");
	ifstream in(path, ios::binary);
	ofstream out("featurexYz.db", ios::binary);
	if (!in) {
		printf("open file error");
		return -2007;
	}
	if (!out) {
		printf("open file error");
		return -2007;
	}
	char flush[8];
	while (!in.eof()) {
		in.read(flush, 8);
		out.write(flush, in.gcount());
	}
	in.close();
	out.close();
	// 删除索引文件
	return 0;
}

// 1 代表索引添加 2 代表商品模型关系添加 
//{\"type\":1,\"feature\":\"\",\"productCode\":\"\",\"modelCode\": 1}
void saveOtherMachineIndex(const BYTE* pData, int length) {
	string a = (char*)pData;
	string data = a.substr(0, length);
	logger->info("data is {}", data.c_str());
	CppSQLite3DB db;
	db.open(gszFile);

	StringStream s(data.c_str());
	Document d;
	d.ParseStream(s);
	// 1 代表索引添加 2 代表商品模型关系添加
	int type = d["type"].GetInt();
	if (type == 1) {
		string productCode = d["productCode"].GetString();
		string featureValue = d["feature"].GetString();
		if (!productCode.empty() && !featureValue.empty()) {
			saveDbIndex2(db, productCode.c_str(), featureValue);
		}
		else {
			logger->info("productCode or else null");
		}
	}
	else if (type == 2) {
		Value& items = d["modelCodes"];
		assert(a.IsArray());
		for (SizeType i = 0; i < items.Size(); i++) {
			string productCode = items[i]["productCode"].GetString();
			int modelCode = items[i]["modelCode"].GetInt();
			if (!productCode.empty() && modelCode != 0) {
				CppSQLite3Buffer selectProductModel;
				selectProductModel.format("select count(1) from product_model where product_code = %Q or model_code = %d;", productCode.c_str(), modelCode);
				int productModelCount = db.execScalar(selectProductModel);
				if (productModelCount < 1) {
					// 记录商品模型关系
					CppSQLite3Buffer insertProductModel;
					insertProductModel.format("insert into product_model(product_code, model_code) values (%Q,%d);", productCode.c_str(), modelCode);
					db.execDML(insertProductModel);
				}
			}
			else {
				logger->info("productCode or modelCode null");
			}
		}
	}
	db.close();
}

EnHandleResult ServerListenerImpl::OnHandShake(ITcpServer* pSender, CONNID dwConnID)
{
	logger->info("接收到客户端{}的握手请求,建立连接", dwConnID);
	connIds.push_back(dwConnID);
	return EnHandleResult();
}

EnHandleResult ServerListenerImpl::OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
	logger->info("接收到客户端:{}的关闭请求", dwConnID);

	vector<CONNID>::iterator iter = connIds.begin();
	while (iter != connIds.end())
	{
		if (*iter == dwConnID)
		{
			iter = connIds.erase(iter);
		}
		else
		{
			iter++;
		}
	}
	return EnHandleResult();
}

EnHandleResult ServerListenerImpl::OnReceive(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
	logger->info("服务端Ip:{},接收到客户端: {}的回复", realIp, dwConnID);
	saveOtherMachineIndex(pData, iLength);
	//DWORD count;
	//CONNID connIdAll[maxConnectionCount];
	//bool success = pSender->GetAllConnectionIDs(connIdAll, count);
	//if (!success) {
	//}
	for (long i = 0; i < connIds.size(); i++)
	{
		if (connIds[i] == dwConnID) {
			// 忽略传递过来的Id
			continue;
		}
		pSender->Send(connIds[i], pData, iLength);
	}
	/*else {
		logger->info("获取客户端Id失败");
	}*/
	return EnHandleResult();
}

EnHandleResult ClientListenerImpl::OnReceive(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
	logger->info("客户端ip:{},接收到服务端: {}的消息", realIp, dwConnID);
	saveOtherMachineIndex(pData, iLength);
	return EnHandleResult();
}

/***********************************************************UDP****************************************************************************/

EnHandleResult UdpNodeListenerImpl::OnReceive(IUdpNode* pSender, LPCTSTR lpszRemoteAddress, USHORT usRemotePort, const BYTE* pData, int iLength)
{
	char* ip = TCHAR2char(lpszRemoteAddress);
	if (strncmp(ip, realIp, 16) == 0) {
		// 忽略本身传递的广播
		return EnHandleResult();
	}
	// 如果接到新机器的创建消息
	// 创建客户端连接新机器的服务
	logger->info("接收到地址{}的 UDP NODE 的消息:{},开始注册TCP客户端", ip, pData);
	// 创建新的客户端 连接新的tcp服务端
	createClient(lpszRemoteAddress);
	// 关闭之前的tcp服务端
	if (s_pserver->HasStarted()) {
		logger->info("关闭ip:{}的tcp服务", realIp);
		s_pserver->Stop();
	}
	return EnHandleResult();
}

EnHandleResult UdpNodeListenerImpl::OnError(IUdpNode* pSender, EnSocketOperation enOperation, int iErrorCode, LPCTSTR lpszRemoteAddress, USHORT usRemotePort, const BYTE* pData, int iLength)
{
	return EnHandleResult();
}

int WMAI_API ClearTrainedData() {
	if (exists_file(gszFile)) {
		int res = remove(gszFile);
		if (res != 0) {
			logger->info("hnswIndex dose not exist\n");
		}
		else {
			logger->info("remove gszfile successed\n");
		}
	}
	delete idx;
	return 0;
}

int WMAI_API Test50000(char* code, char* path) {
	cv::Mat m = cv::imread(path, 1);
	if (m.empty())
	{
		logger->info("cv::imread failed\n");
		return -2002;
	}
	string productcode[10];
	std::vector<float> cls_scores;
	float rhs[FEATURE_COUNT];
	double start_time = ncnn::get_current_time();
3038
	int ret = detect_squeezenet(m, cls_scores, rhs);
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077

	// 将图片向量进行逗号组装
	char featureValue[FEATURE_COUNT * 10] = { };
	for (int i = 0; i < FEATURE_COUNT; ++i)
	{
		sprintf(featureValue + strlen(featureValue), "%f,", rhs[i]);
	}
	string tmp2 = featureValue;
	CppSQLite3DB db;
	db.open(gszFile);
	saveDbIndex(db, code, tmp2);
	db.close();

	std::vector<std::pair<float, int>>res = idx->Search(rhs, 1);
	for (int j = 0; j < res.size(); j++)
	{
		std::pair<float, int> r = res[j];
		int number = r.second;
		logger->info("index label is {}",number);
	}
	return 0;
}



int WMAI_API WMrelease() {
	if (cap.isOpened()) {
		cap.release();
	}
	if (udp_node->HasStarted()) {
		udp_node->Stop();
	}
	if (s_pclient->HasStarted()) {
		s_pclient->Stop();
	}
	if (s_pserver->HasStarted()) {
		s_pserver->Stop();
	}
	delete idx;
3078
	//delete hnswExecutor;
3079
	param_in.end_thread = true;
zzx's avatar
zzx committed
3080
	RETRI_Release(&handle);
3081
	init_finish = false;
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
	return 0;
}

int WMAI_API Close() {
	logger->info("释放资源开始");
	if (cap.isOpened()) {
		cap.release();
	}
	if (udp_node->HasStarted()) {
		udp_node->Stop();
	}
	if (s_pclient->HasStarted()) {
		s_pclient->Stop();
	}
	if (s_pserver->HasStarted()) {
		s_pserver->Stop();
	}
3099 3100 3101 3102 3103 3104
	if (idx != nullptr)
	{
		delete idx;
		idx = nullptr;
	}

3105
	param_in.end_thread = true;
zzx's avatar
zzx committed
3106
	RETRI_Release(&handle);
3107
	init_finish = false;
3108 3109
	logger->info("释放资源结束");
	
3110 3111 3112 3113 3114 3115 3116 3117
	return 0;
}

int FoodInitParam(FOOD_PARAM_DATA* param_in)
{
	_mkdir("data");

	// step1:先配置下数据源
zzx's avatar
zzx committed
3118
	param_in->back_mat_path = "data/back.jpg";
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
	param_in->debug_mode = false;

	// step2:配置roi
	param_in->has_roi = true;
	cv::Rect roi;
	roi.x = ai_x;
	roi.y = ai_y;
	roi.width = ai_width;
	roi.height = ai_height;
	param_in->roi = roi;

zzx's avatar
zzx committed
3130

3131 3132 3133


	//step4.裁剪下当前帧照片,保存当前图片
zzx's avatar
zzx committed
3134 3135 3136 3137
	param_in->back =cv::imread(param_in->back_mat_path);
	if (param_in->back.empty()) {
		param_in->back = frame_pipe.clone();
		if (param_in->back.empty()) {
3138 3139 3140
			logger->info("图片是空的,\n");
			return -2002;
		}
zzx's avatar
zzx committed
3141

3142 3143
		if (roi.area() != 0)
		{
zzx's avatar
zzx committed
3144
			param_in->back = param_in->back(roi);
3145 3146 3147
		}

		char pathName[128] = {};
zzx's avatar
zzx committed
3148
		sprintf(pathName, "%s", param_in->back_mat_path.c_str());
3149
		logger->info("要保存的文件路径[{}]\n", pathName);
zzx's avatar
zzx committed
3150
		cv::imwrite(pathName, param_in->back);
3151 3152 3153 3154 3155 3156 3157 3158 3159
	}

	// step3:
	param_in->end_thread = false;
	param_in->max_in_frame_queue = 6;
	param_in->queue_max = 5;
	//step(-1):是否启用调试
	param_in->debug_mode = debug;

3160
	libvideopipe::INIT_INFO video_pipe;
3161 3162
	//video_pipe.gpu_enable = drive_ai;
	video_pipe.gpu_enable =true;
zzx's avatar
zzx committed
3163 3164 3165
	video_pipe.lat3d_enable = true;
	param_in->mvp = new libvideopipe::MotionVideoPipe;
	param_in->mvp->Init(video_pipe);
3166

3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
	solve_cost.push_back(67);
	return 0;
}

UINT64 food_get_current_time_millis()
{
	using namespace std;

	timeb now;
	ftime(&now);
	std::stringstream milliStream;
	// 由于毫秒数不一定是三位数,故设置宽度为3,前面补0
	milliStream << setw(3) << setfill('0') << right << now.millitm;

	stringstream secStream;
	secStream << now.time;
	string timeStr(secStream.str());
	timeStr.append(milliStream.str());

	UINT64 timeLong;
	stringstream transStream(timeStr);
	transStream >> timeLong;

	return timeLong;
}


DWORD WINAPI FoodRealtimeCaptureImage(LPVOID params)
{
	FOOD_PARAM_DATA* param_in = (FOOD_PARAM_DATA*)params;
	if (!param_in)
	{
		logger->info("FoodRealtimeCaptureImage:param_in NULL!\n", GetCurrentThreadId());
		return 0;
	}

	while (!(param_in->end_thread))
	{
3205
		//float start = clock();
3206 3207
		Sleep(average_cost());
		// step1:获取当前帧
3208

3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
		Mat img = frame_pipe.clone();

		// step2:判断当前帧是否为空
		if (img.empty())
		{
			logger->info("PID[{}]ERROR: get img error!\n", GetCurrentThreadId());
			param_in->end_thread = true;
			continue;
		}

		// step3:配置FRAME_INFO
zzx's avatar
zzx committed
3220
		VIDEO_FRAME_INFO frame;
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239
		frame.timestamp = food_get_current_time_millis();
		if (param_in->roi.area() == 0)
			param_in->has_roi = false;
		if (param_in->has_roi) {
			frame.img = img(param_in->roi);
		}
		else {
			frame.img = img;
		}
		// step4:压入一个frame
		param_in->frame_in.push(frame);
		//step5:如果上一帧未处理,则丢帧
		if (param_in->frame_in.size() > param_in->max_in_frame_queue)
		{
			logger->info("图片堆积");
			WaitForSingleObject(param_in->hMutex, INFINITE);
			param_in->frame_in.pop();  // 删除一个原图
			ReleaseMutex(param_in->hMutex);
		}
3240
		//float end = clock();
3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
		//logger->info("get image cost:{}", end - start); 
	}
	return 1;
}



void trace_detect_process()
{
	char rawPath[128];
	char cropPath[128];

	result.state = true;
3254
	Sleep(150);
3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
	cv::Mat m = getScaleBitmap(rawPath, cropPath,false);
	if (m.empty())//获取图片失败编写日志
	{
		logger->info("cv::imread failed\n");
		return;
	}
	int ret = MatDetect(m, result.productCodes, result.sessionId);
	if (ret != 0)
	{
		logger->info("Detect error:{}",ret);
		return;
	}
	if (param_in.result_queue.size()< param_in.queue_max) 
	{
		DETECT_RESULT tem = result;
		param_in.result_queue.push(tem);
	}
}

3274 3275 3276 3277 3278 3279 3280
void trace_judge_process()
{
	Sleep(100);
	char path[128] = {};
	char row_path[128] = {};
	GetScaleBitmap(row_path, path);
	param_in.detect_image_path = string(path);
3281
}
3282

3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
void save_in_image()
{
	std::string dir = "video_image_in"; logger->info("{}", __LINE__);
	std::string time = std::to_string(food_get_current_time_millis()); logger->info("{}", __LINE__);

	_mkdir(dir.c_str()); logger->info("{}", __LINE__);
	_mkdir((dir + "/" + time).c_str()); logger->info("{}", __LINE__);

	int i = 1;
	const char* path = "%s/%s/%s-%d.jpg";
	char name2[128] = {};
	char name3[128] = {};
	char name4[128] = {};
3296 3297 3298 3299
	vector<string>res;
	string pre1;
	string pre2;
	string pre3;
3300
	sprintf(name2, path, dir.c_str(), time.c_str(), time.c_str(), i++); 
3301 3302
	pre1 = pre1 + time.c_str() + "-" + "1" + ".jpg";
	res.push_back(pre1);
3303 3304
	cv::imwrite(name2, param_in.back);
	sprintf(name3, path, dir.c_str(), time.c_str(), time.c_str(), i++); 
3305 3306
	pre2 = pre2 + time.c_str() + "-" + "2" + ".jpg";
	res.push_back(pre2);
3307 3308
	cv::imwrite(name3, param_in.frame_out[3].img);
	sprintf(name4, path, dir.c_str(), time.c_str(), time.c_str(), i++); 
3309 3310
	pre3 = pre3 + time.c_str() + "-" + "3" + ".jpg";
	res.push_back(pre3);
3311
	cv::imwrite(name4, param_in.frame_out[4].img);
3312 3313 3314 3315 3316 3317 3318 3319

	char in[10] = "IN";
	res.push_back(in);
	for (int i = 0; i < res.size(); i++)
	{
		logger->info("res:{}", res[i].c_str());
	}
	if (rest_in < 10)
3320
	{
3321
		rest_in++;
3322 3323 3324 3325 3326
		Document d;
		string response;
		char uploadUrl[200];
		string tenantStrs = "0";
		sprintf(uploadUrl, upload_file1_url, dev.c_str(), tenantStrs.c_str());
3327
		logger->info("upload url is {},     imagePath is {}", uploadUrl, name4);
3328
		
3329
		int curlCode = CommonTools::upload_file1(uploadUrl,name2,name3,name4,res,response);
3330 3331 3332 3333 3334 3335 3336 3337 3338
		//logger->info("response is {},curl code is {}", response.c_str(), curlCode);
		string rrr= UTF_82ASCII(response);
		logger->info("rrr is {}",rrr);
		logger->info("response is {}",response.c_str());
		if (curlCode != 0) {
			logger->info("上传图片失败,退出");
			return;
		}
		
3339
	}
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
}

void save_out_image()
{
	std::string dir = "video_image_out";
	std::string time = std::to_string(food_get_current_time_millis());

	_mkdir(dir.c_str());
	_mkdir((dir + "/" + time).c_str());

	int i = 1;
	const char* path = "%s/%s/%s-%d.jpg";
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
	char name5[128] = {};
	char name6[128] = {};
	char name7[128] = {};
	vector<string>res1;
	string buf1, buf2, buf3;
	sprintf(name5, path, dir.c_str(), time.c_str(), time.c_str(), i++);
	buf1 = buf1 + time.c_str() + "-" + "1" + ".jpg";
	res1.push_back(buf1);
	cv::imwrite(name5, param_in.back);
	sprintf(name6, path, dir.c_str(), time.c_str(), time.c_str(), i++);
	buf2 = buf2 + time.c_str() + "-" + "2"+".jpg";
	res1.push_back(buf2);
	cv::imwrite(name6, param_in.frame_out[3].img);
	sprintf(name7, path, dir.c_str(), time.c_str(), time.c_str(), i++);
	buf3 = buf3 + time.c_str() + "-" + "3" + ".jpg";
	res1.push_back(buf3);
	cv::imwrite(name7, param_in.frame_out[4].img);
	string out = "OUT";
	res1.push_back(out);
	if (rest_out < 10)
	{
		rest_out++;
		Document d;
		string response;
		char uploadUrl[200];
		string tenantStrs = "0";
		sprintf(uploadUrl, upload_file1_url, dev.c_str(), tenantStrs.c_str());
		logger->info("upload url is {},     imagePath is {}", uploadUrl, name5);
3380

3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
		int curlCode = CommonTools::upload_file1(uploadUrl, name5, name6, name7,res1, response);
		//logger->info("response is {},curl code is {}", response.c_str(), curlCode);
		string rrr = UTF_82ASCII(response);
		logger->info("rrr is {}", rrr);
		logger->info("response is {}", response.c_str());
		if (curlCode != 0) {
			logger->info("上传图片失败,退出");
			return;
		}

	}
3392 3393
}

zzx's avatar
zzx committed
3394
void video_trace_result_callback(const char* data, int len, void* user)
3395 3396
{
	// AI识别
zzx's avatar
zzx committed
3397 3398 3399
	libvideopipe::MOTION_VIDEOPIPE_OUTPUT* output = (libvideopipe::MOTION_VIDEOPIPE_OUTPUT*)data;

	if (output->status == libvideopipe::MOTION_STATUS_TYPES::MOTION_IN)
3400 3401
	{
		logger->info("检测到物品进入");
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
		if (mode == FRESH_DETECT)
		{
			thread t(trace_detect_process);                logger->info("{}", __LINE__);
			t.detach();                                    logger->info("{}", __LINE__);
			thread t_(save_in_image);                      logger->info("{}", __LINE__);
			t_.detach();                                   logger->info("{}", __LINE__);
		}
		else if (mode == PREVENT_LOSS)
		{
			thread t(trace_judge_process);                 logger->info("{}", __LINE__);
			t.detach();                                    logger->info("{}", __LINE__);
			//thread t_(save_in_image);
			//t_.detach();
			//logger->info("没有进行存图!");
			if (param_in.result_queue.size() < param_in.queue_max)
			{
				DETECT_RESULT tem = result; logger->info("{}", __LINE__);
				tem.state = true; logger->info("{}", __LINE__);
				param_in.result_queue.push(tem); logger->info("{}", __LINE__);
			}
		}
3423
	}
zzx's avatar
zzx committed
3424
	if (output->status == libvideopipe::MOTION_STATUS_TYPES::MOTION_OUT)
3425
	{
3426
		logger->info("检测到物品离开");                    logger->info("{}", __LINE__);
3427 3428
		thread t_(save_out_image);                        
		t_.detach();                                      
3429 3430
		if (param_in.result_queue.size() < param_in.queue_max)
		{
3431 3432 3433
			DETECT_RESULT tem = result;                   
			tem.state = false;                             
			param_in.result_queue.push(tem);              
3434 3435 3436 3437 3438 3439 3440
		}
	}
}

DWORD WINAPI FoodDetectTrace(LPVOID params)
{

3441
	auto start = clock();
3442 3443 3444 3445 3446 3447 3448 3449
	FOOD_PARAM_DATA* param_in = (FOOD_PARAM_DATA*)params;
	if (param_in == NULL)
	{
		logger->info("FoodDetectTrace:param_in NULL!\n");
		return 0;
	}

	// step0:初始化一个跟踪器
zzx's avatar
zzx committed
3450 3451 3452
	param_in->mvp->SetROI(param_in->roi);
	param_in->mvp->SetMarkMat(param_in->back);
	param_in->mvp->SetResultCallback(video_trace_result_callback, param_in);
3453 3454

	g_video_init = true;
3455
	logger->info("videopipe init end");
3456 3457 3458

	while (!param_in->end_thread)
	{
3459
		
3460 3461 3462 3463 3464 3465 3466
		// step1:判断帧数据是否为空
		if (param_in->frame_in.empty())
		{
			Sleep(30);
			in_image = false;
			continue;
		}
3467
		
zzx's avatar
zzx committed
3468
		//处理图像开始
3469 3470
		in_image = true;
		float start = clock();
zzx's avatar
zzx committed
3471

3472
		// step2:获取输入数据
zzx's avatar
zzx committed
3473
		WaitForSingleObject(param_in->hMutex, INFINITE);
zzx's avatar
zzx committed
3474
		VIDEO_FRAME_INFO frame;
3475 3476 3477 3478
		frame = param_in->frame_in.front();
		param_in->frame_in.pop();  // 删除一个原图
		ReleaseMutex(param_in->hMutex);

3479 3480 3481 3482 3483 3484
		param_in->frame_out.push_back(frame);
		if (param_in->frame_out.size() > param_in->max_in_frame_queue)
		{
			param_in->frame_out.erase(param_in->frame_out.begin());
		}

3485 3486

		// step3:设置video input
zzx's avatar
zzx committed
3487
		libvideopipe::MOTION_VIDEOPIPE_INPUT video_input;
3488 3489
		video_input.img = frame.img.clone();
		video_input.pts = frame.timestamp;
3490
		video_input.debug_mode = false;
3491 3492 3493 3494 3495 3496 3497 3498

		// step4:是否显示调试的视频
		if (param_in->debug_mode == true)
		{
			imshow("frame.img", video_input.img);
			cv::waitKey(1);
		}

3499 3500
		// step5:开始Trace;
		//float _start = clock();
zzx's avatar
zzx committed
3501
		int rt = param_in->mvp->FeedFrame(video_input);
3502 3503
		//float _end = clock();
		//logger->info("FeedFrame costs {} ms \n",_end - _start);
3504 3505 3506 3507
		if (rt != 0)
		{
			logger->info("Trace return error code:{0:x}\n", rt);
		}
zzx's avatar
zzx committed
3508

3509 3510 3511 3512 3513 3514
		cv::waitKey(3);
		float end = clock();
		solve_cost.push_back(end-start);
		//logger->info("dev solve cost:{}", end - start);

	}
3515
	return 0;
3516 3517
}

3518 3519 3520 3521
void videoPipeDetect() 
{

	logger->info("videopipe init start");
3522
	FoodInitParam(&param_in);
3523

3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536
	// step1: 开线程测试
	const int MAX_THREADS = 2;
	HANDLE hThread[MAX_THREADS];
	hThread[0] = CreateThread(NULL, 0, FoodRealtimeCaptureImage, &param_in, 0, NULL);
	hThread[1] = CreateThread(NULL, 0, FoodDetectTrace, &param_in, 0, NULL);
	param_in.hMutex = CreateMutex(NULL, FALSE, (LPCWSTR)"screen");
	// step2: Wait until all threads have terminated.
	WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE);
	for (int i = 0; i < MAX_THREADS; i++)
	{
		CloseHandle(hThread[i]);
	}
	ReleaseMutex(param_in.hMutex);
zzx's avatar
zzx committed
3537
	delete param_in.mvp;
3538
	g_video_init = false;
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
	logger->info("process end");

}

//识别函数主控
int WMAI_API VideoPipeDetect() {
	thread t(videoPipeDetect);
	t.detach();
	return 0;
}

int WMAI_API GetQueueSize()
{
	if (re_ret)
	{
		return 0;
	}
	int ret = param_in.result_queue.size();
	if (ret > 0) {
		re_ret = true;
	}
	return ret;
}

int WMAI_API RealTimeDetect(char* code, char* sessionId, bool &state)
{
	if (param_in.result_queue.size() <= 0) {
		logger->info("error get result");
		return -5009;
	}
	logger->info("productCodes:{},sessionId:{},state:{}", param_in.result_queue.front().productCodes, param_in.result_queue.front().sessionId, param_in.result_queue.front().state);
3570 3571
	std::strcpy(code, param_in.result_queue.front().productCodes);
	std::strcpy(sessionId, param_in.result_queue.front().sessionId);
3572 3573 3574 3575 3576 3577 3578 3579 3580
	state = param_in.result_queue.front().state;
	param_in.result_queue.pop();
	re_ret = false;
	return 0;
}

void uploadImage() {
	Document d;
	string response;
3581
	char uploadUrl[200];
3582
	sprintf(uploadUrl, upload_file_url, dev.c_str(), tenantStr.c_str());
zzx's avatar
zzx committed
3583 3584
	logger->info("upload url is {},imagePath is {}", uploadUrl, param_in.back_mat_path.c_str());
	int curlCode = CommonTools::upload_file(uploadUrl, param_in.back_mat_path.c_str(), response);
3585
	//logger->info("response is {},curl code is {}", response.c_str(), curlCode);
3586 3587 3588 3589 3590
	if (curlCode != 0) {
		logger->info("上传图片失败,退出");
		return;
	}
	d.Parse(response.c_str());
3591
	int resultCode = d["code"].GetInt(); 
3592
	if (resultCode == 0) {
3593
		Value& s1 = d["data"]["url"]; 
3594 3595 3596 3597
		if (s1.IsNull()) {
			logger->info("上传失败");
			return;
		}
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
		string imageUrl = s1.GetString(); 
		d.Clear(); 

		Pointer("/recommendTime").Set(d, 0); 
		Pointer("/weightingStartTime").Set(d, getNowDate()); 
		Pointer("/weighImageUrl").Set(d, imageUrl); 
		Pointer("/aiType").Set(d, "WINMORE"); 
		Pointer("/identifyCode/code").Set(d, to_string(99999)); 
		Pointer("/identifyCode/accuracy").Set(d, 0.001); 
		StringBuffer buffer; 
		Writer<StringBuffer> writer(buffer); 
		d.Accept(writer); 

		char url[100]; 
		sprintf(url, save_record_url, dev.c_str(), tenantStr.c_str()); 
3613 3614 3615 3616
		logger->info("url:{}",url);

		string response2;
		CommonTools::HttpPost(url, buffer.GetString(), response2, 3);
3617
		//logger->info("response2:{}", response2);
3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
	}
	else {
		logger->info("upload error url is {}, error code is {}", uploadUrl, resultCode);
	}
}

int WMAI_API ChangeBackPicture() 
{	//step1.获取图像
	logger->info("改变空盘图像开始");
	cv::Mat img = frame_pipe.clone();
	if (img.empty()) {
		logger->info("图片是空的,\n");
		return -2002;
	}

	//step2.裁剪下当前帧照片,保存当前图片
	cv::Rect roi;
	roi.x = ai_x ;
	roi.y = ai_y ;
	roi.width = ai_width;
	roi.height = ai_height;
	if (roi.area() == 0)
	{
		logger->info("裁剪错误");
		return -2002;

	}
	param_in.roi = roi;
	param_in.has_roi = true;
	cv::Mat imgRoi = img(param_in.roi);

	char pathName[128] = {};
zzx's avatar
zzx committed
3650
	sprintf(pathName, "%s", param_in.back_mat_path.c_str());
3651 3652 3653
	cv::imwrite(pathName, imgRoi);

	//step3.置换
3654
	param_in.back = imgRoi;
zzx's avatar
zzx committed
3655
	param_in.mvp->SetMarkMat(imgRoi);
3656 3657
	logger->info("改变空盘图像结束");

3658

3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681
	//step4.上传图片
	thread t(uploadImage);
	t.detach();
	return 0;
}


int WMAI_API Probation()
{
	string mac;
	GetMacByGetAdaptersAddresses(mac);

	Document d;
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);

	char url[200];
	sprintf(url, wmpos_probation_url, dev.c_str(), mac.c_str());
	logger->info("url is {}", url);

	string response;
	CommonTools::HttpGet(url, response, 3);
3682
	logger->info("reponse is {}", UTF_82ASCII(response));
3683 3684 3685
	d.Parse(response.c_str());
	Value& s = d["code"];
	if (s.GetInt() == 0) {
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699


#if APPOINT_LIBRARY
		string new_dir = string(drive) + dir;
		char wmkey_path[MAX_PATH];
		strcpy(wmkey_path, (new_dir + "pwmkey.wm").c_str());
		const char* wmkey = wmkey_path;
		char prikey_path[MAX_PATH];
		strcpy(prikey_path, (new_dir + "pprikey.pem").c_str());
		const char* prikey = prikey_path;
#else
		string wmkey = "pwmkey.wm";
		string prikey =  "pprikey.pem";
#endif // 0
3700 3701
		string wmKeyUrl = d["data"]["wmKeyUrl"].GetString();
		string privateKeyUrl = d["data"]["privateKeyUrl"].GetString();
3702 3703 3704 3705
		//const char* wmkey = "pwmkey.wm";
		//const char* prikey = "pprikey.pem";
		CommonTools::download_file(wmKeyUrl.c_str(), wmkey.c_str());
		CommonTools::download_file(privateKeyUrl.c_str(), prikey.c_str());
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748
		return 0;
	}
	else if (s.GetInt() == 65021) {
		logger->info("试用码已过期");
		return -4010;
	}
	else{
		logger->info("probation failed errorCode: {}", s.GetInt());
		return -4011;
	}
}

int WMAI_API WriteLog(const char* txt)
{
	logger->info("node:{}",txt);
	return 0;
}

int WMAI_API SetLogoCoordinate(int x1,int y1,int width1,int height1)
{
	if (!(width1 && height1))
	{
		logger->info("coordinate error");
		return -2008;
	}

	ai_x = x1;
	ai_y = y1;
	ai_width = width1;
	ai_height = height1;

	Document d;
	Pointer("/x").Set(d, x);
	Pointer("/y").Set(d, y);
	Pointer("/width").Set(d, width);
	Pointer("/height").Set(d, height);
	Pointer("/ai_x").Set(d, ai_x);
	Pointer("/ai_y").Set(d, ai_y);
	Pointer("/ai_width").Set(d, ai_width);
	Pointer("/ai_height").Set(d, ai_height);
	Pointer("/cameraNum").Set(d, cameraNum);

	FILE* fp = fopen(json_path, "wb"); // 非 Windows 平台使用 "w"
zzx's avatar
zzx committed
3749
	char *writeBuffer = (char *)calloc(65536,sizeof(char));
3750 3751 3752 3753
	FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
	Writer<FileWriteStream> writer(os);
	d.Accept(writer);
	fclose(fp);
zzx's avatar
zzx committed
3754 3755
	free(writeBuffer);
	return 0;
3756 3757
}

zzx's avatar
zzx committed
3758 3759
int WMAI_API inputPluToDetect(char *code,char *sessionId)
{
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
	if (g_video_init && init_finish) 
	{
		param_in.scan = true;
		char detected_code[100] = {};
		char path[128] = {};
		doSnacksAutoDetect(detected_code, sessionId, path);
		param_in.detect_image_path = string(path);
		if (detected_code[0] == '\0')
		{
			logger->info("没有检测出该商品");;
			return -6001;
		}
		if (strstr(detected_code, code) == nullptr)
		{
			logger->info("没有检测出该商品");
			return -6001;
		}
		return 0;
zzx's avatar
zzx committed
3778
	}
3779
	else
zzx's avatar
zzx committed
3780
	{
3781
		return -6002;
zzx's avatar
zzx committed
3782
	}
3783

zzx's avatar
zzx committed
3784 3785 3786 3787
}

int WMAI_API getDetectImage(char* path)
{
3788
	logger->info("image_path:{}", param_in.detect_image_path);
3789
	std::strcpy(path,param_in.detect_image_path.c_str());
3790
	logger->info("path:{}", path);
zzx's avatar
zzx committed
3791 3792 3793 3794 3795 3796 3797 3798 3799
	return 0;
}

bool WMAI_API judgeScanTheCode()
{
	bool ret = param_in.scan;
	param_in.scan = false;
	return ret;
}
3800

3801 3802 3803 3804
bool WMAI_API getVideopipeInit()
{
	return g_video_init;
}
3805

3806 3807 3808 3809 3810
bool WMAI_API ReturnCameraState()
{
	return cap.isOpened();
}

zzx's avatar
zzx committed
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883

//纠错
int WMAI_API FreshChangeError(const char* code)
{


	//检测表单是否存在
	CppSQLite3DB db;                                    
	db.open(gszFile);                                  
	if (!db.tableExists("feature_code")) {
		return 0;                                       
	}

	int r = reassion[code];                      
	int number = r; 
	float feature_a[FEATURE_COUNT]; 

	CppSQLite3Buffer selectFeatureCode; 
	selectFeatureCode.format("select code,feature,id from feature_code where id = %d;", number); 
	CppSQLite3Query q = db.execQuery(selectFeatureCode); 

	//接收数据搜索结果
	int id;                                                                       
	std::string sql_code;                                                         
	while (!q.eof())
	{
		sql_code = q.getStringField(0);                                           
		const char* sql_feature = q.getStringField(1);
		id = q.getIntField(2);                                                   
		char* feature_c = const_cast<char*>(sql_feature); 
		split(feature_c, feature_a); 
		q.nextRow();
	}
	q.finalize();

	//根据返回的plu查询结果
	std::vector<std::pair<float, int>>res = idx->Search(feature_a, 10); 
	for (unsigned int j = 0; j < res.size(); j++)
	{

		//索引结果
		std::pair<float, int> f = res[j];                                   
		logger->info("res[{}]={} {}\n", j, f.first, f.second);              

		//idx的id与数据库id有 1 的偏差
		int number = f.second + 1;
		float feature_f[FEATURE_COUNT];

		CppSQLite3Buffer selectFeatureCode;                                
		selectFeatureCode.format("select code,feature,id from feature_code where id = %d;", number);
		CppSQLite3Query q = db.execQuery(selectFeatureCode);                

		//接收数据搜索结果
		int id; 
		std::string sql_code;
		
		while (!q.eof())
		{
			sql_code = q.getStringField(0);
			const char* sql_feature = q.fieldValue(1);                      
			id = q.getIntField(2);															
			char* feature_c = const_cast<char*>(sql_feature);                
			split(feature_c, feature_f);                 
			q.nextRow();
		}
		q.finalize();

		float similarity = calculSimilar(feature_a, feature_f, FEATURE_COUNT);        
                                                                                                                                                        
		if (sql_code == string(code) && similarity > ERROR_SIMILARITY)
		{
			//删除相似度高的数据
			CppSQLite3Buffer deleted_sql;
3884
			deleted_sql.format("update feature_code set deleted = 1, update_time = datetime('now','localtime') where id = %d", number);
zzx's avatar
zzx committed
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898
			db.execDML(deleted_sql);
			idx->Removesample(f.second);
			q.finalize();
		}
	}

	reassion.clear();                                                       
	db.close();                                                              
	return 0;
}



//自动配图
3899
int WMAI_API SelectByName(char* name , char* code, char* image)
zzx's avatar
zzx committed
3900 3901
{

3902 3903 3904 3905 3906 3907 3908 3909 3910 3911
	if (!authed) {
		authed = authorize();
		if (!authed) {
			logger->info("验证失败");
			return -2001;
		};
	}
	string utf_name(name);
	logger->info("input name{}",UTF_82ASCII(utf_name));

zzx's avatar
zzx committed
3912 3913 3914 3915 3916 3917 3918 3919 3920
	Document d;
	d.SetObject();
	Document::AllocatorType& a = d.GetAllocator();


	Value array(kArrayType);
	Value o1(kObjectType);


3921
	Value v1(name, a);
zzx's avatar
zzx committed
3922 3923 3924 3925
	Value v2(code, a);

	o1.AddMember("productName", v1, a);
	o1.AddMember("productNumber", v2, a);
3926
	array.PushBack(o1, a);
zzx's avatar
zzx committed
3927 3928 3929

	d.AddMember("productList", array, d.GetAllocator());

3930 3931 3932 3933 3934
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);
	string buffer1 = buffer.GetString();
	string buffer2 = UTF_82ASCII(buffer1);
zzx's avatar
zzx committed
3935 3936

	char uploadUrl[200];
3937
	string tenant3;
zzx's avatar
zzx committed
3938

3939
	if (tenantStr.size() != 0)
zzx's avatar
zzx committed
3940
	{
3941 3942 3943 3944 3945 3946
		tenant3 = tenant3 + tenantStr;
	}
	else if (tenantStr.size() == 0)
	{
		tenant3 = tenant3 + '0';
	}
zzx's avatar
zzx committed
3947

3948 3949 3950 3951 3952 3953 3954
	sprintf(uploadUrl, pictured_json_url, dev.c_str(), tenant3.c_str());
	string response;
	logger->info("uploadUrl:{}", uploadUrl);
	CommonTools::HttpPost(uploadUrl, buffer.GetString(), response, 3);
	logger->info("reponse is {}", UTF_82ASCII(response));

	d.Parse(response.c_str());
zzx's avatar
zzx committed
3955 3956
	Value& s = d["code"];
	if (s.GetInt() == 0) {
3957
#if 0
zzx's avatar
zzx committed
3958
		string out;
3959
		for (int i = 0; i < response.size() - 1; i++)
zzx's avatar
zzx committed
3960
		{
3961
			if (response[i] == 'h' && response[i + 1] == 't')
zzx's avatar
zzx committed
3962
			{
3963
				for (int j = i; j < response.size(); j++)
zzx's avatar
zzx committed
3964
				{
3965
					if (response[j] == '"')
zzx's avatar
zzx committed
3966 3967 3968
					{
						break;
					}
3969
					out += response[j];
zzx's avatar
zzx committed
3970 3971 3972 3973 3974 3975 3976 3977 3978
				}
			}
		}

		if (out.size() <= 0)
		{
			logger->info("该名称没有找到图片");
			return -1;
		}
3979 3980 3981 3982 3983 3984 3985

		//string  out1 = UTF_82ASCII(out);
		strcpy(image, out.c_str());
#else
		Value& pro_list = d["data"]["productList"].GetArray();

		if (pro_list.Empty())
zzx's avatar
zzx committed
3986
		{
3987
			logger->info("该名称没有找到图片");
zzx's avatar
zzx committed
3988 3989 3990
			return -1;
		}

3991
		string iup = pro_list[0]["matchProductUrl"].GetString();
zzx's avatar
zzx committed
3992

3993
		strcpy(image, iup.c_str());
zzx's avatar
zzx committed
3994

3995 3996 3997 3998 3999 4000
#endif
	}
	else
	{
		logger->info("匹配图片失败");
		return -1;
zzx's avatar
zzx committed
4001 4002 4003 4004
	}
	return 0;
}