2 * This file is part of the libCEC(R) library.
4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
5 * libCEC(R) is an original work, containing original code.
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
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.
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.
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.
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
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/
34 #include "USBCECAdapterDetection.h"
35 #include "lib/platform/util/StdString.h"
37 #if defined(__APPLE__)
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 #elif defined(__WINDOWS__)
47 #pragma comment(lib, "advapi32.lib")
48 #pragma comment(lib, "setupapi.lib")
51 // the virtual COM port only shows up when requesting devices with the raw device guid!
52 static GUID USB_RAW_GUID
= { 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
53 #elif defined(HAVE_LIBUDEV)
59 #elif defined(__FreeBSD__)
64 #define CEC_VID 0x2548
65 #define CEC_PID 0x1001
66 #define CEC_PID2 0x1002
71 #if defined(HAVE_LIBUDEV)
72 bool TranslateComPort(CStdString
&strString
)
74 CStdString
strTmp(strString
);
76 int iSlash
= strTmp
.Find('/');
79 strTmp
= strTmp
.Left(iSlash
);
81 strString
.Format("%s/%s:1.0/tty", strString
.c_str(), strTmp
.c_str());
88 bool FindComPort(CStdString
&strLocation
)
90 CStdString strPort
= strLocation
;
91 bool bReturn(!strPort
.IsEmpty());
92 CStdString
strConfigLocation(strLocation
);
93 if (TranslateComPort(strConfigLocation
))
96 struct dirent
*dirent
;
97 if((dir
= opendir(strConfigLocation
.c_str())) == NULL
)
100 while ((dirent
= readdir(dir
)) != NULL
)
102 if(strcmp((char*)dirent
->d_name
, "." ) != 0 && strcmp((char*)dirent
->d_name
, ".." ) != 0)
104 strPort
.Format("/dev/%s", dirent
->d_name
);
105 if (!strPort
.IsEmpty())
107 strLocation
= strPort
;
120 bool CUSBCECAdapterDetection::CanAutodetect(void)
122 #if defined(__APPLE__) || defined(HAVE_LIBUDEV) || defined(__WINDOWS__) || defined(__FreeBSD__)
129 uint8_t CUSBCECAdapterDetection::FindAdapters(cec_adapter
*deviceList
, uint8_t iBufSize
, const char *strDevicePath
/* = NULL */)
133 #if defined(__APPLE__)
134 kern_return_t kresult
;
135 char bsdPath
[MAXPATHLEN
] = {0};
136 io_iterator_t serialPortIterator
;
138 CFMutableDictionaryRef classesToMatch
= IOServiceMatching(kIOSerialBSDServiceValue
);
141 CFDictionarySetValue(classesToMatch
, CFSTR(kIOSerialBSDTypeKey
), CFSTR(kIOSerialBSDModemType
));
142 kresult
= IOServiceGetMatchingServices(kIOMasterPortDefault
, classesToMatch
, &serialPortIterator
);
143 if (kresult
== KERN_SUCCESS
)
145 io_object_t serialService
;
146 while ((serialService
= IOIteratorNext(serialPortIterator
)))
148 int iVendor
= 0, iProduct
= 0;
149 CFTypeRef bsdPathAsCFString
;
151 // fetch the device path.
152 bsdPathAsCFString
= IORegistryEntryCreateCFProperty(serialService
,
153 CFSTR(kIOCalloutDeviceKey
), kCFAllocatorDefault
, 0);
154 if (bsdPathAsCFString
)
156 // convert the path from a CFString to a C (NUL-terminated) string.
157 CFStringGetCString((CFStringRef
)bsdPathAsCFString
, bsdPath
, MAXPATHLEN
- 1, kCFStringEncodingUTF8
);
158 CFRelease(bsdPathAsCFString
);
160 // now walk up the hierarchy until we find the entry with vendor/product IDs
161 io_registry_entry_t parent
;
162 CFTypeRef vendorIdAsCFNumber
= NULL
;
163 CFTypeRef productIdAsCFNumber
= NULL
;
164 kern_return_t kresult
= IORegistryEntryGetParentEntry(serialService
, kIOServicePlane
, &parent
);
165 while (kresult
== KERN_SUCCESS
)
167 vendorIdAsCFNumber
= IORegistryEntrySearchCFProperty(parent
,
168 kIOServicePlane
, CFSTR(kUSBVendorID
), kCFAllocatorDefault
, 0);
169 productIdAsCFNumber
= IORegistryEntrySearchCFProperty(parent
,
170 kIOServicePlane
, CFSTR(kUSBProductID
), kCFAllocatorDefault
, 0);
171 if (vendorIdAsCFNumber
&& productIdAsCFNumber
)
173 CFNumberGetValue((CFNumberRef
)vendorIdAsCFNumber
, kCFNumberIntType
, &iVendor
);
174 CFRelease(vendorIdAsCFNumber
);
175 CFNumberGetValue((CFNumberRef
)productIdAsCFNumber
, kCFNumberIntType
, &iProduct
);
176 CFRelease(productIdAsCFNumber
);
177 IOObjectRelease(parent
);
180 io_registry_entry_t oldparent
= parent
;
181 kresult
= IORegistryEntryGetParentEntry(parent
, kIOServicePlane
, &parent
);
182 IOObjectRelease(oldparent
);
184 if (strlen(bsdPath
) && iVendor
== CEC_VID
&& (iProduct
== CEC_PID
|| iProduct
== CEC_PID2
))
186 if (!strDevicePath
|| !strcmp(bsdPath
, strDevicePath
))
188 // on darwin, the device path is the same as the comm path.
189 snprintf(deviceList
[iFound
].path
, sizeof(deviceList
[iFound
].path
), "%s", bsdPath
);
190 snprintf(deviceList
[iFound
++].comm
, sizeof(deviceList
[iFound
].path
), "%s", bsdPath
);
194 IOObjectRelease(serialService
);
197 IOObjectRelease(serialPortIterator
);
199 #elif defined(HAVE_LIBUDEV)
201 if (!(udev
= udev_new()))
204 struct udev_enumerate
*enumerate
;
205 struct udev_list_entry
*devices
, *dev_list_entry
;
206 struct udev_device
*dev
, *pdev
;
207 enumerate
= udev_enumerate_new(udev
);
208 udev_enumerate_scan_devices(enumerate
);
209 devices
= udev_enumerate_get_list_entry(enumerate
);
210 udev_list_entry_foreach(dev_list_entry
, devices
)
213 strPath
= udev_list_entry_get_name(dev_list_entry
);
215 dev
= udev_device_new_from_syspath(udev
, strPath
);
219 pdev
= udev_device_get_parent(udev_device_get_parent(dev
));
220 if (!pdev
|| !udev_device_get_sysattr_value(pdev
,"idVendor") || !udev_device_get_sysattr_value(pdev
, "idProduct"))
222 udev_device_unref(dev
);
226 int iVendor
, iProduct
;
227 sscanf(udev_device_get_sysattr_value(pdev
, "idVendor"), "%x", &iVendor
);
228 sscanf(udev_device_get_sysattr_value(pdev
, "idProduct"), "%x", &iProduct
);
229 if (iVendor
== CEC_VID
&& (iProduct
== CEC_PID
|| iProduct
== CEC_PID2
))
231 CStdString
strPath(udev_device_get_syspath(pdev
));
232 if (!strDevicePath
|| !strcmp(strPath
.c_str(), strDevicePath
))
234 CStdString
strComm(strPath
);
235 if (FindComPort(strComm
))
237 snprintf(deviceList
[iFound
].path
, sizeof(deviceList
[iFound
].path
), "%s", strPath
.c_str());
238 snprintf(deviceList
[iFound
++].comm
, sizeof(deviceList
[iFound
].path
), "%s", strComm
.c_str());
242 udev_device_unref(dev
);
245 udev_enumerate_unref(enumerate
);
247 #elif defined(__WINDOWS__)
249 DWORD required
= 0, iMemberIndex
= 0;
252 SP_DEVICE_INTERFACE_DATA deviceInterfaceData
;
253 deviceInterfaceData
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
255 SP_DEVINFO_DATA devInfoData
;
256 devInfoData
.cbSize
= sizeof(SP_DEVINFO_DATA
);
258 if ((hDevHandle
= SetupDiGetClassDevs(&USB_RAW_GUID
, 0, 0, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
)) == INVALID_HANDLE_VALUE
)
262 TCHAR
*buffer
= NULL
;
263 PSP_DEVICE_INTERFACE_DETAIL_DATA devicedetailData
;
264 while(bResult
&& iFound
< iBufSize
)
266 bResult
= SetupDiEnumDeviceInfo(hDevHandle
, iMemberIndex
, &devInfoData
);
269 bResult
= SetupDiEnumDeviceInterfaces(hDevHandle
, 0, &USB_RAW_GUID
, iMemberIndex
, &deviceInterfaceData
);
273 SetupDiDestroyDeviceInfoList(hDevHandle
);
280 BOOL bDetailResult
= false;
282 // As per MSDN, Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with a
283 // NULL DeviceInterfaceDetailData pointer, a DeviceInterfaceDetailDataSize of zero,
284 // and a valid RequiredSize variable. In response to such a call, this function returns
285 // the required buffer size at RequiredSize and fails with GetLastError returning
286 // ERROR_INSUFFICIENT_BUFFER.
287 // Allocate an appropriately sized buffer and call the function again to get the interface details.
289 SetupDiGetDeviceInterfaceDetail(hDevHandle
, &deviceInterfaceData
, NULL
, 0, &required
, NULL
);
291 buffer
= new TCHAR
[required
];
292 devicedetailData
= (PSP_DEVICE_INTERFACE_DETAIL_DATA
) buffer
;
293 devicedetailData
->cbSize
= sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA
);
294 nBufferSize
= required
;
297 bDetailResult
= SetupDiGetDeviceInterfaceDetail(hDevHandle
, &deviceInterfaceData
, devicedetailData
, nBufferSize
, &required
, NULL
);
301 if (strDevicePath
&& strcmp(strDevicePath
, devicedetailData
->DevicePath
) != 0)
304 CStdString strVendorId
;
305 CStdString strProductId
;
306 CStdString
strTmp(devicedetailData
->DevicePath
);
307 strVendorId
.assign(strTmp
.substr(strTmp
.Find("vid_") + 4, 4));
308 strProductId
.assign(strTmp
.substr(strTmp
.Find("pid_") + 4, 4));
309 if (strTmp
.Find("&mi_") >= 0 && strTmp
.Find("&mi_00") < 0)
312 int iVendor
, iProduct
;
313 sscanf(strVendorId
, "%x", &iVendor
);
314 sscanf(strProductId
, "%x", &iProduct
);
315 if (iVendor
!= CEC_VID
|| (iProduct
!= CEC_PID
&& iProduct
!= CEC_PID2
))
318 HKEY hDeviceKey
= SetupDiOpenDevRegKey(hDevHandle
, &devInfoData
, DICS_FLAG_GLOBAL
, 0, DIREG_DEV
, KEY_QUERY_VALUE
);
322 TCHAR strPortName
[256];
323 strPortName
[0] = _T('\0');
324 DWORD dwSize
= sizeof(strPortName
);
327 /* search the registry */
328 if ((RegQueryValueEx(hDeviceKey
, _T("PortName"), NULL
, &dwType
, reinterpret_cast<LPBYTE
>(strPortName
), &dwSize
) == ERROR_SUCCESS
) && (dwType
== REG_SZ
))
330 if (_tcslen(strPortName
) > 3 && _tcsnicmp(strPortName
, _T("COM"), 3) == 0 &&
331 _ttoi(&(strPortName
[3])) > 0)
333 snprintf(deviceList
[iFound
].path
, sizeof(deviceList
[iFound
].path
), "%s", devicedetailData
->DevicePath
);
334 snprintf(deviceList
[iFound
++].comm
, sizeof(deviceList
[iFound
].path
), "%s", strPortName
);
338 RegCloseKey(hDeviceKey
);
340 #elif defined(__FreeBSD__)
341 char devicePath
[PATH_MAX
+ 1];
344 for (i
= 0; i
< 8; ++i
)
346 (void)snprintf(devicePath
, sizeof(devicePath
), "/dev/ttyU%d", i
);
347 if (!access(devicePath
, 0))
349 snprintf(deviceList
[iFound
].path
, sizeof(deviceList
[iFound
].path
), "%s", devicePath
);
350 snprintf(deviceList
[iFound
++].comm
, sizeof(deviceList
[iFound
].path
), "%s", devicePath
);
354 //silence "unused" warnings
355 void *tmp
= (void*)deviceList
;
356 tmp
= (void *)strDevicePath
;
359 iBufSize
= 0; /* silence "unused" warning on linux/osx */