WmAceKG-x86.cpp 112 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
#define FRESH_DETECT 0
#define PREVENT_LOSS 1
70 71
#define VIDEOCOUNT   49
#define VIDEOCOINTIN 49
zzx's avatar
zzx committed
72 73
//纠错存 code和id
unordered_map<string, int>reassion;
74
string realProductCodes[10];
zzx's avatar
zzx committed
75

76 77 78
//空盘图向量
float feature_empty[FEATURE_COUNT];

79 80
//视频流存图
int rest_count;
81 82
int rest_in = 0;
int rest_out = 0;
83 84 85 86 87
using namespace std;
using namespace cv;
using namespace rapidjson;


zzx's avatar
zzx committed
88
struct VIDEO_FRAME_INFO
89 90 91 92 93 94 95 96 97
{
	UINT64 timestamp; // 时间戳
	Mat img;
};

struct DETECT_RESULT
{
	char productCodes[100];
	char sessionId[100];
98
	int state;
99 100 101 102
};

struct FOOD_PARAM_DATA
{
zzx's avatar
zzx committed
103 104 105 106 107 108 109 110 111 112 113
	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
114
	vector<VIDEO_FRAME_INFO>  frame_out;	// q2
zzx's avatar
zzx committed
115 116 117 118 119 120 121 122 123

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

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

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

zzx's avatar
zzx committed
124
	string detect_image_path;
zzx's avatar
zzx committed
125
	bool scan;													//是否扫描
126 127 128 129 130 131 132 133
};

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

//文件的路径
134
const char *gszFile = "featurexYz.db";
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
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;
151 152 153

int mode;

154 155 156 157 158 159 160 161 162 163 164 165 166 167
// 版本文本
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";
168 169
// 上传视频流的照片文件
const char* upload_file1_url = "%s.wmdigit.com/%s/newretail/api/dfs/upload2";
170 171 172 173 174 175
// 重置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
176 177
//自动配图
const char* pictured_json_url = "%s.wmdigit.com/%s/newretail/api/mall/productMatch/match";
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

// 是否连接网络
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;

202
string wmphoto_path = "WMPhoto";
203 204 205

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

207 208 209 210 211 212 213 214

// posId
string posId;

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

libbm25::Index *match_map = nullptr;

zzx's avatar
zzx committed
215
//视频流算法参数
216 217
float MarkThreshold;
float AiMarkThreshold;
218

zzx's avatar
zzx committed
219 220

//是否使用gpu和ai
221
bool using_ai = true;
222
bool drive_ai = 1;
zzx's avatar
zzx committed
223 224

//元芒加速库句柄
225
void* handle = nullptr;
zzx's avatar
zzx committed
226 227

//debug模式
228
bool debug = false;
zzx's avatar
zzx committed
229 230

//抓图线程安全
231
HANDLE PhotoMutex;
zzx's avatar
zzx committed
232 233

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

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

//扫描开始,停止视频流
bool plu_input_stop_video = false;
241 242 243

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

245
//防止多次初始化
246
bool init_finish = false;
247 248 249 250

// 是否触发视频流识别
bool video_detect = true;

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
/*******************************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);


275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
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;
}

318 319 320 321 322 323 324 325 326 327
float average_cost()
{
	if(solve_cost.size() == 0 && (!in_image))
	{
		return 67;
	}
	while (solve_cost.size() == 0 && in_image)
	{
		Sleep(100);
	}
328
	float ret = solve_cost[0];
329
	solve_cost.erase(solve_cost.begin());
330 331 332 333
	if (ret > 3000)
	{
		ret = 3000;
	}
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
	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++)
		{
427
			s_pserver->Send(connIds[i], (const BYTE*)buffer.GetString(), buffer.GetLength());
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
		}
	}
	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;
}

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
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;
}

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
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")) {
773
		CppSQLite3Query q = db.execQuery("select id,feature from feature_code where deleted = 0");
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
		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
790
int retri_Init() {
791 792 793
	logger->info("初始化元芒图像加速库");
	int ret = 0;
	if (drive_ai == 0) {
zzx's avatar
zzx committed
794
		ret = RETRI_Init(NULL, RETRI_DEVICE::RETRI_CPU, &handle);
795 796 797
	}
	else
	{
zzx's avatar
zzx committed
798
		ret = RETRI_Init(NULL, RETRI_DEVICE::RETRI_GPU, &handle);
799 800
	}
	if (ret != 0) {
801
		logger->info("初始化元芒图像加速库失败:{0:x}",ret);
802 803 804 805 806 807 808
		return -1;
	}
	else {
		logger->info("初始化元芒图像加速库成功");
		return 0;
	}
}
809

810 811 812
/**
 * 初始化faiss索引
 */
813
int WMAI_API Init(char* path) {
814

815 816 817 818 819 820
	if (init_finish == true)
	{
		logger->info("二次初始化");
		return 0;
	}

821 822 823 824 825 826 827 828 829 830 831 832 833
#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;

834

835
	char* gsz_file = new char[MAX_PATH];
836 837 838
	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());
839 840
	gszFile = gsz_file;

841 842 843 844 845 846 847 848

	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;


849 850 851 852
	char* tenant_path = new char[MAX_PATH];
	strcpy(tenant_path, (new_dir + "tenant.json").c_str());
	json_tenant_path = tenant_path;

853

854 855 856 857
	char* posId_path = new char[MAX_PATH];
	strcpy(posId_path, (new_dir + "posId.json").c_str());
	posId_json_path = posId_path;

858

859 860 861 862
	char* coordinate = new char[MAX_PATH];
	strcpy(coordinate, (new_dir + "coordinate.json").c_str());
	json_path = coordinate;

863

864
	char* logPath = new char[MAX_PATH];
865
	strcpy(logPath, (new_dir + "logs/daily.txt").c_str());
866 867
	log_path = logPath;

868

869 870 871 872 873 874 875
	char* wmphotoPath = new char[MAX_PATH];
	strcpy(wmphotoPath, (new_dir + "WMphoto").c_str());
	wmphoto_path = wmphotoPath;

#else
	// do nothing
#endif // 0
876

877 878 879 880
	if (logger == nullptr)
	{
		logger = spdlog::daily_logger_mt("daily_logger", log_path, 2, 7);
		logger->flush_on(spdlog::level::info);
881
		delete_daily();
882
	}
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900

	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);
	}
901 902 903 904 905 906 907
	
	char* json_ten = new char[MAX_PATH];
	string ascll_ten_file = string(path) + "\\" + "tenant.json";
	string utf_8_ten_file = ASCII2UTF_8(ascll_ten_file);
	std::strcpy(json_ten, utf_8_ten_file.c_str());
	json_tenant_path = json_ten;
	
908 909
	FILE* fp2 = fopen(json_tenant_path, "rb"); // 非 Windows 平台使用 "r"
	if (fp2) {
910 911 912 913 914 915
		char readBuffer2[65536];                                    
		FileReadStream is2(fp2, readBuffer2, sizeof(readBuffer2)); 
		Document d2; 
		d2.ParseStream(is2); 
		tenantStr = d2["demo"].GetString(); 
		fclose(fp2); 
916 917 918
	}
	FILE* fp3 = fopen(posId_json_path, "rb"); // 非 Windows 平台使用 "r"
	if (fp3) {
919 920 921 922
		char readBuffer3[65536]; 
		FileReadStream is3(fp3, readBuffer3, sizeof(readBuffer3)); 
		Document d3; 
		d3.ParseStream(is3); 
923 924 925
		posId = d3["posId"].GetString();
		fclose(fp3);
	}
926 927 928 929 930 931 932 933 934 935
	GetMacByGetAdaptersAddresses(macAddr); 
	del_rod(macAddr); 
	mINI::INIFile file(dev_ini_path); 
	mINI::INIStructure ini; 
	file.read(ini); 
	dev = ini["default"]["dev"]; 
	mode = atoi(ini["default"]["mode"].c_str()); 
	drive_ai = atoi(ini["default"]["drive_ai"].c_str()); 
	openSync = atoi(ini["default"]["openSync"].c_str()); 
	filterScore = atof(ini["default"]["filterScore"].c_str()); 
936 937

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

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

944
	//添加索引
945
	float idx_start = clock(); 
946 947 948 949 950 951

	char* gsz_file = new char[MAX_PATH];
	string ascll_gsz_file = string(path)+"\\" + "featurexYz.db";
	string utf_8_gsz_file = ASCII2UTF_8(ascll_gsz_file);
	std::strcpy(gsz_file, utf_8_gsz_file.c_str());
	gszFile = gsz_file;
952
	logger->info("gszFile  is {}", gszFile);
953 954


955 956 957
	CppSQLite3DB db; 
	db.open(gszFile); 
	db.setBusyTimeout(5000); 
958 959 960 961 962 963 964 965 966 967 968

	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;");
		}
	}


969
	idx =  new libhnsw::Index(FEATURE_COUNT, DATABASE_SIZE, libhnsw::BRUTE_FORCE_KNN_CF,libhnsw::INNER_PRODUCT);
970 971 972 973 974 975 976 977 978 979
	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);
	}
980
	
981 982
	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);");
983
	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);");
984
	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);");
985 986 987 988 989 990 991


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

992 993 994
	//检测表单,此表单为计数

	db.execDML("CREATE TABLE IF NOT EXISTS video_count (id integer PRIMARY KEY AUTOINCREMENT, count_in integer NOT NULL)");
995
	//检测record_count表达数据
996 997 998 999 1000
	
	CppSQLite3Buffer selectvideocount;
	selectvideocount.format("select count(*) from video_count"); 
	CppSQLite3Query q = db.execQuery(selectvideocount); 
	int pre1;
1001 1002
	while (!q.eof())
	{
1003
		pre1 = q.getIntField(0); 
1004 1005 1006
		break;
	}
	q.finalize();
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039

	if (pre1 == 0)
	{
		rest_count = 0; 
		logger->info("rest_count is{}", rest_count);
	}
	else
	{
		CppSQLite3Buffer  selectvideo; 
		selectvideo.format("select count_in from video_count where id=1;"); 
		CppSQLite3Query q2 = db.execQuery(selectvideo); 
		while (!q2.eof())
		{
			rest_count = q2.getIntField(0);
			logger->info("rest_count is{}",rest_count);
			break;
		}
		q2.finalize(); 
	}

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

1048 1049
	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);");
1050
		db.execDML("CREATE INDEX session_id_index ON product_record(session_id);"); 
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
	}
	// 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;
1065
		updateFeatureCodeTime.format("update feature_code set update_time = datetime('now','localtime');");
1066 1067 1068 1069 1070
		db.execDML(updateFeatureCodeTime);
	}
	queryColumn.finalize();
	queryColumn2.finalize();
	db.close();
1071 1072

	string dir_path = tool_get_dll_path();
1073
	wmphoto_path = dir_path + "WMPhoto";
1074
	DeleteDirectory(wmphoto_path.c_str());
1075 1076

	init_finish = true;
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
	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;
1163 1164
	string pprikey = new_dir + "pprikey.pem";
	string pwmkey = new_dir + "pwmkey.wm";
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
#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());
1179
	logger->info("decryptStr:{}", decryptStr);
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
	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;
}

1224
//static int k;
1225
int detect_squeezenet(const cv::Mat& bgr, std::vector<float>& cls_scores, float* rhs)
1226 1227 1228 1229 1230 1231 1232
{
	// step1:初始化handle
	logger->info("进入元芒图像加速库");
	if (handle == nullptr) {
		logger->info("初始化元芒图像加速库");
		int hr = 0;
		if (drive_ai == 0) {
zzx's avatar
zzx committed
1233
			hr = RETRI_Init(NULL, RETRI_DEVICE::RETRI_CPU, &handle);
1234 1235 1236
		}
		else
		{
zzx's avatar
zzx committed
1237
			hr = RETRI_Init(NULL, RETRI_DEVICE::RETRI_GPU, &handle);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
		}
		if (hr != 0)
		{
			logger->info("元芒图形加速库初始化失败!error code:{0:x}\n", hr);
			return -1;
		}
		else
		{
			logger->info("元芒图形加速库初始化成功");
		}
	}
	// step2:推理
zzx's avatar
zzx committed
1250
	RETRI_INPUT in_img;
1251
	in_img.img = bgr.clone();
zzx's avatar
zzx committed
1252
	RETRI_OUTPUT clsretri_output;
1253
	cv::imwrite("input.jpg", in_img.img);
1254
	//string inimg = tool_get_dll_path()+"in-image";
1255
	
1256 1257 1258 1259 1260 1261
	//_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++;
1262
	
1263
	int s_time = clock();
zzx's avatar
zzx committed
1264
	int hr = RETRI_Process(in_img, &clsretri_output, handle);
1265 1266 1267
	int e_time = clock();
	if (hr != 0)
	{
1268
		logger->info("元芒图形加速库推理失败!error code:{0:x}\n", hr);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
		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;
}

1322

1323 1324
int compare_feature_faiss(float* rhs, string* code, int& biggerNinety) {
	try {
1325 1326
		CppSQLite3DB db; 
		db.open(gszFile);  
1327
		if (!db.tableExists("feature_code")) {
1328
			return 0;  
1329 1330
		}
		//  ============ 搜索 ===================
1331
		reassion.clear();  
1332
		double startTime1 = clock();//1计时开始   
1333 1334

		//logger->info("detect feature:{}", rhs);
1335
		///
1336 1337 1338 1339 1340 1341 1342
		//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);*/
		
1343
		std::vector<std::pair<float, int>>res = idx->Search(rhs,6);  
1344 1345
		for (unsigned int j = 0; j < res.size(); j++)
		{
1346
			std::pair<float, int> r = res[j];   
1347
			//logger->info("res[{}]:id {},prob {}\n", j, r.second, 1-r.first);
1348
			int number = r.second;   
1349 1350

			// 商品向量
1351 1352 1353 1354 1355 1356 1357 1358 1359
			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;  
1360 1361 1362 1363 1364 1365
			int id;
			while (!q.eof())
			{
				sql_code = q.getStringField(0);
				const char* sql_feature = q.fieldValue(1);
				id = q.getIntField(2);
1366
				char* c = const_cast<char*>(sql_feature);   
1367 1368
				split(c, features);
				q.nextRow();
1369
				//logger->info("idx;{} feature:{}", j, sql_feature);
1370
			}
1371
			q.finalize();   
1372

1373
			float sim = calculSimilar(rhs, features, FEATURE_COUNT);   
1374
			
1375
			logger->info("{} is {}", sql_code.c_str(), sim);   
1376 1377
			if (sim > filterScore)
			{
1378
				code[j + 3] = sql_code;   
zzx's avatar
zzx committed
1379
				reassion.emplace(sql_code, id);
1380 1381
				// 如果大于过滤值 说明该向量最近被使用 修改最后更新时间
				CppSQLite3Buffer updateFeatureCode;
1382
				updateFeatureCode.format("update feature_code set update_time = datetime('now','localtime') where id = %d", id);
1383 1384
				db.execDML(updateFeatureCode);
			}
1385 1386
			if (j == 0 && sim > 0.9) {
				logger->info("第一个向量大于0.9的置信度 置换第一个商品代码");
1387 1388
				biggerNinety = 1;
			}
1389 1390

	
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
			// 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) {
1573 1574
	cv::Mat returnFrame, frame1, frame2, frame3; 
	double startTime1, endTime1, elasped;  
1575
	startTime1 = clock();//1计时开始
1576 1577
	char pic_Name[128] = {};     //照片名称      
	char raw_pic_Name[128] = {};     //照片名称  
1578 1579
	if (!cap.isOpened())
	{
1580
		logger->info("The camera open failed!");  
1581 1582 1583 1584 1585 1586 1587
		return returnFrame;
	}
	if (frame_one.empty() || frame_thr.empty() || frame_two.empty()) {
		logger->info("camera not init,please wait");
		return returnFrame;
	}
	time_t nowTime;
1588 1589 1590 1591 1592
	tm* now;                                        
	WaitForSingleObject(PhotoMutex, INFINITE);       
	frame1= frame_one.clone();               
	frame2= frame_two.clone();         
	frame3 =frame_thr.clone();            
1593 1594
	ReleaseMutex(PhotoMutex);
	endTime1 = clock();
1595 1596
	elasped = endTime1 - startTime1;            
	logger->info("camera load elapsed {}ms\n", elasped);      
1597 1598 1599
	time(&nowTime);				//获取系统当前时间戳
	now = localtime(&nowTime);	//将时间戳转化为时间结构体

1600
	_mkdir(wmphoto_path.c_str());                     
1601 1602 1603 1604 1605 1606 1607
	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];
1608
		std::strcpy(photoPath, (wmphoto_path+"\\raw%d%d%d%d%d%d.jpg").c_str());
1609
#endif // 0
1610
		sprintf(raw_pic_Name, photoPath, now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, 
1611
			now->tm_hour + 8, now->tm_min, now->tm_sec);
1612
		cv::imwrite(raw_pic_Name, frame1);                                                
1613
		std::strcpy(rawPath, raw_pic_Name);
1614 1615 1616 1617 1618 1619 1620 1621
	}
	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];
1622
		std::strcpy(photoPath, (wmphoto_path+"\\%d%d%d%d%d%d.jpg").c_str());
1623 1624 1625 1626
#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));
1627
		cv::Mat catImage2 = frame2(cv::Rect(x, y, width, height));  
1628 1629 1630 1631 1632
		cv::Mat catImage3 = frame3(cv::Rect(x, y, width, height));

		float f1 = TenengradBlurDetect(catImage1);
		float f2 = TenengradBlurDetect(catImage2);
		float f3 = TenengradBlurDetect(catImage3);
1633
		float maxF = max(max(f1, f2), f3);       
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
		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();
			}
		}
1667
		std::strcpy(cropPath, pic_Name);  
1668 1669
	}
	endTime1 = clock();//1计时开始
1670 1671
	elasped = endTime1 - startTime1;   
	logger->info("camera all elapsed {}ms\n", elasped);  
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
	return returnFrame;
}

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

// 主动识别接口
1683 1684
int MatDetect(char* productcodes, char* sessionId) {
	double all_start_time = clock();//1计时开始  
1685 1686 1687
	if (!authed) {
		authed = authorize();
		if (!authed) {
1688 1689
			logger->info("验证失败");
			return -2001;
1690 1691
		};
	}
1692 1693 1694 1695 1696
	if (!x && !y && !width && !height) {
		logger->info("没有设置摄像头剪辑坐标");
		return -2009;
	}
	int thread = 4;
1697
	int use_gpu = 0;
1698

1699 1700 1701
#if NCNN_VULKAN
	// ncnn::create_gpu_instance(); 
#endif // NCNN_VULKAN
1702 1703 1704
	char rawPath[128];
	char cropPath[128];
	cv::Mat m = getScaleBitmap(rawPath, cropPath, false);
1705 1706 1707
	if (m.empty())
	{
		logger->info("cv::imread failed\n");
1708
		return -2002;
1709 1710
	}
	int biggerNinety = 0;
1711 1712
	// 拷贝图片地址
	//strncpy(image, cropPath, 128);
1713 1714 1715 1716
	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
	double elasped = ncnn::get_current_time() - start_time;
	logger->info("category elapsed {}ms\n", elasped);
1720
	compare_feature_faiss(rhs, productcode, ref(biggerNinety));
1721

1722 1723
	double save_record_start_time = clock();//1计时开始  
	string newSessionId = get_session_id();
1724
	std::strcpy(sessionId, newSessionId.c_str());
1725 1726 1727 1728
	// 组装返回的商品代码
	char codes[10 * 10] = { };
	for (int i = 0; i < 10; ++i)
	{
zzx's avatar
zzx committed
1729
		if (productcode[i].empty() || productcode[i] == "0") {
1730 1731
			continue;
		}
zzx's avatar
zzx committed
1732
		sprintf(codes + strlen(codes), "%s,", productcode[i].c_str());
1733
	}
zzx's avatar
zzx committed
1734
	logger->info("productcodes:{}", codes);
1735
	std::strcpy(productcodes, codes);
1736 1737 1738 1739 1740 1741

	string  product_codes = productcodes;

	char* realIds = const_cast<char*>(product_codes.c_str());
	splitString(realIds, realProductCodes);
	// 将图片向量进行逗号组装 
1742 1743 1744 1745 1746 1747 1748 1749 1750
	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
1751 1752 1753
		if (productcode[i].empty()) {
			continue;
		}
1754 1755
		sprintf(productIds + strlen(productIds), "%s,", productcode[i].c_str());
	}
zzx's avatar
zzx committed
1756

1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
	////判断是否识别到了空盘
	//float sim = calculSimilar(rhs, feature_empty, FEATURE_COUNT);
	//char rhs_data[FEATURE_COUNT * 10] = { };
	//for (int i = 0; i < FEATURE_COUNT; ++i)
	//{
	//	sprintf(rhs_data + strlen(rhs_data), "%f,", feature_empty[i]);
	//}
	//logger->info("feature_empty feature:{}", rhs_data);
	//logger->info("相似度为 sim is{}", sim);
	//if (sim >= 0.95)
	//{
	//	result.state = 2;
	//	memset(productIds, '\0', sizeof(productIds));
	//}
	//logger->info("result.state is {}", result.state);
zzx's avatar
zzx committed
1772

1773 1774 1775
	save_record(newSessionId, 0, 0, elasped, string(cropPath), string(featureValue), string(productIds), string(codes));

	double save_record_end_time = clock();//1计时开始  
zzx's avatar
zzx committed
1776
	logger->info("save record elapsed {}ms\n", save_record_end_time - save_record_start_time);
1777 1778
	double all_end_time = clock();//1计时开始  
	logger->info("all time elapsed {}ms\n", all_start_time - all_end_time);
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
	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();
1809
	int ret = detect_squeezenet(m, cls_scores, rhs);
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
	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();
1821
	std::strcpy(sessionId, newSessionId.c_str());
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
	// 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
1862
	logger->info("productcodes:{}", codes);
1863
	std::strcpy(productcodes, codes);
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
	// 将图片向量进行逗号组装
	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计时开始
1878
	std::thread t1(save_record, newSessionId, 0, 0, elasped, string(imagePath), string(featureValue), string(productIds), string(codes));
1879 1880 1881 1882 1883 1884 1885 1886 1887
	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) {
1888
	double all_start_time = clock();//1计时开始  
1889
	if (!authed) {
1890
		authed = authorize();  
1891
		if (!authed) {
1892
			logger->info("验证失败");  
1893 1894 1895 1896
			return -2001;
		};
	}
	if (!x && !y && !width && !height) {
1897
		logger->info("没有设置摄像头剪辑坐标");  
1898 1899
		return -2009;
	}
1900 1901
	int thread = 4;  
	int use_gpu = 0;  
1902 1903 1904 1905

#if NCNN_VULKAN
	// ncnn::create_gpu_instance(); 
#endif // NCNN_VULKAN
1906 1907 1908
	char rawPath[128];  
	char cropPath[128];  
	cv::Mat m = getScaleBitmap(rawPath, cropPath, false);  
1909 1910
	if (m.empty())
	{
1911
		logger->info("cv::imread failed\n"); 
1912 1913
		return -2002;
	}
1914
	int biggerNinety = 0;  
1915
	// 拷贝图片地址
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
	strncpy(image, cropPath, 128); 
	string productcode[10];      
	std::vector<float> cls_scores;   
	float rhs[FEATURE_COUNT];  
	double start_time = ncnn::get_current_time();   
	int ret = detect_squeezenet(m, cls_scores, rhs);   
	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();   
	std::strcpy(sessionId, newSessionId.c_str());   
1929
	// 组装返回的商品代码
1930
	char codes[10 * 10] = { };   
1931 1932
	for (int i = 0; i < 10; ++i)
	{
1933
		if (productcode[i].empty() || productcode[i] == "0") { 
1934 1935
			continue;
		}
1936
		sprintf(codes + strlen(codes), "%s,", productcode[i].c_str()); 
1937
	}
1938
	logger->info("productcodes:{}", codes);   
1939
	std::strcpy(productcodes, codes);
1940

1941
	string  product_codes = productcodes;   
1942
	
1943 1944 1945 1946 1947 1948
	char* realIds = const_cast<char*>(product_codes.c_str());  
	splitString(realIds, realProductCodes);  
	// 将图片向量进行逗号组装 
	char featureValue[FEATURE_COUNT * 10] = { };  
	for (int i = 0; i < FEATURE_COUNT; ++i) 
	{ 
1949 1950 1951
		sprintf(featureValue + strlen(featureValue), "%f,", rhs[i]);
	}
	// 组装productIds
1952
	char productIds[10 * 10] = { };      
1953 1954 1955 1956 1957
	for (int i = 0; i < 10; ++i)
	{
		if (productcode[i].empty()) {
			continue;
		}
1958
		sprintf(productIds + strlen(productIds), "%s,", productcode[i].c_str());   
1959 1960
	}
	
1961

1962
	save_record(newSessionId, 0, 0, elasped, string(cropPath), string(featureValue), string(productIds), string(codes));   
1963

1964 1965 1966
	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计时开始  
1967 1968 1969 1970 1971
	logger->info("all time elapsed {}ms\n", all_start_time - all_end_time);
	return 0;
}

// 主动识别接口
1972 1973
int WMAI_API AutoDetect(char* productcodes, char* sessionId) 
{
1974
	
1975 1976
	char image[128]; 
	int ret = doSnacksAutoDetect(productcodes, sessionId, image); 
1977
	return ret;
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 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 2014 2015 2016 2017 2018 2019 2020 2021 2022

}

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);
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047

	//检测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();

2048 2049
	int lastId = idx->get_cur_element_count();
	logger->info("lastId is {}", lastId);
2050
	if (size_f >= 30000) {
2051 2052
		// 找到时间最小的向量 进行替换
		int id = 0;
2053
		int count = 0;
2054
		// 找到第一个code的商品 替换他 
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
		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;
2072
			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);
2073 2074 2075 2076 2077 2078 2079 2080 2081
			db.execDML(updateFeatureCode);
			logger->info("覆盖成功");

			//删除用掉的id的记录
			CppSQLite3Buffer delCount;
			selectCount.format("delete from record_count where id = %d;", id);
			db.execDML(selectCount);
		}
		else
2082
		{
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
			//没有积存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;
2105
			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);
2106
			db.execDML(updateFeatureCode);
2107
		}
2108 2109
		logger->info("count :{}", count);

2110 2111 2112
		// 删除label
		// idx->Removesample(id - 1);
		// 保存索引
2113 2114 2115 2116 2117 2118
		//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);
2119 2120 2121
	}
	else {
		// 记录feature 和 商品代码之间的关系 到sqlite 和 faiss索引
2122 2123 2124
		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);	
2125

2126
	
2127
		int count = db.execScalar("select last_insert_rowid() from feature_code;");	
2128 2129 2130
		logger->info("db add id is {}", count);
		//将数据加入索引
		// 保存索引
2131
		//hnswExecutor->enqueue(saveHnswIndex, string(featureValue), count);
2132
		saveHnswIndex(string(featureValue), count);	
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
	}
}

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;
2156
		updateFeatureCode.format("update feature_code set feature = %Q,code = %Q,update_time = datetime('now','localtime') where id = %d", featureValue.c_str(), code, id);
2157 2158 2159 2160 2161 2162 2163
		db.execDML(updateFeatureCode);
		// 保存索引
		saveHnswIndex(string(featureValue), id);
	}
	else {
		// 记录feature 和 商品代码之间的关系 到sqlite 和 faiss索引
		CppSQLite3Buffer insertFeatureCode;
2164
		insertFeatureCode.format("insert into feature_code(code, feature,update_time) values (%Q,%Q,datetime('now','localtime'));", code, featureValue.c_str());
2165 2166 2167 2168
		db.execDML(insertFeatureCode);

		float features[FEATURE_COUNT];
		char c[FEATURE_COUNT * 10];
2169
		std::strcpy(c, featureValue.c_str());
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 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
		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
2286 2287 2288 2289 2290

	if (featureValue.empty())
	{
		return -2005;
	};
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
	// 首先查询商品模型表是否有该数据
	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);
	//}
2305
	if (!hit|| !realProductCodes[1].empty()) {
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 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
		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;
2435 2436 2437
	int realTopNo;
	
	if (!hit|| !realProductCodes[1].empty())
zzx's avatar
zzx committed
2438
	{
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
		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;
		};
2459

2460 2461 2462 2463 2464
		// 获得topNo
		string productCodes[10];
		char* cIds = const_cast<char*>(productIds.c_str());
		splitString(cIds, productCodes);
		int topNo = getTopNo(productCodes, code);
2465

2466 2467 2468 2469 2470
		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);
2471

2472 2473
		saveDbIndex(db, code, featureValue);
		sendClientFeatureMessage(code, featureValue);
2474

2475 2476
		db.close();
	}
2477 2478 2479 2480 2481
	if (connectNet) {
		Document d;
		string response;
		char uploadUrl[200];
		sprintf(uploadUrl, upload_file_url, dev.c_str(), tenantStr.c_str());
2482
		logger->info("upload url is {},imagePath is {}", uploadUrl, (tool_get_dll_path()+imagePath).c_str());
2483
		int resultCode = CommonTools::upload_file(uploadUrl, imagePath.c_str(), response); 
2484
		logger->info("code:{},response:{}", resultCode, response);
2485 2486 2487 2488 2489
		if (resultCode != 0) {
			connectNet = false;
			logger->info("设备未联网不再上传");
			return 0;
		}
2490 2491
		
		d.Parse(response.c_str()); 
2492 2493 2494 2495 2496 2497 2498 2499 2500
		if (d["code"].GetInt() == 0) {
			Value& s1 = d["data"]["url"];
			if (s1.IsNull()) {
				logger->info("上传失败");
				return 0;
			}
			string imageUrl = s1.GetString();
			d.Clear();

2501
			Pointer("/recommendTime").Set(d, time); 
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
			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);
2513
			d.Accept(writer); 
2514

2515 2516
			char url[100] = {};
			
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
			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)
{
2529 2530
	string name(productName);
	logger->info("code is {} sessionId is {} hit is {} productName is {}", code, sessionId,hit, UTF_82ASCII(name));
2531
	logger->info("start feed back");
2532
	int result = doSnacksSetFeedBack(code, sessionId, hit, productName);
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
	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);
2549
	logger->info("reponse is {}", UTF_82ASCII(response2));
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
	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
2565

2566 2567
// 注册pos机
int WMAI_API InitPos(char* tenant, char* posCode, char* snNo) {
2568
	logger->info("{},{},{}", tenant, posCode, snNo);
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
	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);
2590
	logger->info("reponse is {}", UTF_82ASCII(response));
2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
	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;
	}
}

2653 2654
// 解绑pos机
int WMAI_API UnbindPos(char* tenant, char* snNo) {
2655 2656 2657 2658 2659
	int checkTenantCode = checkTenant(tenant);
	if (checkTenantCode != 0) {
		return checkTenantCode;
	}

2660 2661
	const char* pwmkey = "pwmkey.wm";
	const char* pprikey = "pprikey.pem";
2662

2663 2664 2665
	remove(pwmkey);
	remove(pprikey);

2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
	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);
2680
	logger->info("reponse is {}", UTF_82ASCII(response));
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
	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";
2695

2696 2697 2698 2699
#endif // 0

		remove(wmkey);
		remove(prikey);
2700

2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
		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;
2723
	while (cap.isOpened())
2724 2725 2726 2727
	{
		cap >> frame_pipe;
		if (frame_pipe.empty())
		{
2728
			logger->info("frame_pipe empty");
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
			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);
2745
		if (cv::waitKey(30)) { 	 //延时30ms		
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 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 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
			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);
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868

	//记录需要删除的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();

	// 清除数据库
2869 2870
	if (db.tableExists("feature_code")) {
		CppSQLite3Buffer deleteSql;
2871
		deleteSql.format("update feature_code set deleted = 1 where code = %Q;", code);
2872
		db.execDML(deleteSql);
2873
}
2874 2875 2876 2877 2878
	if (db.tableExists("product_model")) {
		CppSQLite3Buffer deleteSql;
		deleteSql.format("delete from product_model where product_code = %Q", code);
		db.execDML(deleteSql);
	}
2879

2880 2881 2882 2883 2884 2885 2886
	// 清除map
	// productModelMap.erase(code);

	// 重置索引
	delete idx;
	idx = new libhnsw::Index(FEATURE_COUNT, DATABASE_SIZE, libhnsw::BRUTE_FORCE_KNN_CF);
	if (db.tableExists("feature_code")) {
2887
		CppSQLite3Query q = db.execQuery("select id,feature from feature_code where deleted = 0");
2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
		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;
}

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
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);
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
	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();
2947 2948
	std::strcpy(path, "data-copy");
#endif // APPOINT_LIBRARY
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 3038 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 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
	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();
3133
	int ret = detect_squeezenet(m, cls_scores, rhs);
3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172

	// 将图片向量进行逗号组装
	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;
3173
	//delete hnswExecutor;
3174
	param_in.end_thread = true;
zzx's avatar
zzx committed
3175
	RETRI_Release(&handle);
3176
	init_finish = false;
3177 3178 3179 3180
	return 0;
}

int WMAI_API Close() {
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
	logger->info("开始释放资源");

	CppSQLite3DB db;
	db.open(gszFile);
	int pre;
	CppSQLite3Buffer selectvideocount;                                  
	selectvideocount.format("select count(*) from video_count");        
	CppSQLite3Query q = db.execQuery(selectvideocount);                 

	while (!q.eof())
	{
		pre = q.getIntField(0);                                        
		break;
	}
	q.finalize();                                                      

	if (pre == 0)
	{
		CppSQLite3Buffer insertvideocount;                                
		insertvideocount.format("insert into video_count(count_in) values (%d);", rest_in);  
		db.execDML(insertvideocount);   
	}
	else
	{
		CppSQLite3Buffer updatevideocount;                                           
		updatevideocount.format("update video_count set count_in=%d where id = 1", rest_in); 
		db.execDML(updatevideocount);                                                  
	}
	 db.close();

3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
	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();
	}
3223 3224 3225 3226 3227 3228
	if (idx != nullptr)
	{
		delete idx;
		idx = nullptr;
	}

3229
	param_in.end_thread = true;
zzx's avatar
zzx committed
3230
	RETRI_Release(&handle);
3231
	init_finish = false;
3232 3233
	logger->info("释放资源结束");
	
3234 3235 3236 3237 3238
	return 0;
}

int FoodInitParam(FOOD_PARAM_DATA* param_in)
{
3239
	
3240
	_mkdir("data");
3241
	
3242
	// step1:先配置下数据源
zzx's avatar
zzx committed
3243
	param_in->back_mat_path = "data/back.jpg";
3244
	param_in->debug_mode = false; 
3245 3246

	// step2:配置roi
3247
	param_in->has_roi = true; 
3248 3249 3250
	cv::Rect roi;
	roi.x = ai_x;
	roi.y = ai_y;
3251
	roi.width = ai_width; 
3252
	roi.height = ai_height;
3253
	param_in->roi = roi; 
3254

zzx's avatar
zzx committed
3255

3256 3257 3258


	//step4.裁剪下当前帧照片,保存当前图片
zzx's avatar
zzx committed
3259
	param_in->back =cv::imread(param_in->back_mat_path);
3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277

	////获取空盘图向量
	//RETRI_INPUT empty_img;
	//empty_img.img = param_in->back.clone();
	//RETRI_OUTPUT clsretri_output;
	//int hr = RETRI_Process(empty_img, &clsretri_output, handle);
	//if (hr != 0)
	//{
	//	logger->info("元芒图形加速库推理失败!error code:{0:x}\n", hr);
	//	return -2008;
	//}
	//for (int i = 0; i < FEATURE_COUNT; i++)
	//{
	//	feature_empty[i] = clsretri_output.feat[i];
	//}



zzx's avatar
zzx committed
3278
	if (param_in->back.empty()) {
3279
		param_in->back = frame_pipe.clone(); 
zzx's avatar
zzx committed
3280
		if (param_in->back.empty()) {
3281 3282 3283
			logger->info("图片是空的,\n");
			return -2002;
		}
zzx's avatar
zzx committed
3284

3285 3286
		if (roi.area() != 0)
		{
zzx's avatar
zzx committed
3287
			param_in->back = param_in->back(roi);
3288
		}
3289
		
3290
		char pathName[128] = {};
zzx's avatar
zzx committed
3291
		sprintf(pathName, "%s", param_in->back_mat_path.c_str());
3292
		logger->info("要保存的文件路径[{}]\n", pathName);
zzx's avatar
zzx committed
3293
		cv::imwrite(pathName, param_in->back);
3294 3295 3296 3297 3298 3299 3300 3301 3302
	}

	// 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;

3303
	libvideopipe::INIT_INFO video_pipe;
3304 3305
	//video_pipe.gpu_enable = drive_ai;
	video_pipe.gpu_enable =true;
zzx's avatar
zzx committed
3306 3307 3308
	video_pipe.lat3d_enable = true;
	param_in->mvp = new libvideopipe::MotionVideoPipe;
	param_in->mvp->Init(video_pipe);
3309

3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
	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))
	{
3348
		//float start = clock();
3349 3350
		Sleep(average_cost());
		// step1:获取当前帧
3351

3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362
		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
3363
		VIDEO_FRAME_INFO frame;
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
		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);
		}
3383
		//float end = clock();
3384 3385 3386 3387 3388 3389 3390 3391 3392
		//logger->info("get image cost:{}", end - start); 
	}
	return 1;
}



void trace_detect_process()
{
3393
	result.state = 1;
3394 3395

	if (video_detect)
3396
	{
3397 3398
		char rawPath[128];                 
		char cropPath[128];                   
3399
		Sleep(150);
3400 3401 3402 3403 3404 3405 3406 3407

		//cv::Mat m = getScaleBitmap(rawPath, cropPath, false);     
		//if (m.empty())//获取图片失败编写日志
		//{
		//	logger->info("cv::imread failed\n");
		//	return;
		//}
		int ret = MatDetect(result.productCodes, result.sessionId);
3408 3409
		if (ret != 0)
		{
3410
			logger->info("Detect error:{}", ret);          
3411 3412
			return;
		}
3413
	}
3414
	else
3415
	{
3416 3417
		std::strcpy(result.productCodes, "");                  
		std::strcpy(result.sessionId, "");                      
3418 3419 3420
	}
	if (param_in.result_queue.size()< param_in.queue_max) 
	{
3421 3422
		DETECT_RESULT tem = result;   
		param_in.result_queue.push(tem);  
3423 3424 3425
	}
}

3426 3427
void trace_judge_process()
{
3428
	Sleep(100);        
3429
	char path[128] = {};
3430 3431 3432
	char row_path[128] = {};     
	GetScaleBitmap(row_path, path); 
	param_in.detect_image_path = string(path); 
3433 3434
}

3435 3436
void save_in_image()
{
3437 3438 3439 3440 3441 3442 3443
	
	if (rest_in > VIDEOCOINTIN)
	{	                                              
		return;
	}
	
	logger->info("rest_in is{}",rest_in);          
3444

3445 3446
	std::string dir = "video_image_in";              
	std::string time = std::to_string(food_get_current_time_millis());          
3447

3448 3449
	_mkdir(dir.c_str());                                  
	_mkdir((dir + "/" + time).c_str());                 
3450 3451

	int i = 1;
3452 3453 3454 3455
	const char* path = "%s/%s/%s-%d.jpg";          
	char name2[128] = {};                  
	char name3[128] = {};                  
	char name4[128] = {};             
3456
	vector<string>res;
3457
	string pre1;                      
3458 3459
	string pre2;
	string pre3;
3460
	sprintf(name2, path, dir.c_str(), time.c_str(), time.c_str(), i++); 
3461
	pre1 = pre1 + time.c_str() + "wmAce"+"-" + "1" + ".jpg";
3462
	res.push_back(pre1);
3463 3464
	cv::imwrite(name2, param_in.back);
	sprintf(name3, path, dir.c_str(), time.c_str(), time.c_str(), i++); 
3465
	pre2 = pre2 + time.c_str() +"wmAce"+ "-" + "2" + ".jpg";
3466
	res.push_back(pre2);
3467 3468
	cv::imwrite(name3, param_in.frame_out[3].img);
	sprintf(name4, path, dir.c_str(), time.c_str(), time.c_str(), i++); 
3469
	pre3 = pre3 + time.c_str() + "wmAce" + "-" + "3" + ".jpg";
3470
	res.push_back(pre3);
3471
	cv::imwrite(name4, param_in.frame_out[4].img);
3472 3473 3474

	char in[10] = "IN";
	res.push_back(in);
3475 3476 3477 3478 3479 3480 3481 3482 3483
	
	
	
	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 {}", uploadUrl);
3484
		
3485
	int curlCode = CommonTools::upload_file1(uploadUrl,name2,name3,name4,res,response);
3486
		
3487 3488 3489 3490 3491
	string rrr= UTF_82ASCII(response);
	logger->info("response is {}",rrr);
	if (curlCode != 0) {
		logger->info("上传图片失败,退出");
		return;
3492
	}
3493 3494 3495
	rest_in++;
	

3496 3497 3498 3499
}

void save_out_image()
{
3500
	
3501

3502 3503 3504 3505
	if (rest_out > VIDEOCOINTIN)
	{
		return;
	}
3506 3507 3508 3509 3510 3511 3512 3513
	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";
3514 3515 3516 3517 3518 3519
	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++);
3520
	buf1 = buf1 + time.c_str() + "wmAce" + "-" + "1" + ".jpg";
3521 3522 3523
	res1.push_back(buf1);
	cv::imwrite(name5, param_in.back);
	sprintf(name6, path, dir.c_str(), time.c_str(), time.c_str(), i++);
3524
	buf2 = buf2 + time.c_str() + "wmAce" + "-" + "2"+".jpg";
3525 3526 3527
	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++);
3528
	buf3 = buf3 + time.c_str() + "wmAce" + "-" + "3" + ".jpg";
3529 3530 3531 3532 3533
	res1.push_back(buf3);
	cv::imwrite(name7, param_in.frame_out[4].img);
	string out = "OUT";
	res1.push_back(out);

3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
	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 {}", uploadUrl);

	int curlCode = CommonTools::upload_file1(uploadUrl, name5, name6, name7,res1, response);
	string rrr = UTF_82ASCII(response);
	logger->info("response is {}", rrr);
		
	if (curlCode != 0) {
		logger->info("上传图片失败,退出");
		return;
3548
	}
3549 3550

	rest_out++;
3551

3552 3553
}

zzx's avatar
zzx committed
3554
void video_trace_result_callback(const char* data, int len, void* user)
3555 3556
{
	// AI识别
zzx's avatar
zzx committed
3557 3558 3559
	libvideopipe::MOTION_VIDEOPIPE_OUTPUT* output = (libvideopipe::MOTION_VIDEOPIPE_OUTPUT*)data;

	if (output->status == libvideopipe::MOTION_STATUS_TYPES::MOTION_IN)
3560
	{
3561
		logger->info("检测到物品进入");  
3562 3563
		if (mode == FRESH_DETECT)
		{
3564
			thread t(trace_detect_process);       
3565 3566 3567 3568 3569 3570
			t.detach();                                
			if (rest_count < VIDEOCOUNT)
			{
				thread t_(save_in_image);                     
				t_.detach();                                    
			}
3571 3572 3573
		}
		else if (mode == PREVENT_LOSS)
		{
3574 3575
			thread t(trace_judge_process);                
			t.detach();                                  
3576 3577 3578
			/*thread t_(save_in_image);
			t_.detach();
			logger->info("没有进行存图!");*/
3579 3580 3581
			if (param_in.result_queue.size() < param_in.queue_max)
			{
				DETECT_RESULT tem = result;
3582
				tem.state = 1;
3583 3584 3585
				param_in.result_queue.push(tem);
			}
		}
3586
	}
zzx's avatar
zzx committed
3587
	if (output->status == libvideopipe::MOTION_STATUS_TYPES::MOTION_OUT)
3588 3589
	{
		logger->info("检测到物品离开");
3590 3591 3592 3593 3594
		if (rest_count < VIDEOCOUNT)
		{
			thread t_(save_out_image);
			t_.detach();
		}
3595 3596
		if (param_in.result_queue.size() < param_in.queue_max)
		{
3597
			DETECT_RESULT tem = result;                   
3598
			tem.state = 0;                             
3599
			param_in.result_queue.push(tem);              
3600 3601 3602 3603 3604 3605 3606
		}
	}
}

DWORD WINAPI FoodDetectTrace(LPVOID params)
{

3607
	auto start = clock();
3608 3609 3610 3611 3612 3613 3614 3615
	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
3616 3617 3618
	param_in->mvp->SetROI(param_in->roi);
	param_in->mvp->SetMarkMat(param_in->back);
	param_in->mvp->SetResultCallback(video_trace_result_callback, param_in);
3619 3620

	g_video_init = true;
3621
	logger->info("videopipe init end");
3622 3623 3624

	while (!param_in->end_thread)
	{
3625
		
3626 3627 3628 3629 3630 3631 3632
		// step1:判断帧数据是否为空
		if (param_in->frame_in.empty())
		{
			Sleep(30);
			in_image = false;
			continue;
		}
3633
		
zzx's avatar
zzx committed
3634
		//处理图像开始
3635 3636
		in_image = true;
		float start = clock();
zzx's avatar
zzx committed
3637

3638
		// step2:获取输入数据
zzx's avatar
zzx committed
3639
		WaitForSingleObject(param_in->hMutex, INFINITE);
zzx's avatar
zzx committed
3640
		VIDEO_FRAME_INFO frame;
3641 3642 3643 3644
		frame = param_in->frame_in.front();
		param_in->frame_in.pop();  // 删除一个原图
		ReleaseMutex(param_in->hMutex);

3645 3646 3647 3648 3649 3650
		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());
		}

3651 3652

		// step3:设置video input
zzx's avatar
zzx committed
3653
		libvideopipe::MOTION_VIDEOPIPE_INPUT video_input;
3654 3655
		video_input.img = frame.img.clone();
		video_input.pts = frame.timestamp;
3656
		video_input.debug_mode = false;
3657 3658 3659 3660 3661 3662 3663

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

3666 3667
		// step5:开始Trace;
		//float _start = clock();
zzx's avatar
zzx committed
3668
		int rt = param_in->mvp->FeedFrame(video_input);
3669 3670
		//float _end = clock();
		//logger->info("FeedFrame costs {} ms \n",_end - _start);
3671 3672 3673 3674
		if (rt != 0)
		{
			logger->info("Trace return error code:{0:x}\n", rt);
		}
zzx's avatar
zzx committed
3675

3676 3677 3678 3679 3680 3681
		cv::waitKey(3);
		float end = clock();
		solve_cost.push_back(end-start);
		//logger->info("dev solve cost:{}", end - start);

	}
3682
	return 0;
3683 3684
}

3685 3686 3687 3688
void videoPipeDetect() 
{

	logger->info("videopipe init start");
3689
	
3690
	FoodInitParam(&param_in);
3691
	
3692 3693 3694 3695 3696 3697
	// 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");
3698 3699 3700
	bool getthread = false;
	

3701 3702 3703 3704 3705 3706 3707
	// 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
3708
	delete param_in.mvp;
3709
	g_video_init = false;
3710 3711 3712 3713 3714
	logger->info("process end");

}

//识别函数主控
3715
int WMAI_API VideopipeDetect() {
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
	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);
3741 3742
	std::strcpy(code, param_in.result_queue.front().productCodes);
	std::strcpy(sessionId, param_in.result_queue.front().sessionId);
3743 3744 3745 3746 3747 3748 3749 3750 3751
	state = param_in.result_queue.front().state;
	param_in.result_queue.pop();
	re_ret = false;
	return 0;
}

void uploadImage() {
	Document d;
	string response;
3752
	char uploadUrl[200];
3753
	sprintf(uploadUrl, upload_file_url, dev.c_str(), tenantStr.c_str());
zzx's avatar
zzx committed
3754 3755
	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);
3756
	//logger->info("response is {},curl code is {}", response.c_str(), curlCode);
3757 3758 3759 3760 3761
	if (curlCode != 0) {
		logger->info("上传图片失败,退出");
		return;
	}
	d.Parse(response.c_str());
3762
	int resultCode = d["code"].GetInt(); 
3763
	if (resultCode == 0) {
3764
		Value& s1 = d["data"]["url"]; 
3765 3766 3767 3768
		if (s1.IsNull()) {
			logger->info("上传失败");
			return;
		}
3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
		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()); 
3784 3785 3786 3787
		logger->info("url:{}",url);

		string response2;
		CommonTools::HttpPost(url, buffer.GetString(), response2, 3);
3788
		//logger->info("response2:{}", response2);
3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
	}
	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);

3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
	
	////更新空盘图的向量
	//RETRI_INPUT empty_img;
	//empty_img.img = imgRoi.clone();
	//RETRI_OUTPUT clsretri_output;
	//int hr = RETRI_Process(empty_img, &clsretri_output, handle);
	//if (hr != 0)
	//{
	//	logger->info("元芒图形加速库推理失败!error code:{0:x}\n", hr);
	//	return -2008;
	//}

	//for (int i = 0; i < FEATURE_COUNT; i++)
	//{
	//	feature_empty[i] = clsretri_output.feat[i];
	//}

3837
	char pathName[128] = {};
zzx's avatar
zzx committed
3838
	sprintf(pathName, "%s", param_in.back_mat_path.c_str());
3839 3840 3841
	cv::imwrite(pathName, imgRoi);

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

3846

3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
	//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);
3870
	logger->info("reponse is {}", UTF_82ASCII(response));
3871 3872 3873
	d.Parse(response.c_str());
	Value& s = d["code"];
	if (s.GetInt() == 0) {
3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887


#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
3888 3889
		string wmKeyUrl = d["data"]["wmKeyUrl"].GetString();
		string privateKeyUrl = d["data"]["privateKeyUrl"].GetString();
3890 3891 3892 3893
		//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());
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
		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
3937
	char *writeBuffer = (char *)calloc(65536,sizeof(char));
3938 3939 3940 3941
	FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
	Writer<FileWriteStream> writer(os);
	d.Accept(writer);
	fclose(fp);
zzx's avatar
zzx committed
3942 3943
	free(writeBuffer);
	return 0;
3944 3945
}

zzx's avatar
zzx committed
3946 3947
int WMAI_API inputPluToDetect(char *code,char *sessionId)
{
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
	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
3966
	}
3967
	else
zzx's avatar
zzx committed
3968
	{
3969
		return -6002;
zzx's avatar
zzx committed
3970
	}
3971

zzx's avatar
zzx committed
3972 3973 3974 3975
}

int WMAI_API getDetectImage(char* path)
{
3976
	logger->info("image_path:{}", param_in.detect_image_path);
3977
	std::strcpy(path,param_in.detect_image_path.c_str());
3978
	logger->info("path:{}", path);
zzx's avatar
zzx committed
3979 3980 3981 3982 3983 3984 3985 3986 3987
	return 0;
}

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

3989 3990 3991 3992 3993 3994
//bool WMAI_API getVideopipeInit()
//{
//	return g_video_init;
//}

bool WMAI_API getInitResults()
3995 3996 3997
{
	return g_video_init;
}
3998
bool WMAI_API returnCameraState()
3999 4000 4001 4002
{
	return cap.isOpened();
}

zzx's avatar
zzx committed
4003 4004

//纠错
4005
int WMAI_API freshChangeError(const char* code)
zzx's avatar
zzx committed
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075
{


	//检测表单是否存在
	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;
4076
			deleted_sql.format("update feature_code set deleted = 1, update_time = datetime('now','localtime') where id = %d", number);
zzx's avatar
zzx committed
4077
			db.execDML(deleted_sql);
4078 4079 4080 4081
			//将删除的数据加入record_count表中
			CppSQLite3Buffer insertrecord;
			insertrecord.format("insert into record_count(count) values (%d)", number);
			db.execDML(insertrecord);
zzx's avatar
zzx committed
4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
			idx->Removesample(f.second);
			q.finalize();
		}
	}

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



//自动配图
4095
int WMAI_API SelectByName(char* name , char* code, char* image)
zzx's avatar
zzx committed
4096 4097
{

4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
	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
4108 4109 4110 4111 4112 4113 4114 4115 4116
	Document d;
	d.SetObject();
	Document::AllocatorType& a = d.GetAllocator();


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


4117
	Value v1(name, a);
zzx's avatar
zzx committed
4118 4119 4120 4121
	Value v2(code, a);

	o1.AddMember("productName", v1, a);
	o1.AddMember("productNumber", v2, a);
4122
	array.PushBack(o1, a);
zzx's avatar
zzx committed
4123 4124 4125

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

4126 4127 4128 4129 4130
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d.Accept(writer);
	string buffer1 = buffer.GetString();
	string buffer2 = UTF_82ASCII(buffer1);
zzx's avatar
zzx committed
4131 4132

	char uploadUrl[200];
4133
	string tenant3;
zzx's avatar
zzx committed
4134

4135
	if (tenantStr.size() != 0)
zzx's avatar
zzx committed
4136
	{
4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148
		tenant3 = tenant3 + tenantStr;
	}
	else if (tenantStr.size() == 0)
	{
		tenant3 = tenant3 + '0';
	}

	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));
zzx's avatar
zzx committed
4149

4150
	d.Parse(response.c_str());
zzx's avatar
zzx committed
4151 4152
	Value& s = d["code"];
	if (s.GetInt() == 0) {
4153
#if 0
zzx's avatar
zzx committed
4154
		string out;
4155
		for (int i = 0; i < response.size() - 1; i++)
zzx's avatar
zzx committed
4156
		{
4157
			if (response[i] == 'h' && response[i + 1] == 't')
zzx's avatar
zzx committed
4158
			{
4159
				for (int j = i; j < response.size(); j++)
zzx's avatar
zzx committed
4160
				{
4161
					if (response[j] == '"')
zzx's avatar
zzx committed
4162 4163 4164
					{
						break;
					}
4165
					out += response[j];
zzx's avatar
zzx committed
4166 4167 4168 4169 4170 4171 4172 4173 4174
				}
			}
		}

		if (out.size() <= 0)
		{
			logger->info("该名称没有找到图片");
			return -1;
		}
4175 4176 4177 4178 4179 4180 4181

		//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
4182
		{
4183
			logger->info("该名称没有找到图片");
zzx's avatar
zzx committed
4184 4185 4186
			return -1;
		}

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

4189
		strcpy(image, iup.c_str());
zzx's avatar
zzx committed
4190

4191 4192 4193 4194 4195 4196
#endif
	}
	else
	{
		logger->info("匹配图片失败");
		return -1;
zzx's avatar
zzx committed
4197 4198 4199 4200
	}
	return 0;
}

4201

4202
int WMAI_API setVideoDetect(int ch)
4203 4204 4205 4206 4207
{
	video_detect = ch == 0 ? false : true;
	return 0;
}