lichao
2021-05-10 77a6c3512a44dfe6540dde71946e6484fe4f173f
src/socket.cpp
@@ -20,57 +20,24 @@
#include "bh_util.h"
#include "defs.h"
#include "msg.h"
#include <chrono>
using namespace bhome_msg;
using namespace bhome_shm;
using namespace std::chrono_literals;
namespace
ShmSocket::ShmSocket(Shm &shm, const MQId id, const int len) :
    run_(false), mq_(id, shm, len)
{
int GetSocketDefaultLen(ShmSocket::Type type)
{
   switch (type) {
   case ShmSocket::eSockRequest: return 12;
   case ShmSocket::eSockReply: return 64;
   case ShmSocket::eSockPublish: return 0;
   case ShmSocket::eSockSubscribe: return 64;
   default: return 0;
   }
   Start();
}
} // namespace
ShmSocket::ShmSocket(Type type, bhome_shm::SharedMemory &shm) :
    shm_(shm), type_(type), run_(false)
ShmSocket::ShmSocket(Shm &shm, const bool create_or_else_find, const MQId id, const int len) :
    run_(false), mq_(id, create_or_else_find, shm, len)
{
   int len = GetSocketDefaultLen(type);
   if (len != 0) {
      mq_.reset(new Queue(shm_, len));
      auto RecvProc = [this]() {
         while (run_) {
            try {
               std::unique_lock<std::mutex> lk(mutex_);
               if (cv_recv_cb_.wait_for(lk, 100ms, [this]() { return HasRecvCB(); })) {
                  BHMsg msg;
                  if (mq_->Recv(msg, 100)) {
                     this->onRecv_(msg);
                  }
               }
            } catch (...) {
            }
         }
      };
      run_.store(true);
      workers_.emplace_back(RecvProc);
   }
   Start();
}
ShmSocket::ShmSocket(Type type) :
    ShmSocket(type, BHomeShm())
ShmSocket::ShmSocket(bhome_shm::SharedMemory &shm, const int len) :
    run_(false), mq_(shm, len)
{
   Start();
}
ShmSocket::~ShmSocket()
@@ -78,57 +45,125 @@
   Stop();
}
bool ShmSocket::Publish(const std::string &topic, const void *data, const size_t size, const int timeout_ms)
bool ShmSocket::Start(const RawRecvCB &onData, const IdleCB &onIdle, int nworker)
{
   if (type_ != eSockPublish) {
      return false;
   }
   assert(!mq_);
   try {
      MsgI imsg;
      if (!imsg.MakeRC(shm_, MakePub(topic, data, size))) {
         return false;
   auto ioProc = [this, onData, onIdle]() {
      auto DoSend = [this]() { return send_buffer_.TrySend(mq()); };
      auto DoRecv = [=] {
         // do not recv if no cb is set.
         if (!onData) {
            return false;
         }
         auto onMsg = [&](MsgI &imsg) {
            DEFER1(imsg.Release());
            onData(*this, imsg);
         };
         MsgI imsg;
         return mq().TryRecv(imsg) ? (onMsg(imsg), true) : false;
      };
      try {
         bool more_to_send = DoSend();
         bool more_to_recv = DoRecv();
         if (onIdle) { onIdle(*this); }
         if (!more_to_send && !more_to_recv) {
            robust::QuickSleep();
         }
      } catch (...) {
      }
      DEFER1(imsg.Release(shm_));
      return Queue::Send(shm_, kBHBusQueueId, imsg, timeout_ms);
   };
   } catch (...) {
      return false;
   }
}
bool ShmSocket::Subscribe(const std::vector<std::string> &topics, const int timeout_ms)
{
   if (type_ != eSockSubscribe) {
      return false;
   }
   assert(mq_);
   try {
      return mq_->Send(kBHBusQueueId, MakeSub(mq_->Id(), topics), timeout_ms);
   } catch (...) {
      return false;
   }
}
bool ShmSocket::SetRecvCallback(const RecvCB &onRecv)
{
   std::lock_guard<std::mutex> lock(mutex_);
   onRecv_ = onRecv;
   cv_recv_cb_.notify_one();
   StopNoLock();
   run_.store(true);
   for (int i = 0; i < nworker; ++i) {
      workers_.emplace_back([this, ioProc]() { while (run_) { ioProc(); } });
   }
   return true;
}
bool ShmSocket::HasRecvCB()
bool ShmSocket::Start(int nworker, const RecvCB &onData, const IdleCB &onIdle)
{
   return static_cast<bool>(onRecv_);
   auto ioProc = [this, onData, onIdle]() {
      auto DoSend = [this]() { return send_buffer_.TrySend(mq()); };
      auto DoRecv = [=] {
         auto onRecvWithPerMsgCB = [this, onData](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) {
            RecvCB cb;
            if (per_msg_cbs_->Pick(head.msg_id(), cb)) {
               cb(socket, imsg, head);
            } else if (onData) {
               onData(socket, imsg, head);
            }
         };
         // do not recv if no cb is set.
         if (!onData && per_msg_cbs_->empty()) {
            return false;
         }
         auto onMsg = [&](MsgI &imsg) {
            DEFER1(imsg.Release());
            BHMsgHead head;
            if (imsg.ParseHead(head)) {
               onRecvWithPerMsgCB(*this, imsg, head);
            }
         };
         MsgI imsg;
         return mq().TryRecv(imsg) ? (onMsg(imsg), true) : false;
      };
      try {
         bool more_to_send = DoSend();
         bool more_to_recv = DoRecv();
         if (onIdle) { onIdle(*this); }
         if (!more_to_send && !more_to_recv) {
            robust::QuickSleep();
         }
      } catch (...) {
      }
   };
   std::lock_guard<std::mutex> lock(mutex_);
   StopNoLock();
   run_.store(true);
   for (int i = 0; i < nworker; ++i) {
      workers_.emplace_back([this, ioProc]() { while (run_) { ioProc(); } });
   }
   return true;
}
void ShmSocket::Stop()
bool ShmSocket::Stop()
{
   run_ = false;
   for (auto &t : workers_) {
      if (t.joinable()) {
         t.join();
   std::lock_guard<std::mutex> lock(mutex_);
   return StopNoLock();
}
bool ShmSocket::StopNoLock()
{
   if (run_.exchange(false)) {
      for (auto &w : workers_) {
         if (w.joinable()) {
            w.join();
         }
      }
      workers_.clear();
      return true;
   }
   return false;
}
//maybe reimplment, using async cbs?
bool ShmSocket::SyncRecv(bhome_msg::MsgI &msg, bhome_msg::BHMsgHead &head, const int timeout_ms)
{
   // std::lock_guard<std::mutex> lock(mutex_); // seems no need to lock mutex_.
   bool got = (timeout_ms == 0) ? mq().TryRecv(msg) : mq().Recv(msg, timeout_ms);
   if (got) {
      if (msg.ParseHead(head)) {
         return true;
      } else {
         msg.Release();
      }
   }
}
   return false;
}