cec: make all reads and write in CAdapterCommunication go through buffers, so we...
[deb_libcec.git] / src / lib / AdapterCommunication.cpp
index a7466b70a1013c11fb9e231b1e0eb130434f1134..2e330d3fe1005596714019952db40e6f5572a019 100644 (file)
 #include "LibCEC.h"
 #include "platform/serialport.h"
 #include "util/StdString.h"
+#include "platform/timeutils.h"
 
 using namespace std;
 using namespace CEC;
 
 CAdapterCommunication::CAdapterCommunication(CLibCEC *controller) :
-    m_controller(controller),
-    m_inbuf(NULL),
-    m_iInbufSize(0),
-    m_iInbufUsed(0),
-    m_bStarted(false),
-    m_bStop(false)
+    m_port(NULL),
+    m_controller(controller)
 {
   m_port = new CSerialPort;
 }
 
 CAdapterCommunication::~CAdapterCommunication(void)
 {
-  m_port->Close();
-  m_port = NULL;
+  Close();
+
+  if (m_port)
+  {
+    delete m_port;
+    m_port = NULL;
+  }
 }
 
-bool CAdapterCommunication::Open(const char *strPort, int iBaudRate /* = 38400 */, int iTimeoutMs /* = 10000 */)
+bool CAdapterCommunication::Open(const char *strPort, uint16_t iBaudRate /* = 38400 */, uint32_t iTimeoutMs /* = 10000 */)
 {
   CLockObject lock(&m_commMutex);
-  if (m_bStarted)
+  if (!m_port)
+  {
+    m_controller->AddLog(CEC_LOG_ERROR, "port is NULL");
     return false;
+  }
+
+  if (IsOpen())
+  {
+    m_controller->AddLog(CEC_LOG_ERROR, "port is already open");
+  }
 
   if (!m_port->Open(strPort, iBaudRate))
   {
@@ -74,21 +84,16 @@ bool CAdapterCommunication::Open(const char *strPort, int iBaudRate /* = 38400 *
 
   //clear any input bytes
   uint8_t buff[1024];
-  m_port->Read(buff, sizeof(buff), 50);
-
-  CCondition::Sleep(CEC_SETTLE_DOWN_TIME);
-
-  m_bStop = false;
-  m_bStarted = true;
+  m_port->Read(buff, sizeof(buff), 500);
 
   if (CreateThread())
   {
-    m_controller->AddLog(CEC_LOG_DEBUG, "reader thread created");
+    m_controller->AddLog(CEC_LOG_DEBUG, "communication thread created");
     return true;
   }
   else
   {
-    m_controller->AddLog(CEC_LOG_DEBUG, "could not create a reader thread");
+    m_controller->AddLog(CEC_LOG_DEBUG, "could not create a communication thread");
   }
 
   return false;
@@ -96,37 +101,36 @@ bool CAdapterCommunication::Open(const char *strPort, int iBaudRate /* = 38400 *
 
 void CAdapterCommunication::Close(void)
 {
+  CLockObject lock(&m_commMutex);
   StopThread();
-  m_port->Close();
+
+  m_rcvCondition.Broadcast();
 }
 
 void *CAdapterCommunication::Process(void)
 {
-  while (!m_bStop)
-  {
-    if (!ReadFromDevice(250))
-    {
-      m_bStarted = false;
-      break;
-    }
+  m_controller->AddLog(CEC_LOG_DEBUG, "communication thread started");
 
-    CCondition::Sleep(50);
+  while (!IsStopped())
+  {
+    ReadFromDevice(100);
+    WriteNextCommand();
+    Sleep(5);
   }
 
-  m_controller->AddLog(CEC_LOG_DEBUG, "reader thread terminated");
-
-  CLockObject lock(&m_commMutex);
-  m_bStarted = false;
   return NULL;
 }
 
-bool CAdapterCommunication::ReadFromDevice(int iTimeout)
+bool CAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
 {
-  uint8_t buff[1024];
   CLockObject lock(&m_commMutex);
-  int iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
-  lock.Leave();
-  if (iBytesRead < 0)
+  int32_t iBytesRead;
+  uint8_t buff[1024];
+  if (!m_port)
+    return false;
+
+  iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
+  if (iBytesRead < 0 || iBytesRead > 256)
   {
     CStdString strError;
     strError.Format("error reading from serial port: %s", m_port->GetError().c_str());
@@ -134,134 +138,95 @@ bool CAdapterCommunication::ReadFromDevice(int iTimeout)
     return false;
   }
   else if (iBytesRead > 0)
-    AddData(buff, iBytesRead);
+    AddData(buff, (uint8_t) iBytesRead);
 
-  return true;
+  return iBytesRead > 0;
 }
 
-void CAdapterCommunication::AddData(uint8_t *data, int iLen)
+void CAdapterCommunication::AddData(uint8_t *data, uint8_t iLen)
 {
   CLockObject lock(&m_bufferMutex);
-  if (iLen + m_iInbufUsed > m_iInbufSize)
-  {
-    m_iInbufSize = iLen + m_iInbufUsed;
-    m_inbuf = (uint8_t*)realloc(m_inbuf, m_iInbufSize);
-  }
+  for (unsigned int iPtr = 0; iPtr < iLen; iPtr++)
+    m_inBuffer.Push(data[iPtr]);
 
-  memcpy(m_inbuf + m_iInbufUsed, data, iLen);
-  m_iInbufUsed += iLen;
-  lock.Leave();
-  m_condition.Signal();
+  m_rcvCondition.Signal();
 }
 
-bool CAdapterCommunication::Write(const cec_frame &data)
+void CAdapterCommunication::WriteNextCommand(void)
 {
   CLockObject lock(&m_commMutex);
-
-  if (m_port->Write(data) != data.size())
+  cec_adapter_message msg;
+  if (m_outBuffer.Pop(msg))
   {
-    CStdString strError;
-    strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
-    m_controller->AddLog(CEC_LOG_ERROR, strError);
-    return false;
+    if (m_port->Write(msg) != (int32_t) msg.size())
+    {
+      CStdString strError;
+      strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
+      m_controller->AddLog(CEC_LOG_ERROR, strError);
+    }
+    else
+    {
+      m_controller->AddLog(CEC_LOG_DEBUG, "command sent");
+      CCondition::Sleep((uint32_t) msg.size() * (uint32_t)24 /*data*/ + (uint32_t)5 /*start bit (4.5 ms)*/);
+    }
   }
+}
 
-  m_controller->AddLog(CEC_LOG_DEBUG, "command sent");
-
-  CCondition::Sleep((int) data.size() * 24 /*data*/ + 5 /*start bit (4.5 ms)*/ + 50 /* to be on the safe side */);
-
+bool CAdapterCommunication::Write(const cec_adapter_message &data)
+{
+  m_outBuffer.Push(data);
   return true;
 }
 
-bool CAdapterCommunication::Read(cec_frame &msg, int iTimeout)
+bool CAdapterCommunication::Read(cec_adapter_message &msg, uint32_t iTimeout)
 {
   CLockObject lock(&m_bufferMutex);
 
-  if (m_iInbufUsed < 1)
-    m_condition.Wait(&m_bufferMutex, iTimeout);
-
-  if (m_iInbufUsed < 1)
-    return false;
+  msg.clear();
+  uint64_t iNow = GetTimeMs();
+  uint64_t iTarget = iNow + iTimeout;
+  bool bGotFullMessage(false);
+  bool bNextIsEscaped(false);
+  bool bGotStart(false);
 
-  //search for first start of message
-  int startpos = -1;
-  for (int i = 0; i < m_iInbufUsed; i++)
+  while(!bGotFullMessage && iNow < iTarget)
   {
-    if (m_inbuf[i] == MSGSTART)
+    uint8_t buf = 0;
+    if (!m_inBuffer.Pop(buf))
     {
-      startpos = i;
-      break;
+      if (!m_rcvCondition.Wait(&m_bufferMutex, iTarget - iNow))
+        return false;
     }
-  }
-
-  if (startpos == -1)
-    return false;
-
-  //move anything from the first start of message to the beginning of the buffer
-  if (startpos > 0)
-  {
-    memmove(m_inbuf, m_inbuf + startpos, m_iInbufUsed - startpos);
-    m_iInbufUsed -= startpos;
-  }
 
-  if (m_iInbufUsed < 2)
-    return false;
-
-  //look for end of message
-  startpos = -1;
-  int endpos = -1;
-  for (int i = 1; i < m_iInbufUsed; i++)
-  {
-    if (m_inbuf[i] == MSGEND)
+    if (!bGotStart)
     {
-      endpos = i;
-      break;
+      if (buf == MSGSTART)
+        bGotStart = true;
+      continue;
     }
-    else if (m_inbuf[i] == MSGSTART)
+    else if (buf == MSGSTART) //we found a msgstart before msgend, this is not right, remove
     {
-      startpos = i;
-      break;
+      m_controller->AddLog(CEC_LOG_ERROR, "received MSGSTART before MSGEND");
+      msg.clear();
+      bGotStart = true;
     }
-  }
-
-  if (startpos > 0) //we found a msgstart before msgend, this is not right, remove
-  {
-    m_controller->AddLog(CEC_LOG_ERROR, "received MSGSTART before MSGEND");
-    memmove(m_inbuf, m_inbuf + startpos, m_iInbufUsed - startpos);
-    m_iInbufUsed -= startpos;
-    return false;
-  }
 
-  if (endpos > 0) //found a MSGEND
-  {
-    msg.clear();
-    bool isesc = false;
-    for (int i = 1; i < endpos; i++)
+    if (buf == MSGEND)
     {
-      if (isesc)
-      {
-        msg.push_back(m_inbuf[i] + (uint8_t)ESCOFFSET);
-        isesc = false;
-      }
-      else if (m_inbuf[i] == MSGESC)
-      {
-        isesc = true;
-      }
-      else
-      {
-        msg.push_back(m_inbuf[i]);
-      }
+      bGotFullMessage = true;
     }
-
-    if (endpos + 1 < m_iInbufUsed)
-      memmove(m_inbuf, m_inbuf + endpos + 1, m_iInbufUsed - endpos - 1);
-
-    m_iInbufUsed -= endpos + 1;
-
-    return true;
+    else if (bNextIsEscaped)
+    {
+      msg.push_back(buf + (uint8_t)ESCOFFSET);
+      bNextIsEscaped = false;
+    }
+    else if (buf == MSGESC)
+      bNextIsEscaped = true;
+    else
+      msg.push_back(buf);
   }
 
-  return false;
+  return bGotFullMessage;
 }
 
 std::string CAdapterCommunication::GetError(void) const
@@ -275,7 +240,9 @@ bool CAdapterCommunication::StartBootloader(void)
     return false;
 
   m_controller->AddLog(CEC_LOG_DEBUG, "starting the bootloader");
-  cec_frame output;
+  cec_adapter_message output;
+  output.clear();
+
   output.push_back(MSGSTART);
   PushEscaped(output, MSGCODE_START_BOOTLOADER);
   output.push_back(MSGEND);
@@ -289,7 +256,7 @@ bool CAdapterCommunication::StartBootloader(void)
   return true;
 }
 
-void CAdapterCommunication::PushEscaped(cec_frame &vec, uint8_t byte)
+void CAdapterCommunication::PushEscaped(cec_adapter_message &vec, uint8_t byte)
 {
   if (byte >= MSGESC && byte != MSGSTART)
   {
@@ -311,7 +278,8 @@ bool CAdapterCommunication::SetAckMask(uint16_t iMask)
   strLog.Format("setting ackmask to %2x", iMask);
   m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str());
 
-  cec_frame output;
+  cec_adapter_message output;
+  output.clear();
 
   output.push_back(MSGSTART);
   PushEscaped(output, MSGCODE_SET_ACK_MASK);
@@ -334,7 +302,9 @@ bool CAdapterCommunication::PingAdapter(void)
     return false;
 
   m_controller->AddLog(CEC_LOG_DEBUG, "sending ping");
-  cec_frame output;
+  cec_adapter_message output;
+  output.clear();
+
   output.push_back(MSGSTART);
   PushEscaped(output, MSGCODE_PING);
   output.push_back(MSGEND);
@@ -350,3 +320,51 @@ bool CAdapterCommunication::PingAdapter(void)
   // TODO check for pong
   return true;
 }
+
+bool CAdapterCommunication::IsOpen(void) const
+{
+  return !IsStopped() && m_port->IsOpen();
+}
+
+void CAdapterCommunication::FormatAdapterMessage(const cec_command &command, cec_adapter_message &packet)
+{
+  packet.clear();
+
+  //set ack polarity to high when transmitting to the broadcast address
+  //set ack polarity low when transmitting to any other address
+  packet.push_back(MSGSTART);
+  PushEscaped(packet, MSGCODE_TRANSMIT_ACK_POLARITY);
+  if (command.destination == CECDEVICE_BROADCAST)
+    PushEscaped(packet, CEC_TRUE);
+  else
+    PushEscaped(packet, CEC_FALSE);
+  packet.push_back(MSGEND);
+
+  // add source and destination
+  packet.push_back(MSGSTART);
+  PushEscaped(packet, MSGCODE_TRANSMIT);
+  packet.push_back(((uint8_t)command.initiator << 4) + (uint8_t)command.destination);
+  packet.push_back(MSGEND);
+
+  // add opcode
+  packet.push_back(MSGSTART);
+  PushEscaped(packet, command.parameters.empty() ? (uint8_t)MSGCODE_TRANSMIT_EOM : (uint8_t)MSGCODE_TRANSMIT);
+  packet.push_back((uint8_t) command.opcode);
+  packet.push_back(MSGEND);
+
+  // add parameters
+  for (int8_t iPtr = 0; iPtr < command.parameters.size; iPtr++)
+  {
+    packet.push_back(MSGSTART);
+
+    if (iPtr == command.parameters.size - 1)
+      PushEscaped(packet, MSGCODE_TRANSMIT_EOM);
+    else
+      PushEscaped(packet, MSGCODE_TRANSMIT);
+
+    PushEscaped(packet, command.parameters[iPtr]);
+
+    packet.push_back(MSGEND);
+  }
+}
+