monitor_emqx.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // Created by zx on 23-3-14.
  3. //
  4. #include "monitor_emqx.h"
  5. #include <unistd.h>
  6. Monitor_emqx::~Monitor_emqx()
  7. {
  8. if(client_!= nullptr){
  9. client_->disconnect();
  10. delete client_;
  11. client_= nullptr;
  12. }
  13. }
  14. bool Monitor_emqx::Connect(std::string ip,int port)
  15. {
  16. if(client_!= nullptr)
  17. {
  18. client_->disconnect();
  19. delete client_;
  20. }
  21. client_=new Paho_client(nodeId_);
  22. bool ret= client_->connect(ip,port);
  23. if(ret)
  24. {
  25. while(!client_->isconnected()) usleep(1000);
  26. client_->subcribe(subTopic_,1,StatuArrivedCallback,this);
  27. }
  28. return ret;
  29. }
  30. void Monitor_emqx::set_statu_arrived_callback(StatuCallback callback,void* context)
  31. {
  32. StatuArrivedCallback_=callback;
  33. context_=context;
  34. }
  35. void Monitor_emqx::set_speed(SpeedType type,double v,double a)
  36. {
  37. MqttMsg msg;
  38. NavMessage::Speed speed;
  39. heat_=(heat_++)%255;
  40. speed.set_h(heat_);
  41. speed.set_t(type);
  42. speed.set_v(v);
  43. speed.set_w(a);
  44. msg.fromProtoMessage(speed);
  45. if(client_)
  46. client_->publish(pubTopic_,1,msg);
  47. else
  48. printf("set speed failed : emqx client disconnected...\n");
  49. }
  50. void Monitor_emqx::stop()
  51. {
  52. MqttMsg msg;
  53. NavMessage::Speed speed;
  54. heat_=(heat_++)%255;
  55. speed.set_h(heat_);
  56. speed.set_t(eStop);
  57. speed.set_v(0);
  58. speed.set_w(0);
  59. msg.fromProtoMessage(speed);
  60. if(client_)
  61. client_->publish(pubTopic_,1,msg);
  62. else
  63. printf("stop failed : emqx client disconnected...\n");
  64. }
  65. Monitor_emqx::Monitor_emqx(std::string nodeId,std::string pubTopic,std::string subTopic)
  66. :client_(nullptr),nodeId_(nodeId),pubTopic_(pubTopic),subTopic_(subTopic)
  67. {
  68. heat_=0;
  69. StatuArrivedCallback_= nullptr;
  70. context_= nullptr;
  71. }
  72. void Monitor_emqx::StatuArrivedCallback(std::string topic,int QOS,MqttMsg& msg,void* context)
  73. {
  74. Monitor_emqx* monitor=(Monitor_emqx*)context;
  75. NavMessage::AGVStatu statu;
  76. if(msg.toProtoMessage(statu))
  77. {
  78. if (monitor->StatuArrivedCallback_)
  79. monitor->StatuArrivedCallback_(statu.x(), statu.y(), statu.theta(), statu.v(), statu.vth(),monitor->context_);
  80. }
  81. }