cec: fix some logging. only transmit packets once
[deb_libcec.git] / src / lib / AdapterDetection.cpp
CommitLineData
abbca718
LOK
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
2abe74eb 33#include "AdapterDetection.h"
b9187cc6 34#include "platform/os-dependent.h"
abbca718 35#include "util/StdString.h"
a58d63d2 36
6df2c52f 37#if defined(__APPLE__)
38#include <dirent.h>
39#include <sys/param.h>
40#include <IOKit/IOKitLib.h>
41#include <IOKit/IOMessage.h>
42#include <IOKit/IOCFPlugIn.h>
43#include <IOKit/usb/IOUSBLib.h>
44#include <IOKit/serial/IOSerialKeys.h>
45#include <CoreFoundation/CoreFoundation.h>
46
47#elif !defined(__WINDOWS__)
abbca718
LOK
48#include <dirent.h>
49#include <libudev.h>
50#include <poll.h>
a58d63d2
LOK
51#else
52#include <setupapi.h>
53
54// the virtual COM port only shows up when requesting devices with the raw device guid!
55static GUID USB_RAW_GUID = { 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
abbca718 56#endif
abbca718
LOK
57
58#define CEC_VID 0x2548
59#define CEC_PID 0x1001
60
61using namespace CEC;
62using namespace std;
63
64#if !defined(__WINDOWS__)
65bool TranslateComPort(CStdString &strString)
66{
67 CStdString strTmp(strString);
68 strTmp.MakeReverse();
69 int iSlash = strTmp.Find('/');
70 if (iSlash >= 0)
71 {
72 strTmp = strTmp.Left(iSlash);
73 strTmp.MakeReverse();
74 strString.Format("%s/%s:1.0/tty", strString.c_str(), strTmp.c_str());
75 return true;
76 }
77
78 return false;
79}
80
81bool FindComPort(CStdString &strLocation)
82{
83 CStdString strPort = strLocation;
84 bool bReturn(!strPort.IsEmpty());
85 CStdString strConfigLocation(strLocation);
86 if (TranslateComPort(strConfigLocation))
87 {
88 DIR *dir;
89 struct dirent *dirent;
90 if((dir = opendir(strConfigLocation.c_str())) == NULL)
91 return bReturn;
92
93 while ((dirent = readdir(dir)) != NULL)
94 {
95 if(strcmp((char*)dirent->d_name, "." ) != 0 && strcmp((char*)dirent->d_name, ".." ) != 0)
96 {
97 strPort.Format("/dev/%s", dirent->d_name);
98 if (!strPort.IsEmpty())
99 {
100 strLocation = strPort;
101 bReturn = true;
102 break;
103 }
104 }
105 }
106 closedir(dir);
107 }
108
109 return bReturn;
110}
111#endif
112
25701fa6 113uint8_t CAdapterDetection::FindAdapters(cec_adapter *deviceList, uint8_t iBufSize, const char *strDevicePath /* = NULL */)
abbca718 114{
25701fa6 115 uint8_t iFound(0);
abbca718 116
6df2c52f 117#if defined(__APPLE__)
118 kern_return_t kresult;
119 char bsdPath[MAXPATHLEN] = {0};
120 io_iterator_t serialPortIterator;
121
122 CFMutableDictionaryRef classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
123 if (classesToMatch)
124 {
125 CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDModemType));
126 kresult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, &serialPortIterator);
127 if (kresult == KERN_SUCCESS)
128 {
129 io_object_t serialService;
130 while ((serialService = IOIteratorNext(serialPortIterator)))
131 {
132 int iVendor = 0, iProduct = 0;
133 CFTypeRef bsdPathAsCFString;
134
135 // fetch the device path.
136 bsdPathAsCFString = IORegistryEntryCreateCFProperty(serialService,
137 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
138 if (bsdPathAsCFString)
139 {
140 // convert the path from a CFString to a C (NUL-terminated) string.
141 CFStringGetCString((CFStringRef)bsdPathAsCFString, bsdPath, MAXPATHLEN - 1, kCFStringEncodingUTF8);
142 CFRelease(bsdPathAsCFString);
143
144 // now walk up the hierarchy until we find the entry with vendor/product IDs
145 io_registry_entry_t parent;
146 CFTypeRef vendorIdAsCFNumber = NULL;
147 CFTypeRef productIdAsCFNumber = NULL;
148 kern_return_t kresult = IORegistryEntryGetParentEntry(serialService, kIOServicePlane, &parent);
149 while (kresult == KERN_SUCCESS)
150 {
151 vendorIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
152 kIOServicePlane, CFSTR(kUSBVendorID), kCFAllocatorDefault, 0);
153 productIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
154 kIOServicePlane, CFSTR(kUSBProductID), kCFAllocatorDefault, 0);
155 if (vendorIdAsCFNumber && productIdAsCFNumber)
156 {
157 CFNumberGetValue((CFNumberRef)vendorIdAsCFNumber, kCFNumberIntType, &iVendor);
158 CFRelease(vendorIdAsCFNumber);
159 CFNumberGetValue((CFNumberRef)productIdAsCFNumber, kCFNumberIntType, &iProduct);
160 CFRelease(productIdAsCFNumber);
161 IOObjectRelease(parent);
162 break;
163 }
164 io_registry_entry_t oldparent = parent;
165 kresult = IORegistryEntryGetParentEntry(parent, kIOServicePlane, &parent);
166 IOObjectRelease(oldparent);
167 }
168 if (strlen(bsdPath) && iVendor == CEC_VID && iProduct == CEC_PID)
169 {
170 if (!strDevicePath || !strcmp(bsdPath, strDevicePath))
171 {
172 // on darwin, the device path is the same as the comm path.
173 snprintf(deviceList[iFound ].path, sizeof(deviceList[iFound].path), "%s", bsdPath);
174 snprintf(deviceList[iFound++].comm, sizeof(deviceList[iFound].path), "%s", bsdPath);
175 }
176 }
177 }
178 IOObjectRelease(serialService);
179 }
180 }
181 IOObjectRelease(serialPortIterator);
182 }
183
184#elif !defined(__WINDOWS__)
abbca718
LOK
185 struct udev *udev;
186 if (!(udev = udev_new()))
187 return -1;
188
189 struct udev_enumerate *enumerate;
190 struct udev_list_entry *devices, *dev_list_entry;
25701fa6 191 struct udev_device *dev, *pdev;
abbca718
LOK
192 enumerate = udev_enumerate_new(udev);
193 udev_enumerate_scan_devices(enumerate);
194 devices = udev_enumerate_get_list_entry(enumerate);
195 udev_list_entry_foreach(dev_list_entry, devices)
196 {
197 const char *strPath;
198 strPath = udev_list_entry_get_name(dev_list_entry);
199
200 dev = udev_device_new_from_syspath(udev, strPath);
201 if (!dev)
202 continue;
203
25701fa6
LOK
204 pdev = udev_device_get_parent(udev_device_get_parent(dev));
205 if (!pdev || !udev_device_get_sysattr_value(pdev,"idVendor") || !udev_device_get_sysattr_value(pdev, "idProduct"))
abbca718
LOK
206 {
207 udev_device_unref(dev);
208 continue;
209 }
210
211 int iVendor, iProduct;
25701fa6
LOK
212 sscanf(udev_device_get_sysattr_value(pdev, "idVendor"), "%x", &iVendor);
213 sscanf(udev_device_get_sysattr_value(pdev, "idProduct"), "%x", &iProduct);
abbca718
LOK
214 if (iVendor == CEC_VID && iProduct == CEC_PID)
215 {
25701fa6
LOK
216 CStdString strPath(udev_device_get_syspath(pdev));
217 if (!strDevicePath || !strcmp(strPath.c_str(), strDevicePath))
abbca718 218 {
25701fa6
LOK
219 CStdString strComm(strPath);
220 if (FindComPort(strComm))
221 {
222 snprintf(deviceList[iFound ].path, sizeof(deviceList[iFound].path), "%s", strPath.c_str());
223 snprintf(deviceList[iFound++].comm, sizeof(deviceList[iFound].path), "%s", strComm.c_str());
224 }
abbca718
LOK
225 }
226 }
227 udev_device_unref(dev);
228 }
229
230 udev_enumerate_unref(enumerate);
231 udev_unref(udev);
a58d63d2
LOK
232#else
233 HDEVINFO hDevHandle;
234 DWORD required = 0, iMemberIndex = 0;
235 int nBufferSize = 0;
236
237 SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
238 deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
239
240 SP_DEVINFO_DATA devInfoData;
241 devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
242
243 if ((hDevHandle = SetupDiGetClassDevs(&USB_RAW_GUID, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)) == INVALID_HANDLE_VALUE)
244 return iFound;
245
246 BOOL bResult = true;
247 TCHAR *buffer = NULL;
248 PSP_DEVICE_INTERFACE_DETAIL_DATA devicedetailData;
25701fa6 249 while(bResult && iFound < iBufSize)
a58d63d2
LOK
250 {
251 bResult = SetupDiEnumDeviceInfo(hDevHandle, iMemberIndex, &devInfoData);
252
253 if (bResult)
254 bResult = SetupDiEnumDeviceInterfaces(hDevHandle, 0, &USB_RAW_GUID, iMemberIndex, &deviceInterfaceData);
255
256 if(!bResult)
257 {
258 SetupDiDestroyDeviceInfoList(hDevHandle);
259 delete []buffer;
260 buffer = NULL;
261 return iFound;
262 }
263
264 iMemberIndex++;
265 BOOL bDetailResult = false;
266 {
267 // As per MSDN, Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with a
268 // NULL DeviceInterfaceDetailData pointer, a DeviceInterfaceDetailDataSize of zero,
269 // and a valid RequiredSize variable. In response to such a call, this function returns
270 // the required buffer size at RequiredSize and fails with GetLastError returning
271 // ERROR_INSUFFICIENT_BUFFER.
272 // Allocate an appropriately sized buffer and call the function again to get the interface details.
273
274 SetupDiGetDeviceInterfaceDetail(hDevHandle, &deviceInterfaceData, NULL, 0, &required, NULL);
275
276 buffer = new TCHAR[required];
277 devicedetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) buffer;
278 devicedetailData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
279 nBufferSize = required;
280 }
281
282 bDetailResult = SetupDiGetDeviceInterfaceDetail(hDevHandle, &deviceInterfaceData, devicedetailData, nBufferSize , &required, NULL);
283 if(!bDetailResult)
284 continue;
285
b824eadc
LOK
286 if (strDevicePath && strcmp(strDevicePath, devicedetailData->DevicePath) != 0)
287 continue;
288
a58d63d2
LOK
289 CStdString strVendorId;
290 CStdString strProductId;
291 CStdString strTmp(devicedetailData->DevicePath);
25701fa6
LOK
292 strVendorId.assign(strTmp.substr(strTmp.Find("vid_") + 4, 4));
293 strProductId.assign(strTmp.substr(strTmp.Find("pid_") + 4, 4));
a58d63d2
LOK
294 if (strTmp.Find("&mi_") >= 0 && strTmp.Find("&mi_00") < 0)
295 continue;
296
297 int iVendor, iProduct;
298 sscanf(strVendorId, "%x", &iVendor);
299 sscanf(strProductId, "%x", &iProduct);
300 if (iVendor != CEC_VID || iProduct != CEC_PID)
301 continue;
302
303 HKEY hDeviceKey = SetupDiOpenDevRegKey(hDevHandle, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
304 if (!hDeviceKey)
305 continue;
306
307 TCHAR strPortName[256];
308 strPortName[0] = _T('\0');
309 DWORD dwSize = sizeof(strPortName);
310 DWORD dwType = 0;
311
312 /* search the registry */
313 if ((RegQueryValueEx(hDeviceKey, _T("PortName"), NULL, &dwType, reinterpret_cast<LPBYTE>(strPortName), &dwSize) == ERROR_SUCCESS) && (dwType == REG_SZ))
314 {
315 if (_tcslen(strPortName) > 3 && _tcsnicmp(strPortName, _T("COM"), 3) == 0 &&
316 _ttoi(&(strPortName[3])) > 0)
317 {
25701fa6
LOK
318 snprintf(deviceList[iFound ].path, sizeof(deviceList[iFound].path), "%s", devicedetailData->DevicePath);
319 snprintf(deviceList[iFound++].comm, sizeof(deviceList[iFound].path), "%s", strPortName);
a58d63d2
LOK
320 }
321 }
322
323 RegCloseKey(hDeviceKey);
324 }
abbca718
LOK
325#endif
326
327 return iFound;
328}