cec: renamed CCommunication -> CAdapterCommunication
[deb_libcec.git] / src / lib / CECParser.cpp
index 547d6268116576529553a8c34d5c2df2e637453e..a86da1a58f3411c7e23193ddb852cd971209e48e 100644 (file)
 #include "util/threads.h"
 #include "util/timeutils.h"
 #include "CECDetect.h"
+#include "AdapterCommunication.h"
 
 using namespace CEC;
 using namespace std;
 
 #define CEC_MAX_RETRY 5
+#define CEC_BUTTON_TIMEOUT 500
 
 /*!
  * ICECDevice implementation
  */
 //@{
 CCECParser::CCECParser(const char *strDeviceName, cec_logical_address iLogicalAddress /* = CECDEVICE_PLAYBACKDEVICE1 */, int iPhysicalAddress /* = CEC_DEFAULT_PHYSICAL_ADDRESS*/) :
-    m_inbuf(NULL),
-    m_iInbufSize(0),
-    m_iInbufUsed(0),
     m_iCurrentButton(CEC_USER_CONTROL_CODE_UNKNOWN),
     m_physicaladdress(iPhysicalAddress),
     m_iLogicalAddress(iLogicalAddress),
-    m_strDeviceName(strDeviceName),
-    m_bRunning(false)
+    m_strDeviceName(strDeviceName)
 {
-  m_serialport = new CSerialPort;
+  m_communication = new CAdapterCommunication(this);
 }
 
 CCECParser::~CCECParser(void)
 {
-  m_bRunning = false;
-  pthread_join(m_thread, NULL);
-  m_serialport->Close();
-  delete m_serialport;
+  Close();
+  m_communication->Close();
+  delete m_communication;
 }
 
 bool CCECParser::Open(const char *strPort, int iTimeoutMs /* = 10000 */)
 {
-  bool bReturn(false);
+  if (!m_communication)
+    return false;
 
-  if (!(bReturn = m_serialport->Open(strPort, 38400)))
+  if (m_communication->IsOpen())
   {
-    CStdString strError;
-    strError.Format("error opening serial port '%s': %s", strPort, m_serialport->GetError().c_str());
-    AddLog(CEC_LOG_ERROR, strError);
-    return bReturn;
+    AddLog(CEC_LOG_ERROR, "connection already open");
+    return false;
   }
 
-  //clear any input bytes
-  uint8_t buff[1024];
-  m_serialport->Read(buff, sizeof(buff), CEC_SETTLE_DOWN_TIME);
-
-  if (bReturn)
-    bReturn = SetLogicalAddress(m_iLogicalAddress);
-
-  if (!bReturn)
+  if (!m_communication->Open(strPort, 38400, iTimeoutMs))
   {
-    CStdString strError;
-    strError.Format("error opening serial port '%s': %s", strPort, m_serialport->GetError().c_str());
-    AddLog(CEC_LOG_ERROR, strError);
-    return bReturn;
+    AddLog(CEC_LOG_ERROR, "could not open a connection");
+    return false;
   }
 
-  if (bReturn)
+  if (!SetLogicalAddress(m_iLogicalAddress))
   {
-    m_bRunning = true;
-    if (pthread_create(&m_thread, NULL, (void *(*) (void *))&CCECParser::ThreadHandler, (void *)this) == 0)
-      pthread_detach(m_thread);
-    else
-      m_bRunning = false;
+    AddLog(CEC_LOG_ERROR, "could not set the logical address");
+    return false;
   }
 
-  return bReturn;
+  if (CreateThread())
+    return true;
+  else
+    AddLog(CEC_LOG_ERROR, "could not create a processor thread");
+
+  return false;
 }
 
-void *CCECParser::ThreadHandler(CCECParser *parser)
+void CCECParser::Close(void)
 {
-  if (parser)
-    parser->Process();
-  return 0;
+  StopThread();
 }
 
-bool CCECParser::Process(void)
+void *CCECParser::Process(void)
 {
+  AddLog(CEC_LOG_DEBUG, "processor thread started");
+
   int64_t now = GetTimeMs();
-  while (m_bRunning)
+  while (!m_bStop)
   {
+    bool bParseFrame(false);
     {
-      CLockObject lock(&m_mutex, 1000);
-      if (lock.IsLocked())
-      {
-        if (!ReadFromDevice(100))
-        {
-          m_bRunning = false;
-          return false;
-        }
-      }
+      CLockObject lock(&m_mutex);
+      cec_frame msg;
+      if (!m_bStop && m_communication->IsOpen() && m_communication->Read(msg, CEC_BUTTON_TIMEOUT))
+        bParseFrame = ParseMessage(msg);
     }
 
-    //AddLog(CEC_LOG_DEBUG, "processing messages");
-    ProcessMessages();
+    if (bParseFrame)
+      ParseCurrentFrame();
+
     now = GetTimeMs();
     CheckKeypressTimeout(now);
     CCondition::Sleep(50);
   }
 
-  AddLog(CEC_LOG_DEBUG, "reader thread terminated");
-  m_bRunning = false;
-  return true;
+  AddLog(CEC_LOG_DEBUG, "processor thread terminated");
+  return NULL;
 }
 
 bool CCECParser::Ping(void)
 {
+  if (!IsRunning())
+    return false;
+
   AddLog(CEC_LOG_DEBUG, "sending ping");
   cec_frame output;
   output.push_back(MSGSTART);
   PushEscaped(output, MSGCODE_PING);
   output.push_back(MSGEND);
 
-  if (!TransmitFormatted(output, false, (int64_t) 5000))
+  if (!TransmitFormatted(output, false))
   {
     AddLog(CEC_LOG_ERROR, "could not send ping command");
     return false;
@@ -170,13 +158,16 @@ bool CCECParser::Ping(void)
 
 bool CCECParser::StartBootloader(void)
 {
+  if (!IsRunning())
+    return false;
+
   AddLog(CEC_LOG_DEBUG, "starting the bootloader");
   cec_frame output;
   output.push_back(MSGSTART);
   PushEscaped(output, MSGCODE_START_BOOTLOADER);
   output.push_back(MSGEND);
 
-  if (!TransmitFormatted(output, false, (int64_t) 5000))
+  if (!TransmitFormatted(output, false))
   {
     AddLog(CEC_LOG_ERROR, "could not start the bootloader");
     return false;
@@ -193,17 +184,14 @@ uint8_t CCECParser::GetSourceDestination(cec_logical_address destination /* = CE
 
 bool CCECParser::PowerOffDevices(cec_logical_address address /* = CECDEVICE_BROADCAST */)
 {
-  CStdString strLog;
-  strLog.Format("powering off devices with logical address %d", (int8_t)address);
-  AddLog(CEC_LOG_DEBUG, strLog.c_str());
-  cec_frame frame;
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back(CEC_OPCODE_STANDBY);
-  return Transmit(frame);
+  return StandbyDevices(address);
 }
 
-bool CCECParser::PowerOnDevices(cec_logical_address address /* = CECDEVICE_BROADCAST */)
+bool CCECParser::PowerOnDevices(cec_logical_address address /* = CECDEVICE_TV */)
 {
+  if (!IsRunning())
+    return false;
+
   CStdString strLog;
   strLog.Format("powering on devices with logical address %d", (int8_t)address);
   AddLog(CEC_LOG_DEBUG, strLog.c_str());
@@ -215,6 +203,9 @@ bool CCECParser::PowerOnDevices(cec_logical_address address /* = CECDEVICE_BROAD
 
 bool CCECParser::StandbyDevices(cec_logical_address address /* = CECDEVICE_BROADCAST */)
 {
+  if (!IsRunning())
+    return false;
+
   CStdString strLog;
   strLog.Format("putting all devices with logical address %d in standby mode", (int8_t)address);
   AddLog(CEC_LOG_DEBUG, strLog.c_str());
@@ -226,6 +217,9 @@ bool CCECParser::StandbyDevices(cec_logical_address address /* = CECDEVICE_BROAD
 
 bool CCECParser::SetActiveView(void)
 {
+  if (!IsRunning())
+    return false;
+
   AddLog(CEC_LOG_DEBUG, "setting active view");
   cec_frame frame;
   frame.push_back(GetSourceDestination(CECDEVICE_BROADCAST));
@@ -237,6 +231,9 @@ bool CCECParser::SetActiveView(void)
 
 bool CCECParser::SetInactiveView(void)
 {
+  if (!IsRunning())
+    return false;
+
   AddLog(CEC_LOG_DEBUG, "setting inactive view");
   cec_frame frame;
   frame.push_back(GetSourceDestination(CECDEVICE_BROADCAST));
@@ -253,12 +250,12 @@ bool CCECParser::GetNextLogMessage(cec_log_message *message)
 
 bool CCECParser::GetNextKeypress(cec_keypress *key)
 {
-  return m_keyBuffer.Pop(*key);
+  return IsRunning() ? m_keyBuffer.Pop(*key) : false;
 }
 
 bool CCECParser::GetNextCommand(cec_command *command)
 {
-  return m_commandBuffer.Pop(*command);
+  return IsRunning() ? m_commandBuffer.Pop(*command) : false;
 }
 //@}
 
@@ -358,23 +355,13 @@ void CCECParser::BroadcastActiveSource(void)
   Transmit(frame);
 }
 
-bool CCECParser::TransmitFormatted(const cec_frame &data, bool bWaitForAck /* = true */, int64_t iTimeout /* = 2000 */)
+bool CCECParser::TransmitFormatted(const cec_frame &data, bool bWaitForAck /* = true */)
 {
-  CLockObject lock(&m_mutex, iTimeout);
-  if (!lock.IsLocked())
-  {
-    AddLog(CEC_LOG_ERROR, "could not get a write lock");
-    return false;
-  }
-
-  if (m_serialport->Write(data) != data.size())
+  CLockObject lock(&m_mutex);
+  if (!m_communication || !m_communication->Write(data))
   {
-    CStdString strError;
-    strError.Format("error writing to serial port: %s", m_serialport->GetError().c_str());
-    AddLog(CEC_LOG_ERROR, strError);
     return false;
   }
-  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 */);
   if (bWaitForAck && !WaitForAck())
@@ -386,7 +373,7 @@ bool CCECParser::TransmitFormatted(const cec_frame &data, bool bWaitForAck /* =
   return true;
 }
 
-bool CCECParser::Transmit(const cec_frame &data, bool bWaitForAck /* = true */, int64_t iTimeout /* = 5000 */)
+bool CCECParser::Transmit(const cec_frame &data, bool bWaitForAck /* = true */)
 {
   CStdString txStr = "transmit ";
   for (unsigned int i = 0; i < data.size(); i++)
@@ -427,27 +414,21 @@ bool CCECParser::Transmit(const cec_frame &data, bool bWaitForAck /* = true */,
     output.push_back(MSGEND);
   }
 
-  return TransmitFormatted(output, bWaitForAck, iTimeout);
+  return TransmitFormatted(output, bWaitForAck);
 }
 
-bool CCECParser::WaitForAck(int64_t iTimeout /* = 1000 */)
+bool CCECParser::WaitForAck(int iTimeout /* = 1000 */)
 {
   bool bGotAck(false);
   bool bError(false);
 
   int64_t iNow = GetTimeMs();
-  int64_t iTargetTime = iNow + iTimeout;
+  int64_t iTargetTime = iNow + (int64_t) iTimeout;
 
   while (!bGotAck && !bError && (iTimeout <= 0 || iNow < iTargetTime))
   {
-    if (!ReadFromDevice((int) iTimeout))
-    {
-      AddLog(CEC_LOG_ERROR, "failed to read from device");
-      return false;
-    }
-
     cec_frame msg;
-    while (!bGotAck && !bError && GetMessage(msg, false))
+    while (!bGotAck && !bError && m_communication->Read(msg, iTimeout))
     {
       uint8_t iCode = msg[0] & ~(MSGCODE_FRAME_EOM | MSGCODE_FRAME_ACK);
 
@@ -497,123 +478,12 @@ bool CCECParser::WaitForAck(int64_t iTimeout /* = 1000 */)
   return bGotAck && !bError;
 }
 
-bool CCECParser::ReadFromDevice(int iTimeout)
+bool CCECParser::ParseMessage(cec_frame &msg)
 {
-  uint8_t buff[1024];
-  int iBytesRead = m_serialport->Read(buff, sizeof(buff), iTimeout);
-  if (iBytesRead < 0)
-  {
-    CStdString strError;
-    strError.Format("error reading from serial port: %s", m_serialport->GetError().c_str());
-    AddLog(CEC_LOG_ERROR, strError);
-    return false;
-  }
-  else if (iBytesRead > 0)
-    AddData(buff, iBytesRead);
-
-  return true;
-}
-
-void CCECParser::ProcessMessages(void)
-{
-  cec_frame msg;
-  while (GetMessage(msg))
-    ParseMessage(msg);
-}
-
-bool CCECParser::GetMessage(cec_frame &msg, bool bFromBuffer /* = true */)
-{
-  if (bFromBuffer && m_frameBuffer.Pop(msg))
-    return true;
-
-  if (m_iInbufUsed < 1)
-    return false;
-
-  //search for first start of message
-  int startpos = -1;
-  for (int i = 0; i < m_iInbufUsed; i++)
-  {
-    if (m_inbuf[i] == MSGSTART)
-    {
-      startpos = i;
-      break;
-    }
-  }
-
-  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)
-    {
-      endpos = i;
-      break;
-    }
-    else if (m_inbuf[i] == MSGSTART)
-    {
-      startpos = i;
-      break;
-    }
-  }
-
-  if (startpos > 0) //we found a msgstart before msgend, this is not right, remove
-  {
-    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 (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]);
-      }
-    }
-
-    if (endpos + 1 < m_iInbufUsed)
-      memmove(m_inbuf, m_inbuf + endpos + 1, m_iInbufUsed - endpos - 1);
-
-    m_iInbufUsed -= endpos + 1;
-
-    return true;
-  }
-
-  return false;
-}
+  bool bReturn(false);
 
-void CCECParser::ParseMessage(cec_frame &msg)
-{
   if (msg.empty())
-    return;
+    return bReturn;
 
   CStdString logStr;
   uint8_t iCode = msg[0] & ~(MSGCODE_FRAME_EOM | MSGCODE_FRAME_ACK);
@@ -670,11 +540,13 @@ void CCECParser::ParseMessage(cec_frame &msg)
       AddLog(CEC_LOG_DEBUG, logStr.c_str());
     }
     if (bEom)
-      ParseCurrentFrame();
+      bReturn = true;
     break;
   default:
     break;
   }
+
+  return bReturn;
 }
 
 void CCECParser::ParseCurrentFrame(void)
@@ -776,18 +648,6 @@ void CCECParser::ParseCurrentFrame(void)
   }
 }
 
-void CCECParser::AddData(uint8_t *data, int iLen)
-{
-  if (iLen + m_iInbufUsed > m_iInbufSize)
-  {
-    m_iInbufSize = iLen + m_iInbufUsed;
-    m_inbuf = (uint8_t*)realloc(m_inbuf, m_iInbufSize);
-  }
-
-  memcpy(m_inbuf + m_iInbufUsed, data, iLen);
-  m_iInbufUsed += iLen;
-}
-
 void CCECParser::PushEscaped(cec_frame &vec, uint8_t byte)
 {
   if (byte >= MSGESC && byte != MSGSTART)
@@ -803,7 +663,7 @@ void CCECParser::PushEscaped(cec_frame &vec, uint8_t byte)
 
 void CCECParser::CheckKeypressTimeout(int64_t now)
 {
-  if (m_iCurrentButton != CEC_USER_CONTROL_CODE_UNKNOWN && now - m_buttontime > 500)
+  if (m_iCurrentButton != CEC_USER_CONTROL_CODE_UNKNOWN && now - m_buttontime > CEC_BUTTON_TIMEOUT)
   {
     AddKey();
     m_iCurrentButton = CEC_USER_CONTROL_CODE_UNKNOWN;
@@ -834,10 +694,9 @@ bool CCECParser::SetAckMask(uint16_t iMask)
   PushEscaped(output, (uint8_t)iMask);
   output.push_back(MSGEND);
 
-  if (m_serialport->Write(output) == -1)
+  if (!m_communication->Write(output))
   {
-    strLog.Format("error writing to serial port: %s", m_serialport->GetError().c_str());
-    AddLog(CEC_LOG_ERROR, strLog);
+    AddLog(CEC_LOG_ERROR, "could not set the ackmask");
     return false;
   }