main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include "../common/comm.h"
  4. #include "../common/iobuffer.h"
  5. #include "api.h"
  6. #include "protocol.pb.h"
  7. #include "message_queue.h"
  8. #include <signal.h>
  9. #include <cstring>
  10. #include <stdlib.h>
  11. /*
  12. extern "C"
  13. {
  14. #include "/usr/local/ffmpeg/include/libavcodec/avcodec.h"
  15. //#include "/usr/local/ffmpeg/include/libavutil/time.h"
  16. //#include "/usr/local/ffmpeg/include/libavutil/opt.h"
  17. //#include "/usr/local/ffmpeg/include/libavutil/imgutils.h"
  18. //#include "/usr/local/x264/include/x264.h"
  19. }
  20. */
  21. //#include <sensors/sensors.h>
  22. //#include <PCANBasic.h>
  23. //20230413 MQTT
  24. //#include "../thirdparty/Mqtt/include/MQTTAsync.h"
  25. //#include "../thirdparty/jsoncpp/include/json/json.h"
  26. //
  27. //MQTTAsync mqttClient;
  28. ////static const char* subTopic = "hello1"; //订阅主题
  29. //
  30. //
  31. //void sendMessage(char* data, int qos ,const char * pubTopic)
  32. //{
  33. // int rc;
  34. // MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
  35. // MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  36. //
  37. // opts.context = mqttClient;
  38. //
  39. // pubmsg.payload = data;
  40. // pubmsg.payloadlen = strlen(data);
  41. // pubmsg.qos = qos;
  42. // printf("mqtt send: %s\n", (char*)pubmsg.payload);
  43. //
  44. // if ((rc = MQTTAsync_sendMessage(mqttClient, pubTopic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
  45. // {
  46. // printf("MQTTAsync_sendMessage() fail, error code:%d\n", rc);
  47. // }
  48. //}
  49. //
  50. //void onConnectCallCBack(void* context, char* cause) //连接成功callback
  51. //{
  52. // //printf("Connection successful.\n");
  53. // //int rc, qos;
  54. // //MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  55. //
  56. // //qos = 0;
  57. // //opts.context = mqttClient;
  58. //
  59. // //if ((rc = MQTTAsync_subscribe(mqttClient, subTopic, qos, &opts)) != MQTTASYNC_SUCCESS) //subTopic
  60. // //{
  61. // // printf("MQTTAsync_subscribe() fail, error code:%d\n", rc);
  62. // //}
  63. //
  64. // printf("Connection successful.\n");
  65. // int rc;
  66. // const int qos[2] = {0,1};
  67. // MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  68. //
  69. // char* const subTopic[2] = { "hello" ,"hello1"}; //订阅主题
  70. //
  71. // opts.context = mqttClient;
  72. //
  73. // if ((rc = MQTTAsync_subscribeMany(mqttClient,2,subTopic, qos, &opts)) != MQTTASYNC_SUCCESS) //subTopic
  74. // {
  75. // printf("MQTTAsync_subscribe() fail, error code:%d\n", rc);
  76. // }
  77. //}
  78. //
  79. //void onConnectFailure(void* context, MQTTAsync_failureData* response) //连接失败callback
  80. //{
  81. // printf("connection fail, error code: %d, error message:%s\n", response ? response->code : 0, response ? response->message : 0);
  82. //}
  83. //
  84. //void Disconnect(void* context, char* cause) //连接断开callback
  85. //{
  86. // printf("disconnect, cause: %s\n", cause);
  87. //}
  88. //
  89. //int RecevieMessage(void* context, char* pubTopic, int topicLen, MQTTAsync_message* message)
  90. //{
  91. // char buf[message->payloadlen + 1];
  92. //
  93. // memcpy(buf, message->payload, message->payloadlen);
  94. // printf("mqtt recv: %s\n", buf);
  95. // MQTTAsync_freeMessage(&message);
  96. // MQTTAsync_free(pubTopic);
  97. //
  98. // return 1;
  99. //}
  100. void daemonize(void) {
  101. signal(SIGTTOU, SIG_IGN);
  102. signal(SIGTTIN, SIG_IGN);
  103. signal(SIGTSTP, SIG_IGN);
  104. if (0 != fork()) exit(0);
  105. if (-1 == setsid()) exit(0);
  106. signal(SIGHUP, SIG_IGN);
  107. if (0 != fork()) exit(0);
  108. //if (0 != chdir("/")) exit(0);
  109. }
  110. bool checkOnly()
  111. {
  112. const char filename[] = "./lockfile";
  113. int fd = open (filename, O_WRONLY | O_CREAT , 0644);
  114. int flock = lockf(fd, F_TLOCK, 0 );
  115. if (fd == -1) {
  116. return false;
  117. }
  118. //给文件加锁
  119. if (flock == -1) {
  120. return false;
  121. }
  122. //程序退出后,文件自动解锁
  123. return true;
  124. }
  125. std::string getpath()
  126. {
  127. char exec_name [BUFSIZ];
  128. readlink ("/proc/self/exe", exec_name, BUFSIZ);
  129. int32_t len=strlen(exec_name);
  130. for(int i=len;i>=0;i--)
  131. {
  132. if(exec_name[i]=='/')
  133. {
  134. exec_name[i]=0;
  135. break;
  136. }
  137. }
  138. return std::string(exec_name);
  139. }
  140. //const char *inFileName = "/home/zhouchao/2.yuv";
  141. //const char *outFileName = "/home/zhouchao/3.h264";
  142. /*
  143. int encode(AVCodecContext* codecContent, AVPacket* packet, AVFrame* frame, FILE* outFile)
  144. {
  145. //编码
  146. int ret = avcodec_send_frame(codecContent, frame);
  147. if (ret < 0)
  148. printf("Error sending a frame for encoding\r\n");
  149. while (ret == 0)
  150. {
  151. ret = avcodec_receive_packet(codecContent, packet);
  152. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  153. return 0;
  154. }
  155. else if (ret < 0)
  156. printf("Error encoding video frame\r\n");
  157. if (ret == 0)
  158. fwrite(packet->data, 1, packet->size, outFile);
  159. }
  160. }
  161. */
  162. /*
  163. #include <stdio.h>
  164. #include <dirent.h>
  165. #include <sys/stat.h>
  166. #include <string.h>
  167. int day_diffient(int year_start, int month_start, int day_start,char *Dst)
  168. {
  169. //2024-03-11
  170. int year_end = strtol(Dst,NULL,10);
  171. char Temp = '-',*p = NULL,*p1 = NULL;
  172. p = strchr(Dst,Temp);
  173. int month_end = strtol(p + 1,NULL,10);
  174. p1 = strchr(p + 1,Temp);
  175. int day_end = strtol(p1 + 1,NULL,10);
  176. int y2, m2, d2;
  177. int y1, m1, d1;
  178. m1 = (month_start + 9) % 12;
  179. y1 = year_start - m1/10;
  180. d1 = 365*y1 + y1/4 - y1/100 + y1/400 + (m1*306 + 5)/10 + (day_start - 1);
  181. m2 = (month_end + 9) % 12;
  182. y2 = year_end - m2/10;
  183. d2 = 365*y2 + y2/4 - y2/100 + y2/400 + (m2*306 + 5)/10 + (day_end - 1);
  184. return (d1 - d2);
  185. }
  186. void delete_days(const char *path)
  187. {
  188. DIR *dir;
  189. struct dirent *entry;
  190. struct stat statbuf;
  191. time_t rawtime;
  192. struct tm* info;
  193. time(&rawtime);
  194. info = localtime(&rawtime);
  195. uint8_t secret[64] = { 0 };
  196. sprintf((char*)secret, "%d-%.2d-%.2d", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
  197. printf("%s\r\n",secret);
  198. dir = opendir(path);
  199. if (dir == NULL)
  200. {
  201. printf("无法打开目录\n");
  202. return;
  203. }
  204. while ((entry = readdir(dir)) != NULL)
  205. {
  206. char file_path[1024];
  207. snprintf(file_path, sizeof(file_path), "%s/%s", path, entry->d_name);
  208. if (stat(file_path, &statbuf) == -1)
  209. continue;
  210. if (S_ISDIR(statbuf.st_mode))
  211. {
  212. if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
  213. continue;
  214. if(day_diffient(info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,entry->d_name) > 15)
  215. {
  216. char Dst[128];
  217. memset(Dst,0,128);
  218. sprintf(Dst,"rm -rf /home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log/%s",entry->d_name);
  219. system(Dst);
  220. }
  221. delete_days(file_path);
  222. }
  223. }
  224. closedir(dir);
  225. }
  226. //traverse_path("/home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log");
  227. */
  228. int main(int argc,char *argv[])
  229. {
  230. //system("pulseaudio --start");
  231. // daemonize();
  232. auto path=getpath();
  233. std::cout<<path<<std::endl;
  234. if(-1==chdir(path.c_str())) return 0;
  235. if(checkOnly()==false)
  236. {
  237. std::cout<<"进程已经在运行"<<std::endl;
  238. return 0;
  239. }
  240. /*
  241. #include <sys/statfs.h>
  242. #include <stdlib.h>
  243. #include <unistd.h>
  244. #include <sys/vfs.h>
  245. struct statfs diskInfo;
  246. statfs("/dev/mmcblk0p1", &diskInfo);
  247. unsigned long long blocksize = diskInfo.f_bsize; //每个block里包含的字节数
  248. unsigned long long totalsize = blocksize * diskInfo.f_blocks; //总的字节数,f_blocks为block的数目
  249. printf("Total_size = %llu B = %llu KB = %llu MB = %llu GB\n",
  250. totalsize, totalsize>>10, totalsize>>20, totalsize>>30);
  251. unsigned long long freeDisk = diskInfo.f_bfree * blocksize; //剩余空间的大小
  252. unsigned long long availableDisk = diskInfo.f_bavail * blocksize; //可用空间大小
  253. printf("Disk_free = %llu MB = %llu GB\nDisk_available = %llu MB = %llu GB\n",
  254. freeDisk>>20, freeDisk>>30, availableDisk>>20, availableDisk>>30);
  255. */
  256. //20230425
  257. /*
  258. TPCANStatus result;
  259. char strMsg[256];
  260. result = CAN_Initialize(PCAN_USBBUS1, PCAN_BAUD_500K);
  261. if (result != PCAN_ERROR_OK)
  262. {
  263. CAN_GetErrorText(result, 0, strMsg);
  264. std::cout << strMsg << std::endl;
  265. }
  266. else
  267. std::cout << "PCAN-USB (Ch-1) was initialized" << std::endl;
  268. TPCANMsg dataMessage;
  269. dataMessage.ID = 0x601;
  270. dataMessage.MSGTYPE = PCAN_MESSAGE_STANDARD;
  271. dataMessage.LEN = 0x03;
  272. memset(dataMessage.DATA,0x00,8);
  273. ////memcpy(dataMessage.DATA, date, dataMessage.LEN);
  274. dataMessage.DATA[0] = 0xB1;
  275. dataMessage.DATA[1] = 0x10;
  276. dataMessage.DATA[2] = 0xFF;
  277. result = CAN_Write(PCAN_USBBUS1, &dataMessage);
  278. int fd;
  279. TPCANMsg CANMsg;
  280. TPCANTimestamp CANTimeStamp;
  281. TPCANStatus stsResult = CAN_GetValue(PCAN_USBBUS1, PCAN_RECEIVE_EVENT, &fd, sizeof(fd));
  282. if (stsResult != PCAN_ERROR_OK)
  283. {
  284. std::cout << "CAN_GetValue Error" << "\n";
  285. }
  286. while (true)
  287. {
  288. struct timeval timeout = {};
  289. timeout.tv_usec = 50000; // 50ms
  290. fd_set fds;
  291. FD_ZERO(&fds);
  292. FD_SET(fd, &fds);
  293. // //Checks for messages when an event is received
  294. int err = select(fd + 1, &fds, NULL, NULL, &timeout);
  295. if (err != -1 && FD_ISSET(fd, &fds))
  296. {
  297. result = CAN_Read(PCAN_USBBUS1, &CANMsg, &CANTimeStamp);
  298. if (result != PCAN_ERROR_QRCVEMPTY)
  299. {
  300. //char Dst[128] = { 0 };
  301. // //memcpy(Dst, CANMsg.DATA, CANMsg.LEN);
  302. // //std::cout << Dst << "\n";
  303. std::cout << "111" << "\n";
  304. }
  305. }
  306. }
  307. CAN_Uninitialize(PCAN_USBBUS1);
  308. */
  309. //20230413 HMAC-SHA256签名加密
  310. // uint8_t outdata[128] = {0};
  311. //uint8_t md[SHA256_DIGESTLEN] = {0};
  312. //uint8_t secret[] = {"hallowordjdadwfxfalmfjwgrjlqsjdwg"};//密钥
  313. //uint8_t indata[] = {"halloword"};//数据
  314. //int len1 = strlen((char *)secret);
  315. //int len2 = strlen((char *)indata);
  316. //
  317. //HMAC_SHA256_CTX hmac;
  318. //hmac_sha256_init(&hmac, secret, len1);
  319. //hmac_sha256_update(&hmac, indata, len2);
  320. //hmac_sha256_final(&hmac, md);
  321. //memcpy(outdata, md, SHA256_DIGESTLEN);
  322. //for(int i = 0; i < SHA256_DIGESTLEN; i++)
  323. //{
  324. // printf("%02x",outdata[i]);
  325. //}
  326. //printf("\n");
  327. /*
  328. //20230413 json
  329. Json::Value root;
  330. Json::Value Source;
  331. Json::FastWriter writer;
  332. Source["deviceEsn"] = "";
  333. Source["cloudEsn"] = "";
  334. Source["sendTime"] = "time";
  335. Source["ack"] = false;
  336. Source["seqNum"] = "";
  337. Json::Value GraspStatus;
  338. GraspStatus["graspEsn"] = Json::Value("graspEsn");
  339. GraspStatus["status"] = Json::Value("status");
  340. GraspStatus["timeStamp"] = Json::Value("timeStamp");
  341. Source["graspStatusList"].append(GraspStatus);
  342. //root.append(Source);
  343. Json::StyledWriter sw;
  344. std::cout << sw.write(Source) << std::endl << std::endl;
  345. //std::string data = writer.write(root);
  346. //std::cout << data << std::endl;
  347. */
  348. /*struct timeval tv;
  349. gettimeofday(&tv, NULL);
  350. printf("millisecond: %ld\n", tv.tv_sec * 1000 + tv.tv_usec / 1000);*/
  351. //20230413 mqtt
  352. //int rc;
  353. //const char* serverUrl = "tcp://localhost:1883"; //服务器地址
  354. //const char* clientId = "publish_client"; //客户端标识符
  355. //const char* userName = ""; //用户名
  356. //const char* password = ""; //密码
  357. //MQTTAsync_create(&mqttClient, serverUrl, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL);
  358. //MQTTAsync_setCallbacks(mqttClient, NULL, Disconnect, RecevieMessage, NULL); //设置连接断开和接受数据回调
  359. //MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; //初始化结构体
  360. //conn_opts.cleansession = 1;
  361. //conn_opts.username = userName;
  362. //conn_opts.password = password;
  363. //conn_opts.onFailure = onConnectFailure; //连接失败回调
  364. //conn_opts.context = mqttClient;
  365. //conn_opts.automaticReconnect = true; //开启断开自动重连
  366. //conn_opts.minRetryInterval = 5; //最小重连间隔时间(秒),每次失败重连间隔时间都会加倍
  367. //conn_opts.maxRetryInterval = 365 * 24 * 60 * 60; //最大重连间隔时间(秒)
  368. //MQTTAsync_setConnected(mqttClient, NULL, onConnectCallCBack); //设置连接成功回调,不管是第一次连接成功还是重连成功都会调用此回调
  369. //if ((rc = MQTTAsync_connect(mqttClient, &conn_opts)) != MQTTASYNC_SUCCESS) //尝试连接
  370. //{
  371. // printf("MQTTAsync_connect() fail, error code:%d\n", rc);
  372. //}
  373. /*
  374. double temp=0.f;
  375. auto err=sensors_init(NULL);
  376. if(err==0)
  377. {
  378. const sensors_chip_name *chip;
  379. int chip_nr=0;
  380. int i=0;
  381. const sensors_feature * feature=nullptr;
  382. while ((chip = sensors_get_detected_chips(NULL, &chip_nr)))
  383. {
  384. if ((feature = sensors_get_features(chip, &i)))
  385. {
  386. if (feature->type==SENSORS_FEATURE_TEMP)
  387. {
  388. auto sf = sensors_get_subfeature(chip, feature,SENSORS_SUBFEATURE_TEMP_INPUT);
  389. if(sf->type == SENSORS_SUBFEATURE_TEMP_INPUT)
  390. {
  391. sensors_get_value(chip, sf->number,&temp);
  392. //temp = temp * (9.0F / 5.0F) + 32.0F;
  393. std::cout << "System_Temp : " << temp << std::endl;
  394. }
  395. }
  396. }
  397. }
  398. }m
  399. sensors_cleanup();
  400. */
  401. //20231106-YUV转h.264
  402. /*
  403. AVCodec* codec = NULL;
  404. //AVCodecContext* codecContent = NULL;
  405. //AVPacket* packet = NULL;
  406. //AVFrame* frame = NULL;
  407. FILE* inFile = nullptr;
  408. FILE* outFile = nullptr;
  409. //查找指定编码器
  410. codec = avcodec_find_encoder(AV_CODEC_ID_H264);
  411. if (codec == NULL)
  412. printf("could not find h264 encoder!\r\n");
  413. else
  414. printf("could find h264 encoder!\r\n");
  415. */
  416. /*
  417. //申请编码器上下文
  418. codecContent = avcodec_alloc_context3(codec);
  419. if (codecContent == nullptr)
  420. printf("could not alloc h264 content!\r\n");
  421. //必设参数
  422. codecContent->width = 1280;
  423. codecContent->height = 720;
  424. codecContent->time_base = AVRational{ 1, 25 };
  425. codecContent->max_b_frames = 1;
  426. codecContent->pix_fmt = AV_PIX_FMT_YUV420P;
  427. codecContent->gop_size = 10; //关键帧间隔,默认250
  428. codecContent->framerate = AVRational{ 25, 1 };
  429. //初始化编码器上下文
  430. ret = avcodec_open2(codecContent, codec, NULL);
  431. if (ret < 0)
  432. printf("Could not open codec: \r\n");
  433. packet = av_packet_alloc();
  434. if (packet == nullptr)
  435. printf("alloc packet error\r\n");
  436. frame = av_frame_alloc();
  437. if (packet == nullptr)
  438. printf("alloc frame error\r\n");
  439. //必设参数
  440. frame->width = codecContent->width;
  441. frame->height = codecContent->height;
  442. frame->format = codecContent->pix_fmt;
  443. //申请视频数据存储空间
  444. ret = av_frame_get_buffer(frame, 0);
  445. if (ret)
  446. printf("alloc frame buffer error!\r\n");
  447. inFile = fopen(inFileName, "rb");
  448. if (inFile == nullptr)
  449. printf("error to open inFile: %s\r\n", inFileName);
  450. outFile = fopen(outFileName, "wb+");
  451. if (inFile == nullptr)
  452. printf("error to open outFile: %s\n", outFileName);
  453. int framecount = 0;
  454. frame->pts = 0;
  455. int start_time = av_gettime() / 1000; //毫秒级
  456. while (!feof(inFile))
  457. {
  458. ret = av_frame_is_writable(frame);
  459. if (ret < 0)
  460. ret = av_frame_make_writable(frame);
  461. fread(frame->data[0], 1, frame->width * frame->height, inFile); //y
  462. fread(frame->data[1], 1, frame->width * frame->height / 4, inFile); //u
  463. fread(frame->data[2], 1, frame->width * frame->height / 4, inFile); //v
  464. printf("encode frame num: %d\n", ++framecount);
  465. frame->pts += 1000 / (codecContent->time_base.den / codecContent->time_base.num);
  466. encode(codecContent, packet, frame, outFile);
  467. }
  468. encode(codecContent, packet, nullptr, outFile);
  469. printf("encode time cost: %d ms\n ", av_gettime() / 1000 - start_time);
  470. av_packet_free(&packet);
  471. av_frame_free(&frame);
  472. avcodec_free_context(&codecContent);
  473. fclose(inFile);
  474. fclose(outFile);
  475. */
  476. /*
  477. int16_t hi=(int16_t)(0x8c & 0x00FF);
  478. int16_t low= (int16_t)(0x9E & 0x00FF);
  479. unsigned int mmmm = (hi<<8)|low;
  480. */
  481. CMessageQueue Q;
  482. Q.Create();
  483. while(true)
  484. {
  485. Q.Process();
  486. }
  487. //gtk_main();
  488. return 0;
  489. }