Debian Codegraph @

interfaces/qextserialport/qextserialenumerator_win.cpp

raw symbols SCIP
1 /****************************************************************************
2 ** Copyright (c) 2000-2003 Wayne Roth
3 ** Copyright (c) 2004-2007 Stefan Sander
4 ** Copyright (c) 2007 Michal Policht
5 ** Copyright (c) 2008 Brandon Fosdick
6 ** Copyright (c) 2009-2010 Liam Staskawicz
7 ** Copyright (c) 2011 Debao Zhang
8 ** All right reserved.
9 ** Web: http://code.google.com/p/qextserialport/
10 **
11 ** Permission is hereby granted, free of charge, to any person obtaining
12 ** a copy of this software and associated documentation files (the
13 ** "Software"), to deal in the Software without restriction, including
14 ** without limitation the rights to use, copy, modify, merge, publish,
15 ** distribute, sublicense, and/or sell copies of the Software, and to
16 ** permit persons to whom the Software is furnished to do so, subject to
17 ** the following conditions:
18 **
19 ** The above copyright notice and this permission notice shall be
20 ** included in all copies or substantial portions of the Software.
21 **
22 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 ** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 ** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 ** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 ** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 **
30 ****************************************************************************/
31
32 #include "qextserialenumerator.h"
33 #include "qextserialenumerator_p.h"
34 #include <QtCore/QDebug>
35 #include <QtCore/QMetaType>
36 #include <QtCore/QRegExp>
37 #include <objbase.h>
38 #include <initguid.h>
39 #include <setupapi.h>
40 #include <dbt.h>
41 #include "qextserialport.h"
42
43 #ifdef QT_GUI_LIB
44 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
45 #include <QtGui/QWidget>
46 class QextSerialRegistrationWidget : public QWidget
47 #else
48 #include <QtGui/QWindow>
49 class QextSerialRegistrationWidget : public QWindow
50 #endif
51 {
52 public:
53 QextSerialRegistrationWidget(QextSerialEnumeratorPrivate *qese) {
54 this->qese = qese;
55 }
56 ~QextSerialRegistrationWidget() {}
57
58 protected:
59
60 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
61 bool winEvent(MSG *message, long *result) {
62 #else
63 bool nativeEvent(const QByteArray & /*eventType*/, void *msg, long *result) {
64 MSG *message = static_cast<MSG *>(msg);
65 #endif
66 if (message->message == WM_DEVICECHANGE) {
67 qese->onDeviceChanged(message->wParam, message->lParam);
68 *result = 1;
69 return true;
70 }
71 return false;
72 }
73 private:
74 QextSerialEnumeratorPrivate *qese;
75 };
76
77 #endif // QT_GUI_LIB
78
79 void QextSerialEnumeratorPrivate::platformSpecificInit()
80 {
81 #ifdef QT_GUI_LIB
82 notificationWidget = 0;
83 #endif // QT_GUI_LIB
84 }
85
86 /*!
87 default
88 */
89 void QextSerialEnumeratorPrivate::platformSpecificDestruct()
90 {
91 #ifdef QT_GUI_LIB
92 if (notificationWidget)
93 delete notificationWidget;
94 #endif
95 }
96
97 // see http://msdn.microsoft.com/en-us/library/windows/hardware/ff553426(v=vs.85).aspx
98 // for list of GUID classes
99 const GUID deviceClassGuids[] =
100 {
101 // Ports (COM & LPT ports), Class = Ports
102 {0x4D36E978, 0xE325, 0x11CE, {0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18}},
103 // Modem, Class = Modem
104 {0x4D36E96D, 0xE325, 0x11CE, {0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18}},
105 // Bluetooth Devices, Class = Bluetooth
106 {0xE0CBF06C, 0xCD8B, 0x4647, {0xBB, 0x8A, 0x26, 0x3B, 0x43, 0xF0, 0xF9, 0x74}},
107 // Added by Arne Kristian Jansen, for use with com0com virtual ports (See Issue 54)
108 {0xDF799E12, 0x3C56, 0x421B, {0xB2, 0x98, 0xB6, 0xD3, 0x64, 0x2B, 0xC8, 0x78}}
109 };
110
111 /* Gordon Schumacher's macros for TCHAR -> QString conversions and vice versa */
112 #ifdef UNICODE
113 #define QStringToTCHAR(x) (wchar_t *) x.utf16()
114 #define PQStringToTCHAR(x) (wchar_t *) x->utf16()
115 #define TCHARToQString(x) QString::fromUtf16((ushort *)(x))
116 #define TCHARToQStringN(x,y) QString::fromUtf16((ushort *)(x),(y))
117 #else
118 #define QStringToTCHAR(x) x.local8Bit().constData()
119 #define PQStringToTCHAR(x) x->local8Bit().constData()
120 #define TCHARToQString(x) QString::fromLocal8Bit((char *)(x))
121 #define TCHARToQStringN(x,y) QString::fromLocal8Bit((char *)(x),(y))
122 #endif /*UNICODE*/
123
124 /*!
125 \internal
126 Get value of specified property from the registry.
127 \a key handle to an open key.
128 \a property property name.
129
130 return property value.
131 */
132 static QString getRegKeyValue(HKEY key, LPCTSTR property)
133 {
134 DWORD size = 0;
135 DWORD type;
136 ::RegQueryValueEx(key, property, NULL, NULL, NULL, &size);
137 BYTE *buff = new BYTE[size];
138 QString result;
139 if (::RegQueryValueEx(key, property, NULL, &type, buff, &size) == ERROR_SUCCESS)
140 result = TCHARToQString(buff);
141 ::RegCloseKey(key);
142 delete [] buff;
143 return result;
144 }
145
146 /*!
147 \internal
148 Get specific property from registry.
149 \a devInfo pointer to the device information set that contains the interface
150 and its underlying device. Returned by SetupDiGetClassDevs() function.
151 \a devData pointer to an SP_DEVINFO_DATA structure that defines the device instance.
152 this is returned by SetupDiGetDeviceInterfaceDetail() function.
153 \a property registry property. One of defined SPDRP_* constants.
154
155 return property string.
156 */
157 static QString getDeviceProperty(HDEVINFO devInfo, PSP_DEVINFO_DATA devData, DWORD property)
158 {
159 DWORD buffSize = 0;
160 ::SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, NULL, 0, &buffSize);
161 BYTE *buff = new BYTE[buffSize];
162 ::SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, buff, buffSize, NULL);
163 QString result = TCHARToQString(buff);
164 delete [] buff;
165 return result;
166 }
167
168 /*!
169 \internal
170 */
171 static bool getDeviceDetailsWin(QextPortInfo *portInfo, HDEVINFO devInfo, PSP_DEVINFO_DATA devData
172 , WPARAM wParam = DBT_DEVICEARRIVAL)
173 {
174 portInfo->friendName = getDeviceProperty(devInfo, devData, SPDRP_FRIENDLYNAME);
175 if (wParam == DBT_DEVICEARRIVAL)
176 portInfo->physName = getDeviceProperty(devInfo, devData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME);
177 portInfo->enumName = getDeviceProperty(devInfo, devData, SPDRP_ENUMERATOR_NAME);
178 QString hardwareIDs = getDeviceProperty(devInfo, devData, SPDRP_HARDWAREID);
179 HKEY devKey = ::SetupDiOpenDevRegKey(devInfo, devData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
180 portInfo->portName = getRegKeyValue(devKey, TEXT("PortName"));
181 QRegExp idRx(QLatin1String("VID_(\\w+)&PID_(\\w+)"));
182 if (hardwareIDs.toUpper().contains(idRx)) {
183 bool dummy;
184 portInfo->vendorID = idRx.cap(1).toInt(&dummy, 16);
185 portInfo->productID = idRx.cap(2).toInt(&dummy, 16);
186 //qDebug() << "got vid:" << vid << "pid:" << pid;
187 }
188 return true;
189 }
190
191 /*!
192 \internal
193 */
194 static void enumerateDevicesWin(const GUID &guid, QList<QextPortInfo> *infoList)
195 {
196 HDEVINFO devInfo;
197 if ((devInfo = ::SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT)) != INVALID_HANDLE_VALUE) {
198 SP_DEVINFO_DATA devInfoData;
199 devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
200 for(int i = 0; ::SetupDiEnumDeviceInfo(devInfo, i, &devInfoData); i++) {
201 QextPortInfo info;
202 info.productID = info.vendorID = 0;
203 getDeviceDetailsWin(&info, devInfo, &devInfoData);
204 if (!info.portName.startsWith(QLatin1String("LPT"), Qt::CaseInsensitive))
205 infoList->append(info);
206 }
207 ::SetupDiDestroyDeviceInfoList(devInfo);
208 }
209 }
210
211
212 static bool lessThan(const QextPortInfo &s1, const QextPortInfo &s2)
213 {
214 if (s1.portName.startsWith(QLatin1String("COM"))
215 && s2.portName.startsWith(QLatin1String("COM"))) {
216 return s1.portName.mid(3).toInt()<s2.portName.mid(3).toInt();
217 }
218 return s1.portName < s2.portName;
219 }
220
221
222 /*!
223 Get list of ports.
224
225 return list of ports currently available in the system.
226 */
227 QList<QextPortInfo> QextSerialEnumeratorPrivate::getPorts_sys()
228 {
229 QList<QextPortInfo> ports;
230 const int count = sizeof(deviceClassGuids)/sizeof(deviceClassGuids[0]);
231 for (int i=0; i<count; ++i)
232 enumerateDevicesWin(deviceClassGuids[i], &ports);
233 qSort(ports.begin(), ports.end(), lessThan);
234 return ports;
235 }
236
237
238 /*
239 Enable event-driven notifications of board discovery/removal.
240 */
241 bool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool setup)
242 {
243 #ifndef QT_GUI_LIB
244 Q_UNUSED(setup)
245 QESP_WARNING("QextSerialEnumerator: GUI not enabled - can't register for device notifications.");
246 return false;
247 #else
248 Q_Q(QextSerialEnumerator);
249 if (setup && notificationWidget) //already setup
250 return true;
251 notificationWidget = new QextSerialRegistrationWidget(this);
252
253 DEV_BROADCAST_DEVICEINTERFACE dbh;
254 ::ZeroMemory(&dbh, sizeof(dbh));
255 dbh.dbcc_size = sizeof(dbh);
256 dbh.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
257 // dbh.dbcc_classguid = GUID_DEVCLASS_PORTS; //Ignored in such case
258 DWORD flags = DEVICE_NOTIFY_WINDOW_HANDLE|DEVICE_NOTIFY_ALL_INTERFACE_CLASSES;
259 if (::RegisterDeviceNotification((HWND)notificationWidget->winId(), &dbh, flags) == NULL) {
260 QESP_WARNING() << "RegisterDeviceNotification failed:" << GetLastError();
261 return false;
262 }
263 // setting up notifications doesn't tell us about devices already connected
264 // so get those manually
265 foreach (QextPortInfo port, getPorts_sys())
266 Q_EMIT q->deviceDiscovered(port);
267 return true;
268 #endif // QT_GUI_LIB
269 }
270
271 LRESULT QextSerialEnumeratorPrivate::onDeviceChanged(WPARAM wParam, LPARAM lParam)
272 {
273 if (DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam) {
274 PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
275 if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
276 PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
277 // delimiters are different across APIs...change to backslash. ugh.
278 QString deviceID = TCHARToQString(pDevInf->dbcc_name).toUpper().replace(QLatin1String("#"), QLatin1String("\\"));
279
280 const int count = sizeof(deviceClassGuids)/sizeof(deviceClassGuids[0]);
281 for (int i=0; i<count; ++i) {
282 if (matchAndDispatchChangedDevice(deviceID, deviceClassGuids[i], wParam))
283 break;
284 }
285 }
286 }
287 return 0;
288 }
289
290 bool QextSerialEnumeratorPrivate::matchAndDispatchChangedDevice(const QString &deviceID, const GUID &guid, WPARAM wParam)
291 {
292 Q_Q(QextSerialEnumerator);
293 bool rv = false;
294 DWORD dwFlag = (DBT_DEVICEARRIVAL == wParam) ? DIGCF_PRESENT : DIGCF_ALLCLASSES;
295 HDEVINFO devInfo;
296 if ((devInfo = SetupDiGetClassDevs(&guid,NULL,NULL,dwFlag)) != INVALID_HANDLE_VALUE) {
297 SP_DEVINFO_DATA spDevInfoData;
298 spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
299 for(int i=0; SetupDiEnumDeviceInfo(devInfo, i, &spDevInfoData); i++) {
300 DWORD nSize = 0;
301 TCHAR buf[MAX_PATH];
302 if (SetupDiGetDeviceInstanceId(devInfo, &spDevInfoData, buf, MAX_PATH, &nSize) &&
303 deviceID.contains(TCHARToQString(buf))) { // we found a match
304 rv = true;
305 QextPortInfo info;
306 info.productID = info.vendorID = 0;
307 getDeviceDetailsWin(&info, devInfo, &spDevInfoData, wParam);
308 if (wParam == DBT_DEVICEARRIVAL)
309 Q_EMIT q->deviceDiscovered(info);
310 else if (wParam == DBT_DEVICEREMOVECOMPLETE)
311 Q_EMIT q->deviceRemoved(info);
312 break;
313 }
314 }
315 SetupDiDestroyDeviceInfoList(devInfo);
316 }
317 return rv;
318 }