cec: clean up lib/platform
[deb_libcec.git] / src / lib / adapter / AdapterCommunication.cpp
CommitLineData
a8f0bd18
LOK
1/*
2 * This file is part of the libCEC(R) library.
3 *
b492c10e 4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
a8f0bd18
LOK
5 * libCEC(R) is an original work, containing original code.
6 *
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
8 *
9 * This program is dual-licensed; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 *
23 *
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
26 *
27 * For more information contact:
28 * Pulse-Eight Licensing <license@pulse-eight.com>
29 * http://www.pulse-eight.com/
30 * http://www.pulse-eight.net/
31 */
32
828682d3 33#include "AdapterCommunication.h"
2abe74eb 34
ef7696f5 35#include "AdapterMessage.h"
b5f787b9 36#include "../CECProcessor.h"
ba65909d
LOK
37#include "../platform/sockets/serialport.h"
38#include "../platform/util/timeutils.h"
5477a250 39#include "../LibCEC.h"
a8f0bd18
LOK
40
41using namespace std;
42using namespace CEC;
f00ff009 43using namespace PLATFORM;
a8f0bd18 44
99666519 45CAdapterCommunication::CAdapterCommunication(CCECProcessor *processor, const char *strPort, uint16_t iBaudRate /* = 38400 */) :
12027dbe 46 m_port(NULL),
a171d2fd 47 m_processor(processor),
1fc16cfd
LOK
48 m_iLineTimeout(0),
49 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN)
a8f0bd18 50{
99666519 51 m_port = new PLATFORM::CSerialPort(strPort, iBaudRate);
a8f0bd18
LOK
52}
53
828682d3 54CAdapterCommunication::~CAdapterCommunication(void)
a8f0bd18 55{
12027dbe
LOK
56 Close();
57
58 if (m_port)
59 {
60 delete m_port;
61 m_port = NULL;
62 }
a8f0bd18
LOK
63}
64
99666519 65bool CAdapterCommunication::Open(uint32_t iTimeoutMs /* = 10000 */)
a8f0bd18 66{
7b494bea
LOK
67 uint64_t iNow = GetTimeMs();
68 uint64_t iTimeout = iNow + iTimeoutMs;
69
f00ff009 70 CLockObject lock(m_mutex);
7b494bea 71
13fd6a66
LOK
72 if (!m_port)
73 {
5477a250 74 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
a8f0bd18 75 return false;
13fd6a66
LOK
76 }
77
78 if (IsOpen())
79 {
5477a250 80 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
7b494bea 81 return true;
13fd6a66 82 }
a8f0bd18 83
7b494bea
LOK
84 CStdString strError;
85 bool bConnected(false);
86 while (!bConnected && iNow < iTimeout)
87 {
99666519 88 if ((bConnected = m_port->Open(iTimeout)) == false)
7b494bea 89 {
99666519 90 strError.Format("error opening serial port '%s': %s", m_port->GetName().c_str(), m_port->GetError().c_str());
7b494bea
LOK
91 Sleep(250);
92 iNow = GetTimeMs();
93 }
94 }
95
96 if (!bConnected)
a8f0bd18 97 {
5477a250 98 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
a8f0bd18
LOK
99 return false;
100 }
101
2c780401 102 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
a8f0bd18
LOK
103
104 //clear any input bytes
2c780401
LOK
105 uint8_t buff[1024];
106 while (m_port->Read(buff, 1024, 100) > 0)
107 {
108 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
109 Sleep(250);
110 }
a8f0bd18 111
828682d3 112 if (CreateThread())
a8f0bd18 113 {
5477a250 114 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
a8f0bd18
LOK
115 return true;
116 }
117 else
118 {
5477a250 119 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
a8f0bd18
LOK
120 }
121
122 return false;
123}
124
828682d3 125void CAdapterCommunication::Close(void)
a8f0bd18 126{
f00ff009 127 CLockObject lock(m_mutex);
d5bffd3c 128 m_rcvCondition.Broadcast();
b9eea66d 129 StopThread();
a8f0bd18
LOK
130}
131
828682d3 132void *CAdapterCommunication::Process(void)
a8f0bd18 133{
13fd6a66 134 while (!IsStopped())
a8f0bd18 135 {
9e1cfa5c 136 ReadFromDevice(50);
c02980af 137 Sleep(5);
3c53ac93 138 WriteNextCommand();
a8f0bd18
LOK
139 }
140
ef7696f5 141 CCECAdapterMessage *msg(NULL);
a0878ee3
LOK
142 if (m_outBuffer.Pop(msg))
143 msg->condition.Broadcast();
144
a8f0bd18
LOK
145 return NULL;
146}
147
28352a04 148bool CAdapterCommunication::Write(CCECAdapterMessage *data)
3c53ac93 149{
5dcf9f25
LOK
150 bool bReturn(false);
151
152 CLockObject lock(data->mutex);
153 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
3c53ac93 154 m_outBuffer.Push(data);
5dcf9f25
LOK
155 data->condition.Wait(data->mutex);
156
157 if (data->state != ADAPTER_MESSAGE_STATE_SENT)
158 {
5477a250 159 CLibCEC::AddLog(CEC_LOG_ERROR, "command was not sent");
5dcf9f25 160 }
b2f0b1ab 161 else if (data->expectControllerAck)
5dcf9f25 162 {
b2f0b1ab 163 bReturn = WaitForAck(*data);
4060d525
LOK
164 if (bReturn)
165 {
166 if (data->isTransmission)
167 data->state = ADAPTER_MESSAGE_STATE_SENT_ACKED;
168 }
169 else
170 {
171 data->state = ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
5477a250 172 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
4060d525 173 }
5dcf9f25
LOK
174 }
175 else
176 {
4060d525 177 bReturn = true;
5dcf9f25
LOK
178 }
179
180 return bReturn;
a8f0bd18
LOK
181}
182
220537f2 183bool CAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
a8f0bd18 184{
f00ff009 185 CLockObject lock(m_mutex);
a8f0bd18 186
ef7696f5 187 msg.Clear();
50aa01e6
LOK
188 uint64_t iNow = GetTimeMs();
189 uint64_t iTarget = iNow + iTimeout;
190 bool bGotFullMessage(false);
191 bool bNextIsEscaped(false);
192 bool bGotStart(false);
a8f0bd18 193
50aa01e6 194 while(!bGotFullMessage && iNow < iTarget)
a8f0bd18 195 {
50aa01e6
LOK
196 uint8_t buf = 0;
197 if (!m_inBuffer.Pop(buf))
a8f0bd18 198 {
f00ff009 199 if (!m_rcvCondition.Wait(m_mutex, (uint32_t) (iTarget - iNow)))
50aa01e6 200 return false;
a8f0bd18 201 }
a8f0bd18 202
50aa01e6 203 if (!bGotStart)
a8f0bd18 204 {
50aa01e6
LOK
205 if (buf == MSGSTART)
206 bGotStart = true;
207 continue;
a8f0bd18 208 }
50aa01e6 209 else if (buf == MSGSTART) //we found a msgstart before msgend, this is not right, remove
a8f0bd18 210 {
ef7696f5 211 if (msg.Size() > 0)
5477a250 212 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
ef7696f5 213 msg.Clear();
50aa01e6 214 bGotStart = true;
a8f0bd18 215 }
a8f0bd18 216
50aa01e6 217 if (buf == MSGEND)
a8f0bd18 218 {
50aa01e6 219 bGotFullMessage = true;
a8f0bd18 220 }
50aa01e6
LOK
221 else if (bNextIsEscaped)
222 {
ef7696f5 223 msg.PushBack(buf + (uint8_t)ESCOFFSET);
50aa01e6
LOK
224 bNextIsEscaped = false;
225 }
226 else if (buf == MSGESC)
227 bNextIsEscaped = true;
228 else
ef7696f5 229 msg.PushBack(buf);
a8f0bd18
LOK
230 }
231
0e31a62c 232 if (bGotFullMessage)
5dcf9f25 233 msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
0e31a62c 234
50aa01e6 235 return bGotFullMessage;
a8f0bd18
LOK
236}
237
ba65909d 238CStdString CAdapterCommunication::GetError(void) const
a8f0bd18 239{
ba65909d
LOK
240 CStdString strError;
241 strError = m_port->GetError();
242 return strError;
a8f0bd18 243}
2abe74eb
LOK
244
245bool CAdapterCommunication::StartBootloader(void)
246{
28352a04 247 bool bReturn(false);
2abe74eb 248 if (!IsRunning())
28352a04 249 return bReturn;
2abe74eb 250
5477a250 251 CLibCEC::AddLog(CEC_LOG_DEBUG, "starting the bootloader");
28352a04 252 CCECAdapterMessage *output = new CCECAdapterMessage;
25701fa6 253
ef7696f5
LOK
254 output->PushBack(MSGSTART);
255 output->PushEscaped(MSGCODE_START_BOOTLOADER);
256 output->PushBack(MSGEND);
5dcf9f25 257 output->isTransmission = false;
71c4a2f5 258 output->expectControllerAck = false;
2abe74eb 259
5dcf9f25 260 if ((bReturn = Write(output)) == false)
5477a250 261 CLibCEC::AddLog(CEC_LOG_ERROR, "could not start the bootloader");
28352a04
LOK
262 delete output;
263
264 return bReturn;
2abe74eb
LOK
265}
266
2abe74eb
LOK
267bool CAdapterCommunication::PingAdapter(void)
268{
28352a04 269 bool bReturn(false);
2abe74eb 270 if (!IsRunning())
28352a04 271 return bReturn;
2abe74eb 272
5477a250 273 CLibCEC::AddLog(CEC_LOG_DEBUG, "sending ping");
28352a04 274 CCECAdapterMessage *output = new CCECAdapterMessage;
25701fa6 275
ef7696f5
LOK
276 output->PushBack(MSGSTART);
277 output->PushEscaped(MSGCODE_PING);
278 output->PushBack(MSGEND);
5dcf9f25 279 output->isTransmission = false;
2abe74eb 280
5dcf9f25 281 if ((bReturn = Write(output)) == false)
5477a250 282 CLibCEC::AddLog(CEC_LOG_ERROR, "could not ping the adapter");
28352a04
LOK
283 delete output;
284
285 return bReturn;
2abe74eb 286}
13fd6a66 287
1fc16cfd
LOK
288uint16_t CAdapterCommunication::GetFirmwareVersion(void)
289{
290 uint16_t iReturn(m_iFirmwareVersion);
291 if (!IsRunning())
292 return iReturn;
293
294 if (iReturn == CEC_FW_VERSION_UNKNOWN)
295 {
5477a250 296 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
1fc16cfd
LOK
297 CCECAdapterMessage *output = new CCECAdapterMessage;
298
299 output->PushBack(MSGSTART);
300 output->PushEscaped(MSGCODE_FIRMWARE_VERSION);
301 output->PushBack(MSGEND);
302 output->isTransmission = false;
303 output->expectControllerAck = false;
304
305 SendMessageToAdapter(output);
306 delete output;
307
308 CCECAdapterMessage input;
309 if (!Read(input, CEC_DEFAULT_TRANSMIT_WAIT) || input.Message() != MSGCODE_FIRMWARE_VERSION || input.Size() != 3)
2c780401 310 CLibCEC::AddLog(CEC_LOG_ERROR, "no or invalid firmware version (size = %d, message = %d)", input.Size(), input.Message());
1fc16cfd
LOK
311 else
312 {
313 m_iFirmwareVersion = (input[1] << 8 | input[2]);
314 iReturn = m_iFirmwareVersion;
315 }
316 }
317
318 return iReturn;
319}
320
a171d2fd
LOK
321bool CAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
322{
323 bool bReturn(m_iLineTimeout != iTimeout);
324
325 if (!bReturn)
326 {
327 CCECAdapterMessage *output = new CCECAdapterMessage;
328
ef7696f5
LOK
329 output->PushBack(MSGSTART);
330 output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
331 output->PushEscaped(iTimeout);
332 output->PushBack(MSGEND);
5dcf9f25 333 output->isTransmission = false;
a171d2fd
LOK
334
335 if ((bReturn = Write(output)) == false)
5477a250 336 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
a171d2fd
LOK
337 delete output;
338 }
339
340 return bReturn;
341}
342
5dcf9f25
LOK
343bool CAdapterCommunication::SetAckMask(uint16_t iMask)
344{
345 bool bReturn(false);
346 CStdString strLog;
347 strLog.Format("setting ackmask to %2x", iMask);
5477a250 348 CLibCEC::AddLog(CEC_LOG_DEBUG, strLog.c_str());
5dcf9f25
LOK
349
350 CCECAdapterMessage *output = new CCECAdapterMessage;
351
352 output->PushBack(MSGSTART);
353 output->PushEscaped(MSGCODE_SET_ACK_MASK);
354 output->PushEscaped(iMask >> 8);
355 output->PushEscaped((uint8_t)iMask);
356 output->PushBack(MSGEND);
357 output->isTransmission = false;
358
359 if ((bReturn = Write(output)) == false)
5477a250 360 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the ackmask");
5dcf9f25
LOK
361 delete output;
362
363 return bReturn;
364}
365
f00ff009 366bool CAdapterCommunication::IsOpen(void)
13fd6a66 367{
b9eea66d 368 return !IsStopped() && m_port->IsOpen() && IsRunning();
13fd6a66 369}
ef7696f5 370
b2f0b1ab 371bool CAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
6729ac71
LOK
372{
373 bool bError(false);
374 bool bTransmitSucceeded(false);
b2f0b1ab 375 uint8_t iPacketsLeft(message.Size() / 4);
6729ac71
LOK
376
377 int64_t iNow = GetTimeMs();
b2f0b1ab 378 int64_t iTargetTime = iNow + message.transmit_timeout;
6729ac71 379
b2f0b1ab 380 while (!bTransmitSucceeded && !bError && (message.transmit_timeout == 0 || iNow < iTargetTime))
6729ac71
LOK
381 {
382 CCECAdapterMessage msg;
e2800c15 383 int32_t iWait = (int32_t)(iTargetTime - iNow);
b2f0b1ab 384 if (iWait <= 5 || message.transmit_timeout <= 5)
e2800c15 385 iWait = CEC_DEFAULT_TRANSMIT_WAIT;
6729ac71 386
e2800c15 387 if (!Read(msg, iWait))
6729ac71
LOK
388 {
389 iNow = GetTimeMs();
390 continue;
391 }
392
393 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
394 {
395 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
396 iNow = GetTimeMs();
397 continue;
398 }
399
400 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
401 m_processor->HandleReceiveFailed())
402 {
403 iNow = GetTimeMs();
404 continue;
405 }
406
407 bError = msg.IsError();
408 if (bError)
409 {
b2f0b1ab 410 message.reply = msg.Message();
5477a250 411 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
412 }
413 else
414 {
415 switch(msg.Message())
416 {
417 case MSGCODE_COMMAND_ACCEPTED:
5477a250 418 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
419 if (iPacketsLeft > 0)
420 iPacketsLeft--;
b2f0b1ab 421 if (!message.isTransmission && iPacketsLeft == 0)
5dcf9f25 422 bTransmitSucceeded = true;
6729ac71
LOK
423 break;
424 case MSGCODE_TRANSMIT_SUCCEEDED:
5477a250 425 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
426 bTransmitSucceeded = (iPacketsLeft == 0);
427 bError = !bTransmitSucceeded;
b2f0b1ab 428 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
6729ac71
LOK
429 break;
430 default:
431 // ignore other data while waiting
432 break;
433 }
434
435 iNow = GetTimeMs();
436 }
437 }
438
439 return bTransmitSucceeded && !bError;
440}
441
99666519 442void CAdapterCommunication::AddData(uint8_t *data, size_t iLen)
ef7696f5
LOK
443{
444 CLockObject lock(m_mutex);
99666519 445 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
ef7696f5
LOK
446 m_inBuffer.Push(data[iPtr]);
447
448 m_rcvCondition.Signal();
449}
450
451bool CAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
452{
99666519
LOK
453 ssize_t iBytesRead;
454 uint8_t buff[256];
ef7696f5
LOK
455 if (!m_port)
456 return false;
457
1fc16cfd 458 CLockObject lock(m_mutex);
ef7696f5
LOK
459 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
460 if (iBytesRead < 0 || iBytesRead > 256)
461 {
99666519 462 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
ef7696f5
LOK
463 return false;
464 }
465 else if (iBytesRead > 0)
99666519
LOK
466 {
467 AddData(buff, iBytesRead);
468 }
ef7696f5
LOK
469
470 return iBytesRead > 0;
471}
472
473void CAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
474{
1fc16cfd 475 CLockObject adapterLock(m_mutex);
ef7696f5 476 CLockObject lock(msg->mutex);
99666519 477 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
ef7696f5
LOK
478 {
479 CStdString strError;
480 strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
5477a250 481 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
ef7696f5
LOK
482 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
483 }
484 else
485 {
5477a250 486 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
ef7696f5
LOK
487 msg->state = ADAPTER_MESSAGE_STATE_SENT;
488 }
489 msg->condition.Signal();
490}
491
492void CAdapterCommunication::WriteNextCommand(void)
493{
494 CCECAdapterMessage *msg(NULL);
495 if (m_outBuffer.Pop(msg))
496 SendMessageToAdapter(msg);
497}