monitor_emqx.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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(double v,double a)
  36. {
  37. MqttMsg msg;
  38. msg.fromSpeed(v,a);
  39. if(client_)
  40. client_->publish(pubTopic_,1,msg);
  41. else
  42. printf("set speed failed : emqx client disconnected...\n");
  43. }
  44. void Monitor_emqx::rotate(double v)
  45. {
  46. MqttMsg msg;
  47. msg.fromSpeed(0,v);
  48. if(client_)
  49. client_->publish(pubTopic_,1,msg);
  50. else
  51. printf("rotate failed : emqx client disconnected...\n");
  52. }
  53. void Monitor_emqx::stop()
  54. {
  55. MqttMsg msg;
  56. msg.fromSpeed(0,0);
  57. if(client_)
  58. client_->publish(pubTopic_,1,msg);
  59. else
  60. printf("stop failed : emqx client disconnected...\n");
  61. }
  62. Monitor_emqx::Monitor_emqx(std::string nodeId,std::string pubTopic,std::string subTopic)
  63. :client_(nullptr),nodeId_(nodeId),pubTopic_(pubTopic),subTopic_(subTopic)
  64. {
  65. StatuArrivedCallback_= nullptr;
  66. context_= nullptr;
  67. }
  68. void Monitor_emqx::StatuArrivedCallback(std::string topic,int QOS,MqttMsg& msg,void* context)
  69. {
  70. Monitor_emqx* monitor=(Monitor_emqx*)context;
  71. double x=0,y=0,theta=0,v=0,vth=0;
  72. if(msg.toStatu(x,y,theta,v,vth))
  73. {
  74. if (monitor->StatuArrivedCallback_)
  75. monitor->StatuArrivedCallback_(x, y, theta, v, vth,monitor->context_);
  76. }
  77. }