#include <windows.h>
#include <setupapi.h>
#include <stdio.h>
#include <devguid.h>
#include <wchar.h>
#define SEARCH_STRINT "Cinterion PLSx3 USB Com Port1 "
int main() {
// Get a handle to a device information set for COM ports
HDEVINFO hdevinfo;
//GUID ClassGuid = {0x4d36e978,0xe325,0x11ce,{0xbf,0xc1,0x08,0x00,0x2b,0xe1,0x03,0x18}};
GUID guid = {0x4d36e978,0xe325,0x11ce,{0xbf,0xc1,0x08,0x00,0x2b,0xe1,0x03,0x18}}; //GUID_DEVCLASS_PORTS
//查到資料大多這樣寫,devguid.h也宣告了
//但mingw64編譯卻一直說找不到GUID_DEVCLASS_USB @@
//所以改用查guid碼方式來避開
//hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_USB, 0, 0, DIGCF_PRESENT);
hdevinfo = SetupDiGetClassDevs((LPGUID)&guid, NULL, NULL, DIGCF_PRESENT );
if (hdevinfo == INVALID_HANDLE_VALUE) {
printf("SetupDiGetClassDevs failed with error code %d\n", GetLastError());
return 1;
}
// Enumerate through the COM ports
SP_DEVINFO_DATA devinfoData;
devinfoData.cbSize = sizeof(SP_DEVINFO_DATA);
SP_DEVICE_INTERFACE_DATA interfaceData;
interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DWORD index = 0;
for(index=0; SetupDiEnumDeviceInfo(hdevinfo, index, &devinfoData); index++)
{
wchar_t friendlyName[128];
if (SetupDiGetDeviceRegistryProperty(hdevinfo, &devinfoData, SPDRP_HARDWAREID, NULL, (BYTE*)friendlyName, sizeof(friendlyName), NULL))
{
// Check if the COM port information matches the USB modem's VID and PID
//printf("friendlyName=%s\n", friendlyName);
char cpy[128];
char comport[COMPORT_SIZE];
strcpy(cpy, (char *)friendlyName);
//printf("%d. cpy=%s\n", (int)index, cpy);
if (strcmp(cpy, SEARCH_STR0))
continue;
if (SetupDiGetDeviceRegistryProperty(hdevinfo, &devinfoData, SPDRP_FRIENDLYNAME, NULL, (BYTE*)friendlyName, sizeof(friendlyName), NULL))
{
strcpy(cpy, (char *)friendlyName);
//printf("%d. cpy=%s\n", (int)index, cpy);
char *p;
p = strtok(cpy, SEARCH_STR2);
for (; p != NULL; )
{
//printf( "pp=%s\n", p );
p = strtok(NULL, "M");
if(p)
strncpy(comport, p, COMPORT_SIZE);
}
}
//printf("p=%s, len=%zu\n", comport, strlen(comport));
comport[strlen(comport)-1]='\0';
//printf("comport=%s\n", comport);
strcpy(com, comport);
//printf("com=%s\n", com);
}
}
// Clean up
SetupDiDestroyDeviceInfoList(hdevinfo);
return 0;
}
Ref: ChatGPT
2023年8月28日 星期一
Search for a specific COM port on Win10
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言