cec: added logical address autodetection and let libcec handle multiple types simulta...
[deb_libcec.git] / src / lib / CECProcessor.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 "CECProcessor.h"
34
35 #include "AdapterCommunication.h"
36 #include "devices/CECBusDevice.h"
37 #include "LibCEC.h"
38 #include "util/StdString.h"
39 #include "platform/timeutils.h"
40
41 using namespace CEC;
42 using namespace std;
43
44 CCECProcessor::CCECProcessor(CLibCEC *controller, CAdapterCommunication *serComm, const char *strDeviceName, cec_logical_address iLogicalAddress /* = CECDEVICE_PLAYBACKDEVICE1 */, uint16_t iPhysicalAddress /* = CEC_DEFAULT_PHYSICAL_ADDRESS*/) :
45 m_bStarted(false),
46 m_strDeviceName(strDeviceName),
47 m_communication(serComm),
48 m_controller(controller),
49 m_bMonitor(false)
50 {
51 m_logicalAddresses.clear();
52 m_logicalAddresses.set(iLogicalAddress);
53 m_types.clear();
54 for (int iPtr = 0; iPtr < 16; iPtr++)
55 m_busDevices[iPtr] = new CCECBusDevice(this, (cec_logical_address) iPtr, iPtr == iLogicalAddress ? iPhysicalAddress : 0);
56 }
57
58 CCECProcessor::CCECProcessor(CLibCEC *controller, CAdapterCommunication *serComm, const char *strDeviceName, const cec_device_type_list &types) :
59 m_bStarted(false),
60 m_strDeviceName(strDeviceName),
61 m_types(types),
62 m_communication(serComm),
63 m_controller(controller),
64 m_bMonitor(false)
65 {
66 m_logicalAddresses.clear();
67 for (int iPtr = 0; iPtr < 16; iPtr++)
68 m_busDevices[iPtr] = new CCECBusDevice(this, (cec_logical_address) iPtr, 0);
69 }
70
71 CCECProcessor::~CCECProcessor(void)
72 {
73 m_startCondition.Broadcast();
74 StopThread();
75 m_communication = NULL;
76 m_controller = NULL;
77 for (unsigned int iPtr = 0; iPtr < 16; iPtr++)
78 delete m_busDevices[iPtr];
79 }
80
81 bool CCECProcessor::Start(void)
82 {
83 CLockObject lock(&m_mutex);
84 if (!m_communication || !m_communication->IsOpen())
85 {
86 m_controller->AddLog(CEC_LOG_ERROR, "connection is closed");
87 return false;
88 }
89
90 if (CreateThread())
91 {
92 if (!m_startCondition.Wait(&m_mutex) || !m_bStarted)
93 {
94 m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread");
95 return false;
96 }
97 return true;
98 }
99 else
100 m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread");
101
102 return false;
103 }
104
105 bool CCECProcessor::TryLogicalAddress(cec_logical_address address, const char *strLabel)
106 {
107 CStdString strLog;
108 strLog.Format("trying logical address '%s'", strLabel);
109 AddLog(CEC_LOG_DEBUG, strLog);
110
111 SetAckMask(0x1 << address);
112 if (!m_busDevices[address]->PollDevice(address))
113 {
114
115 strLog.Format("using logical address '%s'", strLabel);
116 AddLog(CEC_LOG_NOTICE, strLog);
117 m_logicalAddresses.set(address);
118
119 // TODO
120 m_busDevices[address]->SetPhysicalAddress(CEC_DEFAULT_PHYSICAL_ADDRESS);
121
122 return true;
123 }
124
125 strLog.Format("logical address '%s' already taken", strLabel);
126 AddLog(CEC_LOG_DEBUG, strLog);
127 return false;
128 }
129
130 bool CCECProcessor::FindLogicalAddressRecordingDevice(void)
131 {
132 AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'recording device'");
133 return TryLogicalAddress(CECDEVICE_RECORDINGDEVICE1, "recording 1") ||
134 TryLogicalAddress(CECDEVICE_RECORDINGDEVICE2, "recording 2") ||
135 TryLogicalAddress(CECDEVICE_RECORDINGDEVICE3, "recording 3");
136 }
137
138 bool CCECProcessor::FindLogicalAddressTuner(void)
139 {
140 AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'tuner'");
141 return TryLogicalAddress(CECDEVICE_TUNER1, "tuner 1") ||
142 TryLogicalAddress(CECDEVICE_TUNER2, "tuner 2") ||
143 TryLogicalAddress(CECDEVICE_TUNER3, "tuner 3") ||
144 TryLogicalAddress(CECDEVICE_TUNER4, "tuner 4");
145 }
146
147 bool CCECProcessor::FindLogicalAddressPlaybackDevice(void)
148 {
149 AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'playback device'");
150 return TryLogicalAddress(CECDEVICE_PLAYBACKDEVICE1, "playback 1") ||
151 TryLogicalAddress(CECDEVICE_PLAYBACKDEVICE2, "playback 2") ||
152 TryLogicalAddress(CECDEVICE_PLAYBACKDEVICE3, "playback 3");
153 }
154
155 bool CCECProcessor::FindLogicalAddressAudioSystem(void)
156 {
157 AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'audio'");
158 return TryLogicalAddress(CECDEVICE_AUDIOSYSTEM, "audio");
159 }
160
161 bool CCECProcessor::FindLogicalAddresses(void)
162 {
163 bool bReturn(true);
164 m_logicalAddresses.clear();
165 CStdString strLog;
166
167 for (unsigned int iPtr = 0; iPtr < 5; iPtr++)
168 {
169 if (m_types.types[iPtr] == CEC_DEVICE_TYPE_RESERVED)
170 continue;
171
172 strLog.Format("%s - device %d: type %d", __FUNCTION__, iPtr, m_types.types[iPtr]);
173 AddLog(CEC_LOG_DEBUG, strLog);
174
175 if (m_types.types[iPtr] == CEC_DEVICE_TYPE_RECORDING_DEVICE)
176 bReturn &= FindLogicalAddressRecordingDevice();
177 if (m_types.types[iPtr] == CEC_DEVICE_TYPE_TUNER)
178 bReturn &= FindLogicalAddressTuner();
179 if (m_types.types[iPtr] == CEC_DEVICE_TYPE_PLAYBACK_DEVICE)
180 bReturn &= FindLogicalAddressPlaybackDevice();
181 if (m_types.types[iPtr] == CEC_DEVICE_TYPE_AUDIO_SYSTEM)
182 bReturn &= FindLogicalAddressAudioSystem();
183 }
184
185 return bReturn;
186 }
187
188 void *CCECProcessor::Process(void)
189 {
190 cec_command command;
191 CCECAdapterMessage msg;
192
193 {
194 if (m_logicalAddresses.empty() && !FindLogicalAddresses())
195 {
196 CLockObject lock(&m_mutex);
197 m_controller->AddLog(CEC_LOG_ERROR, "could not detect our logical addressed");
198 m_startCondition.Signal();
199 return NULL;
200 }
201
202 SetAckMask(m_logicalAddresses.ackmask());
203
204 {
205 CLockObject lock(&m_mutex);
206 m_controller->AddLog(CEC_LOG_DEBUG, "processor thread started");
207 m_bStarted = true;
208 m_startCondition.Signal();
209 }
210 }
211
212 while (!IsStopped())
213 {
214 bool bParseFrame(false);
215 command.clear();
216 msg.clear();
217
218 {
219 CLockObject lock(&m_mutex);
220 if (m_communication->IsOpen() && m_communication->Read(msg, 50))
221 {
222 m_controller->AddLog(msg.is_error() ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
223 bParseFrame = ParseMessage(msg) && !IsStopped();
224 }
225
226 if (bParseFrame)
227 command = m_currentframe;
228 }
229
230 if (bParseFrame)
231 ParseCommand(command);
232
233 Sleep(5);
234
235 m_controller->CheckKeypressTimeout();
236
237 for (unsigned int iDevicePtr = 0; iDevicePtr < 16; iDevicePtr++)
238 m_busDevices[iDevicePtr]->PollVendorId();
239
240 Sleep(5);
241 }
242
243 return NULL;
244 }
245
246 bool CCECProcessor::SetActiveView(void)
247 {
248 if (!IsRunning())
249 return false;
250
251 if (!m_logicalAddresses.empty() && m_busDevices[m_logicalAddresses.primary])
252 return m_busDevices[m_logicalAddresses.primary]->BroadcastActiveView();
253 return false;
254 }
255
256 bool CCECProcessor::SetInactiveView(void)
257 {
258 if (!IsRunning())
259 return false;
260
261 if (!m_logicalAddresses.empty() && m_busDevices[m_logicalAddresses.primary])
262 return m_busDevices[m_logicalAddresses.primary]->BroadcastInactiveView();
263 return false;
264 }
265
266 void CCECProcessor::LogOutput(const cec_command &data)
267 {
268 CStdString strTx;
269 strTx.Format("<< %02x", ((uint8_t)data.initiator << 4) + (uint8_t)data.destination);
270 if (data.opcode_set)
271 strTx.AppendFormat(":%02x", (uint8_t)data.opcode);
272
273 for (uint8_t iPtr = 0; iPtr < data.parameters.size; iPtr++)
274 strTx.AppendFormat(":%02x", data.parameters[iPtr]);
275 m_controller->AddLog(CEC_LOG_TRAFFIC, strTx.c_str());
276 }
277
278 bool CCECProcessor::SetLogicalAddress(cec_logical_address iLogicalAddress)
279 {
280 if (m_logicalAddresses.primary != iLogicalAddress)
281 {
282 CStdString strLog;
283 strLog.Format("<< setting primary logical address to %1x", iLogicalAddress);
284 m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str());
285 m_logicalAddresses.primary = iLogicalAddress;
286 m_logicalAddresses.set(iLogicalAddress);
287 return SetAckMask(m_logicalAddresses.ackmask());
288 }
289
290 return true;
291 }
292
293 bool CCECProcessor::SetPhysicalAddress(uint16_t iPhysicalAddress)
294 {
295 if (!m_logicalAddresses.empty() && m_busDevices[m_logicalAddresses.primary])
296 {
297 m_busDevices[m_logicalAddresses.primary]->SetPhysicalAddress(iPhysicalAddress);
298 return m_busDevices[m_logicalAddresses.primary]->BroadcastActiveView();
299 }
300 return false;
301 }
302
303 bool CCECProcessor::SwitchMonitoring(bool bEnable)
304 {
305 CStdString strLog;
306 strLog.Format("== %s monitoring mode ==", bEnable ? "enabling" : "disabling");
307 m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str());
308
309 m_bMonitor = bEnable;
310 if (bEnable)
311 return SetAckMask(0);
312 else
313 return SetAckMask(m_logicalAddresses.ackmask());
314 }
315
316 bool CCECProcessor::PollDevice(cec_logical_address iAddress)
317 {
318 if (iAddress != CECDEVICE_UNKNOWN && m_busDevices[iAddress])
319 return m_busDevices[iAddress]->PollDevice();
320 return false;
321 }
322
323 cec_version CCECProcessor::GetDeviceCecVersion(cec_logical_address iAddress)
324 {
325 return m_busDevices[iAddress]->GetCecVersion();
326 }
327
328 bool CCECProcessor::GetDeviceMenuLanguage(cec_logical_address iAddress, cec_menu_language *language)
329 {
330 if (m_busDevices[iAddress])
331 {
332 *language = m_busDevices[iAddress]->GetMenuLanguage();
333 return (strcmp(language->language, "???") != 0);
334 }
335 return false;
336 }
337
338 uint64_t CCECProcessor::GetDeviceVendorId(cec_logical_address iAddress)
339 {
340 if (m_busDevices[iAddress])
341 return m_busDevices[iAddress]->GetVendorId();
342 return false;
343 }
344
345 cec_power_status CCECProcessor::GetDevicePowerStatus(cec_logical_address iAddress)
346 {
347 if (m_busDevices[iAddress])
348 return m_busDevices[iAddress]->GetPowerStatus();
349 return CEC_POWER_STATUS_UNKNOWN;
350 }
351
352 bool CCECProcessor::Transmit(const cec_command &data)
353 {
354 bool bReturn(false);
355 LogOutput(data);
356
357 CCECAdapterMessage *output = new CCECAdapterMessage(data);
358 bReturn = Transmit(output);
359 delete output;
360
361 return bReturn;
362 }
363
364 bool CCECProcessor::Transmit(CCECAdapterMessage *output)
365 {
366 bool bReturn(false);
367 CLockObject lock(&m_mutex);
368 {
369 CLockObject msgLock(&output->mutex);
370 if (!m_communication || !m_communication->Write(output))
371 return bReturn;
372 else
373 {
374 output->condition.Wait(&output->mutex);
375 if (output->state != ADAPTER_MESSAGE_STATE_SENT)
376 {
377 m_controller->AddLog(CEC_LOG_ERROR, "command was not sent");
378 return bReturn;
379 }
380 }
381
382 if (output->transmit_timeout > 0)
383 {
384 if ((bReturn = WaitForTransmitSucceeded(output->size(), output->transmit_timeout)) == false)
385 m_controller->AddLog(CEC_LOG_ERROR, "did not receive ack");
386 }
387 else
388 bReturn = true;
389 }
390
391 return bReturn;
392 }
393
394 void CCECProcessor::TransmitAbort(cec_logical_address address, cec_opcode opcode, ECecAbortReason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
395 {
396 m_controller->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message");
397
398 cec_command command;
399 // TODO
400 cec_command::format(command, m_logicalAddresses.primary, address, CEC_OPCODE_FEATURE_ABORT);
401 command.parameters.push_back((uint8_t)opcode);
402 command.parameters.push_back((uint8_t)reason);
403
404 Transmit(command);
405 }
406
407 bool CCECProcessor::WaitForTransmitSucceeded(uint8_t iLength, uint32_t iTimeout /* = 1000 */)
408 {
409 bool bError(false);
410 bool bTransmitSucceeded(false);
411 uint8_t iPacketsLeft(iLength / 4);
412
413 int64_t iNow = GetTimeMs();
414 int64_t iTargetTime = iNow + (uint64_t) iTimeout;
415
416 while (!bTransmitSucceeded && !bError && (iTimeout == 0 || iNow < iTargetTime))
417 {
418 CCECAdapterMessage msg;
419
420 if (!m_communication->Read(msg, iTimeout > 0 ? (int32_t)(iTargetTime - iNow) : 1000))
421 {
422 iNow = GetTimeMs();
423 continue;
424 }
425
426 if ((bError = msg.is_error()) == false)
427 {
428 m_controller->AddLog(bError ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
429
430 switch(msg.message())
431 {
432 case MSGCODE_COMMAND_ACCEPTED:
433 if (iPacketsLeft > 0)
434 iPacketsLeft--;
435 break;
436 case MSGCODE_TRANSMIT_SUCCEEDED:
437 bTransmitSucceeded = (iPacketsLeft == 0);
438 bError = !bTransmitSucceeded;
439 break;
440 default:
441 ParseMessage(msg);
442 }
443
444 iNow = GetTimeMs();
445 }
446 }
447
448 return bTransmitSucceeded && !bError;
449 }
450
451 bool CCECProcessor::ParseMessage(const CCECAdapterMessage &msg)
452 {
453 bool bEom = false;
454
455 if (msg.empty())
456 return bEom;
457
458 switch(msg.message())
459 {
460 case MSGCODE_FRAME_START:
461 {
462 m_currentframe.clear();
463 if (msg.size() >= 2)
464 {
465 m_currentframe.initiator = msg.initiator();
466 m_currentframe.destination = msg.destination();
467 m_currentframe.ack = msg.ack();
468 m_currentframe.eom = msg.eom();
469 }
470 }
471 break;
472 case MSGCODE_FRAME_DATA:
473 {
474 if (msg.size() >= 2)
475 {
476 m_currentframe.push_back(msg[1]);
477 m_currentframe.eom = msg.eom();
478 }
479 bEom = msg.eom();
480 }
481 break;
482 default:
483 break;
484 }
485
486 return bEom;
487 }
488
489 void CCECProcessor::ParseCommand(cec_command &command)
490 {
491 CStdString dataStr;
492 dataStr.Format(">> %1x%1x:%02x", command.initiator, command.destination, command.opcode);
493 for (uint8_t iPtr = 0; iPtr < command.parameters.size; iPtr++)
494 dataStr.AppendFormat(":%02x", (unsigned int)command.parameters[iPtr]);
495 m_controller->AddLog(CEC_LOG_TRAFFIC, dataStr.c_str());
496
497 if (!m_bMonitor)
498 m_busDevices[(uint8_t)command.initiator]->HandleCommand(command);
499 }
500
501 uint16_t CCECProcessor::GetPhysicalAddress(void) const
502 {
503 if (!m_logicalAddresses.empty() && m_busDevices[m_logicalAddresses.primary])
504 return m_busDevices[m_logicalAddresses.primary]->GetPhysicalAddress();
505 return false;
506 }
507
508 void CCECProcessor::SetCurrentButton(cec_user_control_code iButtonCode)
509 {
510 m_controller->SetCurrentButton(iButtonCode);
511 }
512
513 void CCECProcessor::AddCommand(const cec_command &command)
514 {
515 m_controller->AddCommand(command);
516 }
517
518 void CCECProcessor::AddKey(cec_keypress &key)
519 {
520 m_controller->AddKey(key);
521 }
522
523 void CCECProcessor::AddKey(void)
524 {
525 m_controller->AddKey();
526 }
527
528 void CCECProcessor::AddLog(cec_log_level level, const CStdString &strMessage)
529 {
530 m_controller->AddLog(level, strMessage);
531 }
532
533 bool CCECProcessor::SetAckMask(uint16_t iMask)
534 {
535 bool bReturn(false);
536 CStdString strLog;
537 strLog.Format("setting ackmask to %2x", iMask);
538 m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str());
539
540 CCECAdapterMessage *output = new CCECAdapterMessage;
541
542 output->push_back(MSGSTART);
543 output->push_escaped(MSGCODE_SET_ACK_MASK);
544 output->push_escaped(iMask >> 8);
545 output->push_escaped((uint8_t)iMask);
546 output->push_back(MSGEND);
547
548 if ((bReturn = Transmit(output)) == false)
549 m_controller->AddLog(CEC_LOG_ERROR, "could not set the ackmask");
550
551 delete output;
552
553 return bReturn;
554 }