monitor.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. //
  2. // Created by zx on 22-12-7.
  3. //
  4. #include "monitor.h"
  5. void Stringsplit(const std::string& str, const char split, std::vector<std::string>& res)
  6. {
  7. if (str == "") return;
  8. //在字符串末尾也加入分隔符,方便截取最后一段
  9. std::string strs = str + split;
  10. size_t pos = strs.find(split);
  11. // 若找不到内容则字符串搜索函数返回 npos
  12. while (pos != strs.npos)
  13. {
  14. std::string temp = strs.substr(0, pos);
  15. res.push_back(temp);
  16. //去掉已分割的字符串,在剩下的字符串中进行分割
  17. strs = strs.substr(pos + 1, strs.size());
  18. pos = strs.find(split);
  19. }
  20. }
  21. Monitor* Monitor::g_Monitor= nullptr;
  22. Monitor* Monitor::get_instance()
  23. {
  24. if(g_Monitor== nullptr)
  25. {
  26. g_Monitor=new Monitor();
  27. }
  28. return g_Monitor;
  29. }
  30. Monitor::Monitor(){
  31. set_read_callback(recv_callback,this);
  32. }
  33. Monitor::~Monitor()
  34. {
  35. }
  36. void Monitor::set_speed(double v,double a)
  37. {
  38. v_=v;
  39. a_=a;
  40. char buf[255]={0};
  41. sprintf(buf,"V:%f;A:%f",v,a);
  42. write_data(buf);
  43. }
  44. void Monitor::set_statucallback(StatuCallback callback)
  45. {
  46. callback_=callback;
  47. }
  48. void Monitor::recv_callback(char* data,void* p)
  49. {
  50. Monitor* pMonitor= (Monitor*)p;
  51. if(pMonitor== nullptr)
  52. return;
  53. std::string recv(data);
  54. std::vector<std::string> splits;
  55. Stringsplit(recv,';',splits);
  56. if(splits.size()!=3)
  57. return ;
  58. std::string pose_str=splits[0];
  59. std::string v_str=splits[1];
  60. std::string a_str=splits[2];
  61. std::vector<std::string> pose_split;
  62. Stringsplit(pose_str,':',pose_split);
  63. if(pose_split.size()==2)
  64. {
  65. std::string pose_value=pose_split[1];
  66. std::vector<std::string> value_strs;
  67. Stringsplit(pose_value,',',value_strs);
  68. if(value_strs.size()==3)
  69. {
  70. float x=atof(value_strs[0].c_str());
  71. float y=atof(value_strs[1].c_str());
  72. float theta=atof(value_strs[2].c_str());
  73. pMonitor->mtx_.lock();
  74. pMonitor->pose_=Pose2d(x,y,theta);
  75. pMonitor->mtx_.unlock();
  76. //std::cout<<"pose:"<<pMonitor->pose_;
  77. }
  78. }
  79. std::vector<std::string> v_split;
  80. Stringsplit(v_str,':',v_split);
  81. if(v_split.size()==2)
  82. {
  83. pMonitor->v_=atof(v_split[1].c_str());
  84. //std::cout<<"; v:"<<pMonitor->v_;
  85. }
  86. std::vector<std::string> a_split;
  87. Stringsplit(a_str,':',a_split);
  88. if(a_split.size()==2)
  89. {
  90. pMonitor->a_=atof(a_split[1].c_str());
  91. //std::cout<<"; a:"<<pMonitor->a_;
  92. }
  93. //std::cout<<std::endl;
  94. if(pMonitor->callback_!= nullptr)
  95. pMonitor->callback_(pMonitor->pose_,pMonitor->v_,pMonitor->a_);
  96. }