out_sim.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #define WIN32_LEAN_AND_MEAN
  2. #include <windows.h>
  3. #include <WS2tcpip.h>
  4. #include <WinSock2.h>
  5. #include "Protocol.pb.h"
  6. #include <sstream>
  7. #include "out_sim.h"
  8. #include "../common/iobuffer.h"
  9. COutSim::COutSim(const char* ip, int32_t port) :_head(nullptr),_ip(ip),_port(port)
  10. {
  11. }
  12. void COutSim::Start()
  13. {
  14. WSAData data;
  15. WSAStartup(MAKEWORD(2, 2), &data);
  16. _socket = socket(AF_INET, SOCK_DGRAM, 0);
  17. sockaddr_in sin;
  18. sin.sin_family = AF_INET;
  19. sin.sin_port = htons(_port);
  20. inet_pton(AF_INET, _ip.c_str(), &sin.sin_addr);
  21. connect(_socket, (sockaddr*)&sin, sizeof(sin));
  22. _thread = std::thread(std::bind(&COutSim::Run, this));
  23. }
  24. void COutSim::Stop()
  25. {
  26. closesocket(_socket);
  27. if (_run == true)
  28. {
  29. _run = false;
  30. Mtx.lock();
  31. cv.notify_all();
  32. Mtx.unlock();
  33. _thread.join();
  34. }
  35. }
  36. void COutSim::PushSimPack(CIOBuffer* pBuffer)
  37. {
  38. std::unique_lock <std::mutex> lck(Mtx);
  39. //bool bNull = false;
  40. if (_head == nullptr)
  41. {
  42. _head = pBuffer;
  43. }
  44. else {
  45. _head->Release();
  46. _head = pBuffer;
  47. }
  48. }
  49. void COutSim::Run()
  50. {
  51. _run = true;
  52. while (_run)
  53. {
  54. if (!_run) break;
  55. if (_head != nullptr)
  56. SendOutSim(_head);
  57. Sleep(30);
  58. }
  59. }
  60. bool COutSim::SendOutSim(CIOBuffer* pBuffer)
  61. {
  62. int32_t ret = send(_socket, (const char *)pBuffer->Buffer, pBuffer->Length, 0);
  63. return ret == pBuffer->Length;
  64. }
  65. void COutSim::OnPeerMessage(int16_t cmd, int16_t length, const void* data)
  66. {
  67. RemoNet::IMuMessage rep;
  68. rep.ParseFromArray(data, length);
  69. CIOBuffer* buffer=CIOBuffer::Alloc();
  70. OutSimPack p;
  71. //= (OutSimPack*)buffer->Buffer;
  72. p.rx = (rep.rx()*3.1415926) /180.f ;
  73. p.ry = (rep.ry()*3.1415926)/180.f;
  74. p.rz = 0;
  75. memcpy(buffer->Buffer, &p, sizeof(p));
  76. buffer->Length = sizeof(p);
  77. //std::ostringstream str;
  78. //str << p.rx <<","<< p.ry << std::endl;
  79. // OutputDebugStringA(str.str().c_str());
  80. buffer->Length = sizeof(OutSimPack);
  81. PushSimPack(buffer);
  82. }