cec: refactored threading/locking - added windows native instead of pthread-win32...
[deb_libcec.git] / src / lib / AdapterCommunication.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the libCEC(R) library.
3 *
4 * libCEC(R) is Copyright (C) 2011 Pulse-Eight Limited. All rights reserved.
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
33#include "AdapterCommunication.h"
34
35#include "CECProcessor.h"
36#include "platform/serialport/serialport.h"
37
38using namespace std;
39using namespace CEC;
40using namespace PLATFORM;
41
42CCECAdapterMessage::CCECAdapterMessage(const cec_command &command)
43{
44 clear();
45
46 //set ack polarity to high when transmitting to the broadcast address
47 //set ack polarity low when transmitting to any other address
48 push_back(MSGSTART);
49 push_escaped(MSGCODE_TRANSMIT_ACK_POLARITY);
50 if (command.destination == CECDEVICE_BROADCAST)
51 push_escaped(CEC_TRUE);
52 else
53 push_escaped(CEC_FALSE);
54 push_back(MSGEND);
55
56 // add source and destination
57 push_back(MSGSTART);
58 push_escaped(command.opcode_set == 0 ? (uint8_t)MSGCODE_TRANSMIT_EOM : (uint8_t)MSGCODE_TRANSMIT);
59 push_back(((uint8_t)command.initiator << 4) + (uint8_t)command.destination);
60 push_back(MSGEND);
61
62 // add opcode
63 if (command.opcode_set == 1)
64 {
65 push_back(MSGSTART);
66 push_escaped(command.parameters.IsEmpty() ? (uint8_t)MSGCODE_TRANSMIT_EOM : (uint8_t)MSGCODE_TRANSMIT);
67 push_back((uint8_t) command.opcode);
68 push_back(MSGEND);
69
70 // add parameters
71 for (int8_t iPtr = 0; iPtr < command.parameters.size; iPtr++)
72 {
73 push_back(MSGSTART);
74
75 if (iPtr == command.parameters.size - 1)
76 push_escaped( MSGCODE_TRANSMIT_EOM);
77 else
78 push_escaped(MSGCODE_TRANSMIT);
79
80 push_escaped(command.parameters[iPtr]);
81
82 push_back(MSGEND);
83 }
84 }
85
86 // set timeout
87 transmit_timeout = command.transmit_timeout;
88}
89
90CCECAdapterMessage &CCECAdapterMessage::operator =(const CCECAdapterMessage &msg)
91{
92 packet = msg.packet;
93 state = msg.state;
94 return *this;
95}
96
97CStdString CCECAdapterMessage::MessageCodeAsString(void) const
98{
99 CStdString strMsg;
100 switch (message())
101 {
102 case MSGCODE_NOTHING:
103 strMsg = "NOTHING";
104 break;
105 case MSGCODE_PING:
106 strMsg = "PING";
107 break;
108 case MSGCODE_TIMEOUT_ERROR:
109 strMsg = "TIMEOUT";
110 break;
111 case MSGCODE_HIGH_ERROR:
112 strMsg = "HIGH_ERROR";
113 break;
114 case MSGCODE_LOW_ERROR:
115 strMsg = "LOW_ERROR";
116 break;
117 case MSGCODE_FRAME_START:
118 strMsg = "FRAME_START";
119 break;
120 case MSGCODE_FRAME_DATA:
121 strMsg = "FRAME_DATA";
122 break;
123 case MSGCODE_RECEIVE_FAILED:
124 strMsg = "RECEIVE_FAILED";
125 break;
126 case MSGCODE_COMMAND_ACCEPTED:
127 strMsg = "COMMAND_ACCEPTED";
128 break;
129 case MSGCODE_COMMAND_REJECTED:
130 strMsg = "COMMAND_REJECTED";
131 break;
132 case MSGCODE_SET_ACK_MASK:
133 strMsg = "SET_ACK_MASK";
134 break;
135 case MSGCODE_TRANSMIT:
136 strMsg = "TRANSMIT";
137 break;
138 case MSGCODE_TRANSMIT_EOM:
139 strMsg = "TRANSMIT_EOM";
140 break;
141 case MSGCODE_TRANSMIT_IDLETIME:
142 strMsg = "TRANSMIT_IDLETIME";
143 break;
144 case MSGCODE_TRANSMIT_ACK_POLARITY:
145 strMsg = "TRANSMIT_ACK_POLARITY";
146 break;
147 case MSGCODE_TRANSMIT_LINE_TIMEOUT:
148 strMsg = "TRANSMIT_LINE_TIMEOUT";
149 break;
150 case MSGCODE_TRANSMIT_SUCCEEDED:
151 strMsg = "TRANSMIT_SUCCEEDED";
152 break;
153 case MSGCODE_TRANSMIT_FAILED_LINE:
154 strMsg = "TRANSMIT_FAILED_LINE";
155 break;
156 case MSGCODE_TRANSMIT_FAILED_ACK:
157 strMsg = "TRANSMIT_FAILED_ACK";
158 break;
159 case MSGCODE_TRANSMIT_FAILED_TIMEOUT_DATA:
160 strMsg = "TRANSMIT_FAILED_TIMEOUT_DATA";
161 break;
162 case MSGCODE_TRANSMIT_FAILED_TIMEOUT_LINE:
163 strMsg = "TRANSMIT_FAILED_TIMEOUT_LINE";
164 break;
165 case MSGCODE_FIRMWARE_VERSION:
166 strMsg = "FIRMWARE_VERSION";
167 break;
168 case MSGCODE_START_BOOTLOADER:
169 strMsg = "START_BOOTLOADER";
170 break;
171 case MSGCODE_FRAME_EOM:
172 strMsg = "FRAME_EOM";
173 break;
174 case MSGCODE_FRAME_ACK:
175 strMsg = "FRAME_ACK";
176 break;
177 }
178
179 return strMsg;
180}
181
182CStdString CCECAdapterMessage::ToString(void) const
183{
184 CStdString strMsg;
185 if (size() == 0)
186 {
187 strMsg = "empty message";
188 }
189 else
190 {
191 strMsg = MessageCodeAsString();
192
193 switch (message())
194 {
195 case MSGCODE_TIMEOUT_ERROR:
196 case MSGCODE_HIGH_ERROR:
197 case MSGCODE_LOW_ERROR:
198 {
199 uint32_t iLine = (size() >= 3) ? (at(1) << 8) | at(2) : 0;
200 uint32_t iTime = (size() >= 7) ? (at(3) << 24) | (at(4) << 16) | (at(5) << 8) | at(6) : 0;
201 strMsg.AppendFormat(" line:%u", iLine);
202 strMsg.AppendFormat(" time:%u", iTime);
203 }
204 break;
205 case MSGCODE_FRAME_START:
206 if (size() >= 2)
207 strMsg.AppendFormat(" initiator:%1x destination:%1x ack:%s %s", initiator(), destination(), ack() ? "high" : "low", eom() ? "eom" : "");
208 break;
209 case MSGCODE_FRAME_DATA:
210 if (size() >= 2)
211 strMsg.AppendFormat(" %02x %s", at(1), eom() ? "eom" : "");
212 break;
213 default:
214 break;
215 }
216 }
217
218 return strMsg;
219}
220
221bool CCECAdapterMessage::is_error(void) const
222{
223 cec_adapter_messagecode code = message();
224 return (code == MSGCODE_HIGH_ERROR ||
225 code == MSGCODE_LOW_ERROR ||
226 code == MSGCODE_RECEIVE_FAILED ||
227 code == MSGCODE_COMMAND_REJECTED ||
228 code == MSGCODE_TRANSMIT_LINE_TIMEOUT ||
229 code == MSGCODE_TRANSMIT_FAILED_LINE ||
230 code == MSGCODE_TRANSMIT_FAILED_ACK ||
231 code == MSGCODE_TRANSMIT_FAILED_TIMEOUT_DATA ||
232 code == MSGCODE_TRANSMIT_FAILED_TIMEOUT_LINE);
233}
234
235void CCECAdapterMessage::push_escaped(uint8_t byte)
236{
237 if (byte >= MSGESC)
238 {
239 push_back(MSGESC);
240 push_back(byte - ESCOFFSET);
241 }
242 else
243 push_back(byte);
244}
245
246CAdapterCommunication::CAdapterCommunication(CCECProcessor *processor) :
247 m_port(NULL),
248 m_processor(processor),
249 m_iLineTimeout(0)
250{
251 m_port = new PLATFORM::CSerialPort;
252}
253
254CAdapterCommunication::~CAdapterCommunication(void)
255{
256 Close();
257
258 if (m_port)
259 {
260 delete m_port;
261 m_port = NULL;
262 }
263}
264
265bool CAdapterCommunication::Open(const char *strPort, uint16_t iBaudRate /* = 38400 */, uint32_t iTimeoutMs /* = 10000 */)
266{
267 uint64_t iNow = GetTimeMs();
268 uint64_t iTimeout = iNow + iTimeoutMs;
269
270 CLockObject lock(m_mutex);
271
272 if (!m_port)
273 {
274 m_processor->AddLog(CEC_LOG_ERROR, "port is NULL");
275 return false;
276 }
277
278 if (IsOpen())
279 {
280 m_processor->AddLog(CEC_LOG_ERROR, "port is already open");
281 return true;
282 }
283
284 CStdString strError;
285 bool bConnected(false);
286 while (!bConnected && iNow < iTimeout)
287 {
288 if ((bConnected = m_port->Open(strPort, iBaudRate)) == false)
289 {
290 strError.Format("error opening serial port '%s': %s", strPort, m_port->GetError().c_str());
291 Sleep(250);
292 iNow = GetTimeMs();
293 }
294 }
295
296 if (!bConnected)
297 {
298 m_processor->AddLog(CEC_LOG_ERROR, strError);
299 return false;
300 }
301
302 m_processor->AddLog(CEC_LOG_DEBUG, "connection opened");
303
304 //clear any input bytes
305 uint8_t buff[1];
306 while (m_port->Read(buff, 1, 5) == 1) {}
307
308 if (CreateThread())
309 {
310 m_startCondition.Wait(m_mutex);
311 m_processor->AddLog(CEC_LOG_DEBUG, "communication thread started");
312 return true;
313 }
314 else
315 {
316 m_processor->AddLog(CEC_LOG_DEBUG, "could not create a communication thread");
317 }
318
319 return false;
320}
321
322void CAdapterCommunication::Close(void)
323{
324 CLockObject lock(m_mutex);
325 m_startCondition.Broadcast();
326 m_rcvCondition.Broadcast();
327 StopThread();
328}
329
330void *CAdapterCommunication::Process(void)
331{
332 {
333 CLockObject lock(m_mutex);
334 m_startCondition.Signal();
335 }
336
337 while (!IsStopped())
338 {
339 ReadFromDevice(50);
340 Sleep(5);
341 WriteNextCommand();
342 }
343
344 CCECAdapterMessage *msg;
345 if (m_outBuffer.Pop(msg))
346 msg->condition.Broadcast();
347
348 return NULL;
349}
350
351bool CAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
352{
353 int32_t iBytesRead;
354 uint8_t buff[1024];
355 if (!m_port)
356 return false;
357
358 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
359 if (iBytesRead < 0 || iBytesRead > 256)
360 {
361 CStdString strError;
362 strError.Format("error reading from serial port: %s", m_port->GetError().c_str());
363 m_processor->AddLog(CEC_LOG_ERROR, strError);
364 return false;
365 }
366 else if (iBytesRead > 0)
367 AddData(buff, (uint8_t) iBytesRead);
368
369 return iBytesRead > 0;
370}
371
372void CAdapterCommunication::AddData(uint8_t *data, uint8_t iLen)
373{
374 CLockObject lock(m_mutex);
375 for (uint8_t iPtr = 0; iPtr < iLen; iPtr++)
376 m_inBuffer.Push(data[iPtr]);
377
378 m_rcvCondition.Signal();
379}
380
381void CAdapterCommunication::WriteNextCommand(void)
382{
383 CCECAdapterMessage *msg;
384 if (m_outBuffer.Pop(msg))
385 SendMessageToAdapter(msg);
386}
387
388void CAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
389{
390 CLockObject lock(msg->mutex);
391 if (m_port->Write(msg->packet.data, msg->size()) != (int32_t) msg->size())
392 {
393 CStdString strError;
394 strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
395 m_processor->AddLog(CEC_LOG_ERROR, strError);
396 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
397 }
398 else
399 {
400 m_processor->AddLog(CEC_LOG_DEBUG, "command sent");
401 msg->state = ADAPTER_MESSAGE_STATE_SENT;
402 }
403 msg->condition.Signal();
404}
405
406bool CAdapterCommunication::Write(CCECAdapterMessage *data)
407{
408 data->state = ADAPTER_MESSAGE_STATE_WAITING;
409 m_outBuffer.Push(data);
410 return true;
411}
412
413bool CAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
414{
415 CLockObject lock(m_mutex);
416
417 msg.clear();
418 uint64_t iNow = GetTimeMs();
419 uint64_t iTarget = iNow + iTimeout;
420 bool bGotFullMessage(false);
421 bool bNextIsEscaped(false);
422 bool bGotStart(false);
423
424 while(!bGotFullMessage && iNow < iTarget)
425 {
426 uint8_t buf = 0;
427 if (!m_inBuffer.Pop(buf))
428 {
429 if (!m_rcvCondition.Wait(m_mutex, (uint32_t) (iTarget - iNow)))
430 return false;
431 }
432
433 if (!bGotStart)
434 {
435 if (buf == MSGSTART)
436 bGotStart = true;
437 continue;
438 }
439 else if (buf == MSGSTART) //we found a msgstart before msgend, this is not right, remove
440 {
441 if (msg.size() > 0)
442 m_processor->AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
443 msg.clear();
444 bGotStart = true;
445 }
446
447 if (buf == MSGEND)
448 {
449 bGotFullMessage = true;
450 }
451 else if (bNextIsEscaped)
452 {
453 msg.push_back(buf + (uint8_t)ESCOFFSET);
454 bNextIsEscaped = false;
455 }
456 else if (buf == MSGESC)
457 bNextIsEscaped = true;
458 else
459 msg.push_back(buf);
460 }
461
462 if (bGotFullMessage)
463 msg.state = ADAPTER_MESSAGE_STATE_RECEIVED;
464
465 return bGotFullMessage;
466}
467
468std::string CAdapterCommunication::GetError(void) const
469{
470 return m_port->GetError();
471}
472
473bool CAdapterCommunication::StartBootloader(void)
474{
475 bool bReturn(false);
476 if (!IsRunning())
477 return bReturn;
478
479 m_processor->AddLog(CEC_LOG_DEBUG, "starting the bootloader");
480 CCECAdapterMessage *output = new CCECAdapterMessage;
481
482 output->push_back(MSGSTART);
483 output->push_escaped(MSGCODE_START_BOOTLOADER);
484 output->push_back(MSGEND);
485
486 CLockObject lock(output->mutex);
487 if (Write(output))
488 output->condition.Wait(output->mutex);
489 bReturn = output->state == ADAPTER_MESSAGE_STATE_SENT;
490 delete output;
491
492 return bReturn;
493}
494
495bool CAdapterCommunication::PingAdapter(void)
496{
497 bool bReturn(false);
498 if (!IsRunning())
499 return bReturn;
500
501 m_processor->AddLog(CEC_LOG_DEBUG, "sending ping");
502 CCECAdapterMessage *output = new CCECAdapterMessage;
503
504 output->push_back(MSGSTART);
505 output->push_escaped(MSGCODE_PING);
506 output->push_back(MSGEND);
507
508 CLockObject lock(output->mutex);
509 if (Write(output))
510 output->condition.Wait(output->mutex);
511 bReturn = output->state == ADAPTER_MESSAGE_STATE_SENT;
512 delete output;
513
514 return bReturn;
515}
516
517bool CAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
518{
519 bool bReturn(m_iLineTimeout != iTimeout);
520
521 if (!bReturn)
522 {
523 CCECAdapterMessage *output = new CCECAdapterMessage;
524
525 output->push_back(MSGSTART);
526 output->push_escaped(MSGCODE_TRANSMIT_IDLETIME);
527 output->push_escaped(iTimeout);
528 output->push_back(MSGEND);
529
530 if ((bReturn = Write(output)) == false)
531 m_processor->AddLog(CEC_LOG_ERROR, "could not set the idletime");
532 delete output;
533 }
534
535 return bReturn;
536}
537
538bool CAdapterCommunication::IsOpen(void)
539{
540 return !IsStopped() && m_port->IsOpen() && IsRunning();
541}