Merge pull request #16 from finson/65894f58514a9ab61ae20e45cfde06c9d45600e4
[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>
42c02563 46#elif defined(__WINDOWS__)
a58d63d2
LOK
47#include <setupapi.h>
48
49// the virtual COM port only shows up when requesting devices with the raw device guid!
50static GUID USB_RAW_GUID = { 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
42c02563
LOK
51#elif defined(HAVE_LIBUDEV)
52#include <dirent.h>
42c02563 53#include <poll.h>
5fa3eb86
LOK
54extern "C" {
55#include <libudev.h>
56}
abbca718 57#endif
abbca718
LOK
58
59#define CEC_VID 0x2548
60#define CEC_PID 0x1001
61
62using namespace CEC;
63using namespace std;
64
42c02563 65#if defined(HAVE_LIBUDEV)
abbca718
LOK
66bool TranslateComPort(CStdString &strString)
67{
68 CStdString strTmp(strString);
69 strTmp.MakeReverse();
70 int iSlash = strTmp.Find('/');
71 if (iSlash >= 0)
72 {
73 strTmp = strTmp.Left(iSlash);
74 strTmp.MakeReverse();
75 strString.Format("%s/%s:1.0/tty", strString.c_str(), strTmp.c_str());
76 return true;
77 }
78
79 return false;
80}
81
82bool FindComPort(CStdString &strLocation)
83{
84 CStdString strPort = strLocation;
85 bool bReturn(!strPort.IsEmpty());
86 CStdString strConfigLocation(strLocation);
87 if (TranslateComPort(strConfigLocation))
88 {
89 DIR *dir;
90 struct dirent *dirent;
91 if((dir = opendir(strConfigLocation.c_str())) == NULL)
92 return bReturn;
93
94 while ((dirent = readdir(dir)) != NULL)
95 {
96 if(strcmp((char*)dirent->d_name, "." ) != 0 && strcmp((char*)dirent->d_name, ".." ) != 0)
97 {
98 strPort.Format("/dev/%s", dirent->d_name);
99 if (!strPort.IsEmpty())
100 {
101 strLocation = strPort;
102 bReturn = true;
103 break;
104 }
105 }
106 }
107 closedir(dir);
108 }
109
110 return bReturn;
111}
112#endif
113
25701fa6 114uint8_t CAdapterDetection::FindAdapters(cec_adapter *deviceList, uint8_t iBufSize, const char *strDevicePath /* = NULL */)
abbca718 115{
25701fa6 116 uint8_t iFound(0);
abbca718 117
6df2c52f 118#if defined(__APPLE__)
119 kern_return_t kresult;
120 char bsdPath[MAXPATHLEN] = {0};
121 io_iterator_t serialPortIterator;
122
123 CFMutableDictionaryRef classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
124 if (classesToMatch)
125 {
126 CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDModemType));
127 kresult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, &serialPortIterator);
128 if (kresult == KERN_SUCCESS)
129 {
130 io_object_t serialService;
131 while ((serialService = IOIteratorNext(serialPortIterator)))
132 {
133 int iVendor = 0, iProduct = 0;
134 CFTypeRef bsdPathAsCFString;
135
136 // fetch the device path.
137 bsdPathAsCFString = IORegistryEntryCreateCFProperty(serialService,
138 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
139 if (bsdPathAsCFString)
140 {
141 // convert the path from a CFString to a C (NUL-terminated) string.
142 CFStringGetCString((CFStringRef)bsdPathAsCFString, bsdPath, MAXPATHLEN - 1, kCFStringEncodingUTF8);
143 CFRelease(bsdPathAsCFString);
144
145 // now walk up the hierarchy until we find the entry with vendor/product IDs
146 io_registry_entry_t parent;
147 CFTypeRef vendorIdAsCFNumber = NULL;
148 CFTypeRef productIdAsCFNumber = NULL;
149 kern_return_t kresult = IORegistryEntryGetParentEntry(serialService, kIOServicePlane, &parent);
150 while (kresult == KERN_SUCCESS)
151 {
152 vendorIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
153 kIOServicePlane, CFSTR(kUSBVendorID), kCFAllocatorDefault, 0);
154 productIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
155 kIOServicePlane, CFSTR(kUSBProductID), kCFAllocatorDefault, 0);
156 if (vendorIdAsCFNumber && productIdAsCFNumber)
157 {
158 CFNumberGetValue((CFNumberRef)vendorIdAsCFNumber, kCFNumberIntType, &iVendor);
159 CFRelease(vendorIdAsCFNumber);
160 CFNumberGetValue((CFNumberRef)productIdAsCFNumber, kCFNumberIntType, &iProduct);
161 CFRelease(productIdAsCFNumber);
162 IOObjectRelease(parent);
163 break;
164 }
165 io_registry_entry_t oldparent = parent;
166 kresult = IORegistryEntryGetParentEntry(parent, kIOServicePlane, &parent);
167 IOObjectRelease(oldparent);
168 }
169 if (strlen(bsdPath) && iVendor == CEC_VID && iProduct == CEC_PID)
170 {
171 if (!strDevicePath || !strcmp(bsdPath, strDevicePath))
172 {
173 // on darwin, the device path is the same as the comm path.
174 snprintf(deviceList[iFound ].path, sizeof(deviceList[iFound].path), "%s", bsdPath);
175 snprintf(deviceList[iFound++].comm, sizeof(deviceList[iFound].path), "%s", bsdPath);
176 }
177 }
178 }
179 IOObjectRelease(serialService);
180 }
181 }
182 IOObjectRelease(serialPortIterator);
183 }
42c02563 184#elif defined(HAVE_LIBUDEV)
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);
42c02563 232#elif defined(__WINDOWS__)
a58d63d2
LOK
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}