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