main.cpp 17 KB

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