event_log.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include "event_log.h"
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <stdlib.h>
  6. #include <iostream>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <time.h>
  10. #include <sstream>
  11. void CEventLog::Start()
  12. {
  13. if(access("./log/",F_OK)!=0)
  14. {
  15. int status = mkdir("./log/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  16. if (status == 0) {
  17. std::cout << "文件夹创建成功!" << std::endl;
  18. } else {
  19. std::cout << "文件夹创建失败!" << std::endl;
  20. }
  21. }
  22. std::stringstream oss;
  23. oss<<"./log/"<<GetLocalTime()<<".log";
  24. std::string str=oss.str();
  25. _ofile.open(str,std::ios_base::out);
  26. _thread=std::thread(&CEventLog::Run,this);
  27. // _ofile.open()
  28. }
  29. std::string CEventLog::GetLocalTime()
  30. {
  31. time_t t=time(nullptr);
  32. tm * ld=localtime(&t);
  33. char tmp[128];
  34. strftime(tmp,sizeof(tmp),"%Y-%m-%d-%H-%M-%S",ld);
  35. return std::string(tmp);
  36. }
  37. void CEventLog::Run()
  38. {
  39. _run=true;
  40. while(_run)
  41. {
  42. EventType type;
  43. int32_t steer,accel,brake;
  44. {
  45. std::lock_guard<std::mutex> l(_mutex);
  46. type=_type;
  47. steer=_steer;
  48. accel=_accel;
  49. brake=_brake;
  50. }
  51. if(type!=EventType::NORMAL)
  52. {
  53. std::string s;
  54. switch(_type)
  55. {
  56. case EventType::EMERGENCY:
  57. s= "碰撞临界:";
  58. break;
  59. case EventType::OFFLINE:
  60. s="车辆掉线:";
  61. break;
  62. case EventType::LOW_RPM:
  63. s="车辆熄火:";
  64. break;
  65. };
  66. std::stringstream oss;
  67. oss<<GetLocalTime()<<": "<<s<<" 方向盘速度:"<<_steer<<", 油门值:"<<_accel<<", 刹车值:"<<_brake;
  68. std::string str=oss.str();
  69. _ofile<<str.c_str()<<std::endl;
  70. }
  71. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  72. }
  73. }
  74. void CEventLog::Stop()
  75. {
  76. _ofile.close();
  77. _run=false;
  78. _thread.join();
  79. }
  80. void CEventLog::SetEvent(EventType type, int32_t steer,int32_t accel,int32_t brake)
  81. {
  82. std::lock_guard<std::mutex> l(_mutex);
  83. _type=type;
  84. _steer=steer;
  85. _accel=accel;
  86. _brake=brake;
  87. }