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