Get USB disk drive letter by device path or handle - ioctl

My goal is to write a c-dll (compiled with MinGW) that is able to search for certain models of USB sticks connected to the computer and deliver the serial number, the vendor ID, the product ID and the drive letter.
I have searched on the internet for several hours know but could not find an approach that works for me.
I am using the Setup Api to get a list of all connected USB devices. For each USB device I get a path that looks like this:
\?\usb#vid_048d&pid_1172#00000020370220#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
From that string I can get the vendor ID, product ID and the serial number I am looking for.
My problem is now to determine the drive letter of the USB drive that is related to this device path.
During my internet research I found the following approach multiple times (for example here http://oroboro.com/usb-serial-number/):
Once the device path is found, the USB drive must be opened by CreateFile. The handle returned by that function can be used to get the device number by function DeviceIOControl with IOCTL_STORAGE_GET_DEVICE_NUMBER.
After that, the CreateFile function could be used to open each drive letter (starting from a:) and try to get the device number the same way like described above. Once the same device number is found again, the relation between device path and drive letter is made.
My Problem is that the IOCTL_STORAGE_GET_DEVICE_NUMBER call is not working. The DeviceIOControl function returns error code 50 which means "The request is not supported".
I am not able to create a link between the device path of a USB stick and the drive letter. I have tried several IOCTL_STORAGE and IOCTL_VOLUME calls but none worked for the USB sticks I tried.
I also read in another Forum that people had problems with the results of the DeviceIOControl function. It was returning the desired result on some PCs while it was making trouble on others.
Is there another way of achieving my goal?
I already had a look into the registry where I can also find the desired data. But again I had the problem to create the connection between device path and drive letter.
I would not like to use the WMI. I have read that it is still not really supported by MinGW.
I have a implementaion for all this with C# where it is really easy to get the desired information, but now I also need one that is created with unmanaged code and can be used to replace a c-dll also included in Delphi projects.
I would appreciate any suggestions for a solution to my problem.
Best regards,
Florian
And here the code if someone is interested. The position with this comment "//HERE IS WHERE I WOULD LIKE TO GET THE DEVICE NUMBER!!!" is where the request of the device number would be used if it would work.
typedef struct ty_TUSB_Device
{
PSP_DEVICE_INTERFACE_DETAIL_DATA deviceDetailData;
char devicePath[300];
}TUSB_Device;
int
GetUSBDevices (TUSB_Device *devList[], int size)
{
HANDLE hHCDev;
HDEVINFO deviceInfo;
SP_DEVICE_INTERFACE_DATA deviceInfoData;
ULONG index;
ULONG requiredLength;
int devCount = 0;
//SP_DEVINFO_DATA DevInfoData;
// Now iterate over host controllers using the new GUID based interface
//
deviceInfo = SetupDiGetClassDevs((LPGUID)&GUID_DEVINTERFACE_USB_DEVICE,
NULL,
NULL,
(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
if (deviceInfo != INVALID_HANDLE_VALUE)
{
deviceInfoData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
for (index=0;
SetupDiEnumDeviceInterfaces(deviceInfo,
0,
(LPGUID)&GUID_DEVINTERFACE_USB_DEVICE,
index,
&deviceInfoData);
index++)
{
SetupDiGetDeviceInterfaceDetail(deviceInfo,
&deviceInfoData,
NULL,
0,
&requiredLength,
NULL);
//allocate memory for pointer to TUSB_Device structure
devList[devCount] = malloc(sizeof(TUSB_Device));
devList[devCount]->deviceDetailData = GlobalAlloc(GPTR, requiredLength);
devList[devCount]->deviceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
SetupDiGetDeviceInterfaceDetail(deviceInfo,
&deviceInfoData,
devList[devCount]->deviceDetailData,
requiredLength,
&requiredLength,
NULL);
//open the usb device
hHCDev = CreateFile(devList[devCount]->deviceDetailData->DevicePath,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
// If the handle is valid, then we've successfully found a usb device
//
if (hHCDev != INVALID_HANDLE_VALUE)
{
strncpy(devList[devCount]->devicePath, devList[devCount]->deviceDetailData->DevicePath, sizeof(devList[devCount]->devicePath));
//HERE IS WHERE I WOULD LIKE TO GET THE DEVICE NUMBER!!!
CloseHandle(hHCDev);
devCount++;
}
//GlobalFree(devList[devCount]->deviceDetailData);
}
SetupDiDestroyDeviceInfoList(deviceInfo);
}
return devCount;
}

I found out what my problem was. From what I read on the internet it seems there where other people having the same problems like me, so I will post my solution.
The whole point is that there are obviously different path values one can obtain for a USB device using the SetupApi. All path values can be used to get a handle to that device, but there are obviously differences about what can be done with the handle.
My failure was to use GUID_DEVINTERFACE_USB_DEVICE to list the devices. I found out that when I use GUID_DEVINTERFACE_DISK, I get a different path value that lets me request the device number. That way I am able to get the link to the drive letter.
That path value obtained with GUID_DEVINTERFACE_DISK also contains the serial number but not the vendor and product IDs. But since both path values do contain the serial, it is no problem to get them both and build the relation.
I tested the code with Windows XP, 7 and 8 and it works fine. Only the FileCreate code of the code sample above must be adjusted (replace GENERIC_WRITE by 0). Otherwise Administrator rights or compatibility mode are required.
I did not try to find out what these different GUID values really stand for. Someone with a deeper knowledge in this area could probably provide a better explanation.
Best regards,
Florian

Related

Domino Mailbox tool hung with NAMELookup2

We have developed the tools to read the emails from the Domino mailboxes and write those into the separate file in local disk(Its look like a backup). Recently we have created a new domino 9 test environment with our lab. But, our tools not working properly with our new domino work environment. To identify the problem about this issue, I have added some debug logs and it seems to look like the control hanged with the function "NAMELookup2". Here, I have added the code snippet,
DHANDLE hLookup;
char *pLookup;
if (NAMELookup2("Local", 0, 1, "$users", 1, dominoUser, 2, "FullName", &hLookup) == NOERROR) // hunged with this line
{
pLookup = (char *) OSLockObject(hLookup);
}
The same tool working fine with our other test environment. So, I think there is no problem with the code. I suspect that maybe the problem with our new work environment setup creation, or maybe missed to provide some kind permission to the users, or maybe I missed to add the mailboxes somewhere, etc.
Note:
I have run the tool with admin privilege user.
It would be great if anyone gives some direction on this.
Thanks,
See this NAMELookup2 page for reference. The function is declared as:
STATUS LNPUBLIC NAMELookup2(const char far *ServerName, DWORD Flags,
WORD NumNameSpaces, const char far *NameSpaces,
WORD NumNames, const char far *Names,
WORD NumItems, const char far *Items,
DHANDLE far *rethBuffer);
where NumItems is the number of null-terminated item names starting at the Items address. The code snippet in your question is passing a single item name ("FullName"), but is setting NumItems to 2. That is clearly wrong and could explain the hang. NumItems should be 1.
I am also suspicious of the ServerName argument. The documentation recommends passing NULL when you want to do a local lookup. Passing "Local" may be another way to accomplish the same, but you need to change your code in any case. I recommend changing the first argument to NULL.

Psychopy and pylink example

I'm working on integrating an experiment in psychopy with the eyelink eyetracking system. The way to do this seems to be through pylink. Unfortunately I'm really unfamiliar with pylink and I was hoping there was a sample of an experiment that combines the two. I haven't been able to find one. If anyone would be able to share an example or point me towards a more accessible manual than the pylink api that sr-research provides I'd be really grateful.
Thanks!
I am glad you found your solution. I have not used iohub, but we do use psychopy and an eyelink and therefore some of the following code may be of use to others who wish to invoke more direct communication. Note that our computers use Archlinux. If none of the following makes any sense to you, don't worry about it, but maybe it will help others who are stumbling along the same path we are.
Communication between experimental machine and eye tracker machine
First, you have to establish communication with the eyelink. If your experimental machine is turned on and plugged into a live Eyelink computer then on linux you have to first set your ethernet card up, and then set the default address that Eyelink uses (this also works for the Eyelink 1000 - they kept the same address). Note your ethernet will probably have a different name than enp4s0. Try simply with ip link and look for something similar. NB: these commands are being typed into a terminal.
#To set up connection with Eyelink II computer:
#ip link set enp4s0 up
#ip addr add 100.1.1.2/24 dev enp4s0
Eyetracker functions
We have found it convenient to write some functions for talking to the Eyelink computer. For example:
Initialize Eyetracker
sp refers to the tuple of screenx, screeny sizes.
def eyeTrkInit (sp):
el = pl.EyeLink()
el.sendCommand("screen_pixel_coords = 0 0 %d %d" %sp)
el.sendMessage("DISPLAY_COORDS 0 0 %d %d" %sp)
el.sendCommand("select_parser_configuration 0")
el.sendCommand("scene_camera_gazemap = NO")
el.sendCommand("pupil_size_diameter = %s"%("YES"))
return(el)
NB: the pl function comes from import pylink as pl. Also, note that there is another python library called pylink that you can find on line. It is probably not the one you want. Go through the Eyelink forum and get pylink from there. It is old, but it still works.
Calibrate Eyetracker
el is the name of the eyetracker object initialized above. sp screen size, and cd is color depth, e.g. 32.
def eyeTrkCalib (el,sp,cd):
pl.openGraphics(sp,cd)
pl.setCalibrationColors((255,255,255),(0,0,0))
pl.setTargetSize(int(sp[0]/70), int(sp[1]/300))
pl.setCalibrationSounds("","","")
pl.setDriftCorrectSounds("","off","off")
el.doTrackerSetup()
pl.closeGraphics()
#el.setOfflineMode()
Open datafile
You can talk to the eye tracker and do things like opening a file
def eyeTrkOpenEDF (dfn,el):
el.openDataFile(dfn + '.EDF')
Drift correction
Or drift correct
def driftCor(el,sp,cd):
blockLabel=psychopy.visual.TextStim(expWin,text="Press the space bar to begin drift correction",pos=[0,0], color="white", bold=True,alignHoriz="center",height=0.5)
notdone=True
while notdone:
blockLabel.draw()
expWin.flip()
if keyState[key.SPACE] == True:
eyeTrkCalib(el,sp,cd)
expWin.winHandle.activate()
keyState[key.SPACE] = False
notdone=False
Sending and getting messages.
There are a number of built-in variables you can set, or you can add your own. Here is an example of sending a message from your python program to the eyelink
eyelink.sendMessage("TRIALID "+str(trialnum))
eyelink.startRecording(1,1,1,1)
eyelink.sendMessage("FIX1")
tFix1On=expClock.getTime()
Gaze contingent programming
Here is a portion of some code that uses the eyelink's most recent sample in the logic of the experimental program.
while notdone:
if recalib==True:
dict['recalib']=True
eyelink.sendMessage("RECALIB END")
eyelink.startRecording(1,1,1,1)
recalib=False
eventType=eyelink.getNextData()
if eventType==pl.STARTFIX or eventType==pl.FIXUPDATE or eventType==pl.ENDFIX:
sample=eyelink.getNewestSample()
if sample != None:
if sample.isRightSample():
gazePos = sample.getRightEye().getGaze()
if sample.isLeftSample():
gazePos = sample.getLeftEye().getGaze()
gazePosCorFix = [gazePos[0]-scrx/2,-(gazePos[1]-scry/2)]
posPix = posToPix(fixation)
eucDistFix = sqrt((gazePosCorFix[0]-posPix[0])**2+(gazePosCorFix[1]-posPix[1])**2)
if eucDistFix < tolFix:
core.wait(timeFix1)
notdone=False
eyelink.resetData()
break
Happy Hacking.
rather than PyLink, you might want to look into using the ioHub system within PsychoPy. This is a more general-purpose eye tracking system that also allows for saving data in a common format (integrated with PsychoPy events), and provides tools for data analysis and visualisation.
ioHUb is built to be agnostic to the particular eye tracker you are using. You just need to create a configuration file specific to your EyeLink system, and thereafter use the generic functions ioHiv provides for calibration, accessing gaze data in real-time, and so on.
There are some teaching resources accessible here: http://www.psychopy.org/resources/ECEM_Python_materials.zip
For future readers, I wanted to share my library for combining pylink and psychopy. I've recently updated it to work with python 3. It provides simple to use, high level functions.
https://github.com/colinquirk/templateexperiments/tree/master/eyelinker
You could also work at a lower level with the PsychoPyCustomDisplay class (see the pylink docs for more info about EyeLinkCustomDisplay).
For an example of it in use, see:
https://github.com/colinquirk/ChangeDetectionEyeTracking
(At the time of writing, this experiment code is not yet python 3 ready, but it should still be a useful example.)
The repo also includes other modules for creating experiments and recording EEG data, but they are not necessary if you are just interested in the eyelinker code.

How to get author of a pdf document with mupdf

how can I get metadata of a pdf document(e.g. title, author, creation date etc) by using mupdf library? There is not enough documentation to find out this functionality. Comments are not sufficient, too. Most probably, there is a functionality for this purpose but it is hard to find under these circumstances. The following code is what I have so far.
char info[64];
globals *glo = get_globals(env, thiz);
fz_meta(glo->doc, FZ_META_INFO, info, sizeof(info));
I have used FZ_META_INFO tag, but it doesn't work. I didn't get any info, just empty. I have checked that it has metadata. Any help is appreciated.
EDIT:
Target Android sdk:20
Min Android sdk:15
Mupdf version: 1.6
ndk: r10c
Development OS: Ubuntu 12.04
In what sense 'doesn't work' ? Throws an error ? Crashes ? Are you certain the PDF file you are using has any 'Info' metadata ?
What is the version of MuPDF ? What platform are you using ?
You need to set the relevant key in the buffer you pass to fz_meta before you call fz_mets, I notice you aren't doing that.
See win_main.c at around line 487, after you get past the macro this resolves to
char info[256]
sprintf(info, "Title");
fz_meta(doc, FZ_META_INFO, info, 256);
On return 'info' will contain the metadata associated with the Title key in the dictionary.
When in doubt, build the sample app and follow it in a debugger......
If the proper casting allow to send the key,
this casting is NOT correct to receive back a char*.
Exemple;
Proper casting to send a request
char buff[2048];
strcpy(buff,"CreationDate")
if (fz_meta(ctx,doc,FZ_META_INFO,&buff,2048)) {
buff[0] = 0;
}
Will:
find the key,
convert utf8
then will crash when copyback of the result
Proper casting to receive a request
char buff[2048];
strcpy(buff,"CreationDate")
if (fz_meta(ctx,doc,FZ_META_INFO,buff,2048)) {
buff[0] = 0;
}
Will crash during dict scanning.
looks really like a bug!
I confirm that modifying original source
info = pdf_dict_gets(ctx, info, (char *)ptr);
is the way to go. (even if strange that nobody else find it while writing code, because Meta are useful features frequently used

How to get notifications when the headphones are plugged in/out? Mac

I'd like to get notified when headphones are plugged in or out in the headphone jack.
I've searched around for this on stackoverflow but I can't seem to find what I'm looking for for the Mac, I can only find for iOS.
So, do you have any ideas on how to perform this? What I want to do with this is: when headphones are plugged out I want to programmatically pause iTunes (iOS-like feature).
Thank you!
You can observe changes using the CoreAudio framework.
Both headphones and the speakers are data sources on the same audio output device (of type built-in). One of both will be on the audio device based on headphones being plugged in or not.
To get notifications you listen to changes of the active datasource on the built-in output device.
1. Get the built-in output device
To keep this short we'll use the default output device. In most cases this is the built-in output device. In real-life applications you'll want to loop all available devices to find it, because the default device could be set to a different audio device (soundflower or airplay for example).
AudioDeviceID defaultDevice = 0;
UInt32 defaultSize = sizeof(AudioDeviceID);
const AudioObjectPropertyAddress defaultAddr = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultAddr, 0, NULL, &defaultSize, &defaultDevice);
2. Read its current data source
The current datasource on a device is identified by an ID of type UInt32.
AudioObjectPropertyAddress sourceAddr;
sourceAddr.mSelector = kAudioDevicePropertyDataSource;
sourceAddr.mScope = kAudioDevicePropertyScopeOutput;
sourceAddr.mElement = kAudioObjectPropertyElementMaster;
UInt32 dataSourceId = 0;
UInt32 dataSourceIdSize = sizeof(UInt32);
AudioObjectGetPropertyData(defaultDevice, &sourceAddr, 0, NULL, &dataSourceIdSize, &dataSourceId);
3. Observe for changes to the data source
AudioObjectAddPropertyListenerBlock(_defaultDevice, &sourceAddr, dispatch_get_current_queue(), ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses) {
// move to step 2. to read the updated value
});
Determine the data source type
When you have the data source id as UInt32 you can query the audio object for properties using a value transformer. For example to get the source name as string use kAudioDevicePropertyDataSourceNameForIDCFString. This will result in the string "Internal Speaker" or "Headphones". However this might differ based on user locale.
An easier way is to compare the data source id directly:
if (dataSourceId == 'ispk') {
// Recognized as internal speakers
} else if (dataSourceId == 'hdpn') {
// Recognized as headphones
}
However I couldn't find any constants defined for these values, so this is kind of undocumented.
I was looking for a similar solution and found AutoMute in the app store. It works well.
I'm also working on some scripts of my own, and wrote this script to test if headphones are plugged in:
#!/bin/bash
if system_profiler SPAudioDataType | grep --quiet Headphones; then
echo plugged in
else
echo not plugged in
fi

Net use: How can I connect to a network share?

(using vb.net)
How can I connect to a network share without using System.Diagnostics.Process.Start?
I need to connect to a network share and get feedback if it already exists.
Can I use some kind of API?
Use a native call to mpr.dll to add a connection
http://pinvoke.net/default.aspx/mpr/WNetAddConnection2.html
You provide the function with the localname (aka diskletter) and remotename (the \server\sharename) in the NETRESOURCE class
A return value of 0 means success, a value of (among many others)
const int ERROR_ALREADY_ASSIGNED = 85,
(see http://msdn.microsoft.com/nl-be/library/aa385413(v=VS.85).aspx)
means the localname is already in use. If you want to find out if the remotename is already assigned you have to enumerate over the current mappings with the WNetEnumResource
http://pinvoke.net/default.aspx/mpr.WNetEnumResource