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