15b6851ae5abcf843d00d516626095ad85ae7ee5
[deb_libcec.git] / src / lib / adapter / 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 "AdapterMessage.h"
36 #include "CECProcessor.h"
37 #include "platform/serialport/serialport.h"
38
39 using namespace std;
40 using namespace CEC;
41 using namespace PLATFORM;
42
43 CAdapterCommunication::CAdapterCommunication(CCECProcessor *processor) :
44 m_port(NULL),
45 m_processor(processor),
46 m_iLineTimeout(0),
47 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN)
48 {
49 m_port = new PLATFORM::CSerialPort;
50 }
51
52 CAdapterCommunication::~CAdapterCommunication(void)
53 {
54 Close();
55
56 if (m_port)
57 {
58 delete m_port;
59 m_port = NULL;
60 }
61 }
62
63 bool CAdapterCommunication::Open(const char *strPort, uint16_t iBaudRate /* = 38400 */, uint32_t iTimeoutMs /* = 10000 */)
64 {
65 uint64_t iNow = GetTimeMs();
66 uint64_t iTimeout = iNow + iTimeoutMs;
67
68 CLockObject lock(m_mutex);
69
70 if (!m_port)
71 {
72 m_processor->AddLog(CEC_LOG_ERROR, "port is NULL");
73 return false;
74 }
75
76 if (IsOpen())
77 {
78 m_processor->AddLog(CEC_LOG_ERROR, "port is already open");
79 return true;
80 }
81
82 CStdString strError;
83 bool bConnected(false);
84 while (!bConnected && iNow < iTimeout)
85 {
86 if ((bConnected = m_port->Open(strPort, iBaudRate)) == false)
87 {
88 strError.Format("error opening serial port '%s': %s", strPort, m_port->GetError().c_str());
89 Sleep(250);
90 iNow = GetTimeMs();
91 }
92 }
93
94 if (!bConnected)
95 {
96 m_processor->AddLog(CEC_LOG_ERROR, strError);
97 return false;
98 }
99
100 m_processor->AddLog(CEC_LOG_DEBUG, "connection opened");
101
102 //clear any input bytes
103 uint8_t buff[1];
104 while (m_port->Read(buff, 1, 5) == 1) {}
105
106 if (CreateThread())
107 {
108 m_processor->AddLog(CEC_LOG_DEBUG, "communication thread started");
109 return true;
110 }
111 else
112 {
113 m_processor->AddLog(CEC_LOG_ERROR, "could not create a communication thread");
114 }
115
116 return false;
117 }
118
119 void CAdapterCommunication::Close(void)
120 {
121 CLockObject lock(m_mutex);
122 m_rcvCondition.Broadcast();
123 StopThread();
124 }
125
126 void *CAdapterCommunication::Process(void)
127 {
128 while (!IsStopped())
129 {
130 ReadFromDevice(50);
131 Sleep(5);
132 WriteNextCommand();
133 }
134
135 CCECAdapterMessage *msg(NULL);
136 if (m_outBuffer.Pop(msg))
137 msg->condition.Broadcast();
138
139 return NULL;
140 }
141
142 bool CAdapterCommunication::Write(CCECAdapterMessage *data)
143 {
144 bool bReturn(false);
145
146 CLockObject lock(data->mutex);
147 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
148 m_outBuffer.Push(data);
149 data->condition.Wait(data->mutex);
150
151 if (data->state != ADAPTER_MESSAGE_STATE_SENT)
152 {
153 m_processor->AddLog(CEC_LOG_ERROR, "command was not sent");
154 }
155
156 if (data->expectControllerAck)
157 {
158 bReturn = WaitForTransmitSucceeded(data);
159 if (bReturn)
160 {
161 if (data->isTransmission)
162 data->state = ADAPTER_MESSAGE_STATE_SENT_ACKED;
163 }
164 else
165 {
166 data->state = ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
167 m_processor->AddLog(CEC_LOG_DEBUG, "did not receive ack");
168 }
169 }
170 else
171 {
172 bReturn = true;
173 }
174
175 return bReturn;
176 }
177
178 bool CAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
179 {
180 CLockObject lock(m_mutex);
181
182 msg.Clear();
183 uint64_t iNow = GetTimeMs();
184 uint64_t iTarget = iNow + iTimeout;
185 bool bGotFullMessage(false);
186 bool bNextIsEscaped(false);
187 bool bGotStart(false);
188
189 while(!bGotFullMessage && iNow < iTarget)
190 {
191 uint8_t buf = 0;
192 if (!m_inBuffer.Pop(buf))
193 {
194 if (!m_rcvCondition.Wait(m_mutex, (uint32_t) (iTarget - iNow)))
195 return false;
196 }
197
198 if (!bGotStart)
199 {
200 if (buf == MSGSTART)
201 bGotStart = true;
202 continue;
203 }
204 else if (buf == MSGSTART) //we found a msgstart before msgend, this is not right, remove
205 {
206 if (msg.Size() > 0)
207 m_processor->AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
208 msg.Clear();
209 bGotStart = true;
210 }
211
212 if (buf == MSGEND)
213 {
214 bGotFullMessage = true;
215 }
216 else if (bNextIsEscaped)
217 {
218 msg.PushBack(buf + (uint8_t)ESCOFFSET);
219 bNextIsEscaped = false;
220 }
221 else if (buf == MSGESC)
222 bNextIsEscaped = true;
223 else
224 msg.PushBack(buf);
225 }
226
227 if (bGotFullMessage)
228 msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
229
230 return bGotFullMessage;
231 }
232
233 std::string CAdapterCommunication::GetError(void) const
234 {
235 return m_port->GetError();
236 }
237
238 bool CAdapterCommunication::StartBootloader(void)
239 {
240 bool bReturn(false);
241 if (!IsRunning())
242 return bReturn;
243
244 m_processor->AddLog(CEC_LOG_DEBUG, "starting the bootloader");
245 CCECAdapterMessage *output = new CCECAdapterMessage;
246
247 output->PushBack(MSGSTART);
248 output->PushEscaped(MSGCODE_START_BOOTLOADER);
249 output->PushBack(MSGEND);
250 output->isTransmission = false;
251 output->expectControllerAck = false;
252
253 if ((bReturn = Write(output)) == false)
254 m_processor->AddLog(CEC_LOG_ERROR, "could not start the bootloader");
255 delete output;
256
257 return bReturn;
258 }
259
260 bool CAdapterCommunication::PingAdapter(void)
261 {
262 bool bReturn(false);
263 if (!IsRunning())
264 return bReturn;
265
266 m_processor->AddLog(CEC_LOG_DEBUG, "sending ping");
267 CCECAdapterMessage *output = new CCECAdapterMessage;
268
269 output->PushBack(MSGSTART);
270 output->PushEscaped(MSGCODE_PING);
271 output->PushBack(MSGEND);
272 output->isTransmission = false;
273
274 if ((bReturn = Write(output)) == false)
275 m_processor->AddLog(CEC_LOG_ERROR, "could not ping the adapter");
276 delete output;
277
278 return bReturn;
279 }
280
281 uint16_t CAdapterCommunication::GetFirmwareVersion(void)
282 {
283 uint16_t iReturn(m_iFirmwareVersion);
284 if (!IsRunning())
285 return iReturn;
286
287 if (iReturn == CEC_FW_VERSION_UNKNOWN)
288 {
289 m_processor->AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
290 CCECAdapterMessage *output = new CCECAdapterMessage;
291
292 output->PushBack(MSGSTART);
293 output->PushEscaped(MSGCODE_FIRMWARE_VERSION);
294 output->PushBack(MSGEND);
295 output->isTransmission = false;
296 output->expectControllerAck = false;
297
298 SendMessageToAdapter(output);
299 delete output;
300
301 CCECAdapterMessage input;
302 if (!Read(input, CEC_DEFAULT_TRANSMIT_WAIT) || input.Message() != MSGCODE_FIRMWARE_VERSION || input.Size() != 3)
303 m_processor->AddLog(CEC_LOG_ERROR, "no or invalid firmware version");
304 else
305 {
306 m_iFirmwareVersion = (input[1] << 8 | input[2]);
307 iReturn = m_iFirmwareVersion;
308 }
309 }
310
311 return iReturn;
312 }
313
314 bool CAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
315 {
316 bool bReturn(m_iLineTimeout != iTimeout);
317
318 if (!bReturn)
319 {
320 CCECAdapterMessage *output = new CCECAdapterMessage;
321
322 output->PushBack(MSGSTART);
323 output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
324 output->PushEscaped(iTimeout);
325 output->PushBack(MSGEND);
326 output->isTransmission = false;
327
328 if ((bReturn = Write(output)) == false)
329 m_processor->AddLog(CEC_LOG_ERROR, "could not set the idletime");
330 delete output;
331 }
332
333 return bReturn;
334 }
335
336 bool CAdapterCommunication::SetAckMask(uint16_t iMask)
337 {
338 bool bReturn(false);
339 CStdString strLog;
340 strLog.Format("setting ackmask to %2x", iMask);
341 m_processor->AddLog(CEC_LOG_DEBUG, strLog.c_str());
342
343 CCECAdapterMessage *output = new CCECAdapterMessage;
344
345 output->PushBack(MSGSTART);
346 output->PushEscaped(MSGCODE_SET_ACK_MASK);
347 output->PushEscaped(iMask >> 8);
348 output->PushEscaped((uint8_t)iMask);
349 output->PushBack(MSGEND);
350 output->isTransmission = false;
351
352 if ((bReturn = Write(output)) == false)
353 m_processor->AddLog(CEC_LOG_ERROR, "could not set the ackmask");
354 delete output;
355
356 return bReturn;
357 }
358
359 bool CAdapterCommunication::IsOpen(void)
360 {
361 return !IsStopped() && m_port->IsOpen() && IsRunning();
362 }
363
364 bool CAdapterCommunication::WaitForTransmitSucceeded(CCECAdapterMessage *message)
365 {
366 bool bError(false);
367 bool bTransmitSucceeded(false);
368 uint8_t iPacketsLeft(message->Size() / 4);
369
370 int64_t iNow = GetTimeMs();
371 int64_t iTargetTime = iNow + message->transmit_timeout;
372
373 while (!bTransmitSucceeded && !bError && (message->transmit_timeout == 0 || iNow < iTargetTime))
374 {
375 CCECAdapterMessage msg;
376
377 if (!Read(msg, message->transmit_timeout > 0 ? (int32_t)(iTargetTime - iNow) : 1000))
378 {
379 iNow = GetTimeMs();
380 continue;
381 }
382
383 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
384 {
385 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
386 iNow = GetTimeMs();
387 continue;
388 }
389
390 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
391 m_processor->HandleReceiveFailed())
392 {
393 iNow = GetTimeMs();
394 continue;
395 }
396
397 bError = msg.IsError();
398 if (bError)
399 {
400 message->reply = msg.Message();
401 m_processor->AddLog(CEC_LOG_DEBUG, msg.ToString());
402 }
403 else
404 {
405 switch(msg.Message())
406 {
407 case MSGCODE_COMMAND_ACCEPTED:
408 m_processor->AddLog(CEC_LOG_DEBUG, msg.ToString());
409 if (iPacketsLeft > 0)
410 iPacketsLeft--;
411 if (!message->isTransmission && iPacketsLeft == 0)
412 bTransmitSucceeded = true;
413 break;
414 case MSGCODE_TRANSMIT_SUCCEEDED:
415 m_processor->AddLog(CEC_LOG_DEBUG, msg.ToString());
416 bTransmitSucceeded = (iPacketsLeft == 0);
417 bError = !bTransmitSucceeded;
418 message->reply = MSGCODE_TRANSMIT_SUCCEEDED;
419 break;
420 default:
421 // ignore other data while waiting
422 break;
423 }
424
425 iNow = GetTimeMs();
426 }
427 }
428
429 return bTransmitSucceeded && !bError;
430 }
431
432 void CAdapterCommunication::AddData(uint8_t *data, uint8_t iLen)
433 {
434 CLockObject lock(m_mutex);
435 for (uint8_t iPtr = 0; iPtr < iLen; iPtr++)
436 m_inBuffer.Push(data[iPtr]);
437
438 m_rcvCondition.Signal();
439 }
440
441 bool CAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
442 {
443 int32_t iBytesRead;
444 uint8_t buff[1024];
445 if (!m_port)
446 return false;
447
448 CLockObject lock(m_mutex);
449 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
450 if (iBytesRead < 0 || iBytesRead > 256)
451 {
452 CStdString strError;
453 strError.Format("error reading from serial port: %s", m_port->GetError().c_str());
454 m_processor->AddLog(CEC_LOG_ERROR, strError);
455 return false;
456 }
457 else if (iBytesRead > 0)
458 AddData(buff, (uint8_t) iBytesRead);
459
460 return iBytesRead > 0;
461 }
462
463 void CAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
464 {
465 CLockObject adapterLock(m_mutex);
466 CLockObject lock(msg->mutex);
467 if (m_port->Write(msg->packet.data, msg->Size()) != (int32_t) msg->Size())
468 {
469 CStdString strError;
470 strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
471 m_processor->AddLog(CEC_LOG_ERROR, strError);
472 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
473 }
474 else
475 {
476 m_processor->AddLog(CEC_LOG_DEBUG, "command sent");
477 msg->state = ADAPTER_MESSAGE_STATE_SENT;
478 }
479 msg->condition.Signal();
480 }
481
482 void CAdapterCommunication::WriteNextCommand(void)
483 {
484 CCECAdapterMessage *msg(NULL);
485 if (m_outBuffer.Pop(msg))
486 SendMessageToAdapter(msg);
487 }