Modify time until DBT_DEVICEREMOVECOMPLETE is sent - c++

Is there a way to trigger the USB Device Discovery of Windows, such that removed devices are detected faster?
I have a USB Serial modem that I unplug (the USB plug, not the serial one). I want to detect the DBT_DEVICEREMOVECOMPLETE event which is sent as soon as the unplugging is detected (That's what I assume). The detection of the Event works as desired, it is sent sometimes 1s after removal, sometimes several minutes after removal.
Is there a way to decrease the refresh interval, or another way to make this event getting sent faster?

Well, the problem here is that DBT_DEVICEREMOVECOMPLETE is sent after Windows decides it has detected the removal, and you can't influence that, at least not in the general case. There are various things that make Windows do this faster or slower (type of device, current "data flow" with the device, the device itself), and it also varies between OS versions. What I found helps to some degree in some of cases is to remove, from the Registry, references to USB devices that were plugged into that USB port before (there are various utilities for this).
At the extreme, since this is a Windows Broadcast message (non-queued), there will not be another one sent in until the previous is processed. Thus, you may not receive it at all! To solve that, keep message handling fast and simple and don't set a breakpoint there while debugging.
Also, having a separate Windows and Thread for the specific purpose of handling USB device arrival/removal notifications may help.
But, from my experience, polling will not help, as the main problems seems to be in the criteria Windows uses to detect the removal. The time from that event until you receive the message is small. Of course, in your case this may not be true - to find out, use a tool like SysInternals Process Monitor. Depending on what you see going on there, there may be something you can do to make it faster.

Related

Hook and block globally mouse in X11

I need to hook globally mouse clicks and block last click if delay between two clicks is less than was set.
I wrote it for windows using WM_MOUSE_LL hook.
I was unable to find any solution for me. Is it even possible to globally block mouse click in X11 ?
Windows full code
As far as I know the standard X11 protocol doesn't allow this. The XInput 2.0 extension might, but I doubt it.. while Windows assumes a single event queue that every program listens to, so that a program can intercept an event and prevent it from being sent down the queue to other listeners, every X11 client has its own independent queue and all clients that register interest in an event receive an independent copy of it in their queue. This means that under normal circumstances it's impossible for an errant program to block other programs from running; but it also means that, for those times when a client must block other clients, it must do a server grab to prevent the server from processing events for any other client.
Which means you can either
use an X server proxy (won't be hard, but will be pretty slower)
or
do it on the input device level. /dev/input/event<n> give you the input events. You can read off the keypresses there and decide if they should propagate further be consumed. Unfortunately there's no real documentation for this, but the header file linux/include/input.h is quite self explanatory.

CreateMasteringVoice randomly throws HRESULT: 0x88890017

m_audioEngine->CreateMasteringVoice(
&m_masteringVoice,
XAUDIO2_DEFAULT_CHANNELS,
sampleRate,
0,
NULL
)
);
m_audioEngine->CreateSourceVoice(
&implData->sourceVoice,
format,
0,
XAUDIO2_DEFAULT_FREQ_RATIO,
reinterpret_cast<IXAudio2VoiceCallback*>(&implData->callbackHander),
nullptr,
nullptr
)
);
One of the above code when I have my earphones in seems to always run fine.
If I start my game without earphones in, sometimes (not always) the above function fails. It always throws the same HRESULT: 0x88890017
any ideas?
If I put a breakpoint directly after this, it seems to not throw an error... Does this task run asynchronously?
EDIT---------------------------------
My IXAudio2SourceVoice keeps getting lost randomly
what can cause that to lose itself?
this is why my program crashes...
it only loses itself when earphones are not plugged in (when creating XAudio2 objects)
What does it mean?
This error code is known as "*AUDCLNT_E_CPUUSAGE_EXCEEDED*" and occurs when the audio engine is taking too long to process audio packets. This typically occurs when the CPU-usage of the audio engine exceeds a certain treshold. The audio engine will fail creating new streams if its CPU-usage exceeds this threshold.
Resolving: The User
CPU-usage is subject to various things, like the processing power of your CPU, like the number of channels you're using and like the audio device enhancements you have enabled on a system level. Some possible solutions are to ensure a decent CPU (check the minimum system requirements specification), in the application/game-settings lower the amount of channels in use, or to disable some system-level audio device enhancements in your operating system. For the latter check your task manager for CPU-usage, and if one of the suspicious processes is "audiodg.exe", go into the Sound control panel, double-click each of your playback devices in turn, go to the Enhancements tab, and check the "disable all enhancements" box. This should lower the required CPU-usage and solve your problem.
Resolving: The Coder
Keep in mind that the more your audio code is doing, the more CPU-cycles it will require. If you have an IXAudio2 device created with a ton of effect processors in the chain, 1000 SubmixVoices and hundreds of SourceVoices, that's like asking for trouble. Before you point your fingers to the CPU or to the system-level audio device enhancements, do ensure that it isn't just your code being inefficient.
Your big friend here is IXAudio2::GetPerformanceData, which will query the device and fill in a XAUDIO2_PERFORMANCE_DATA-structure for you. This gives you some information about the CPU-cycles used. Chances are good you can intercept this error before it actually occurs. When you detect a heavy CPU-usage, or when the error actually occurs, it's not necessarily a reason to have things fail in your game/engine/framework. You could retry. Or you could adjust the number of SubmixVoices. Or you could choose to not create a SourceVoice. Or you could temporarily suspend audio/switch to a null-device, and inform the user about all of this.
You could setup an event or callback to inform the user of heavy CPU-usage in the audio engine. This enables the application to inform the user of this heavy CPU-usage, and inform the user to lower the amount of channels in the settings (alternatively you can have your application adjust things automatically) or to turn off some system-level audio device enhancements.

"Serial transmit complete"-Interrupt RS485 [BeagleBoneBlack - Angstrom]

I am developing an application on a BeagleBoneBlack. Embedded linux is quite new for me =/
The problem I am facing is that I want to implement a RS485 communication,
I wrote a piece of C++-Code by using the SeriaLib-Library, for the moment a dedicated GPIO is used to toggle the direction of the RS485 interface. All has been fine till this point.
To write a message the function write is used a below
write(fd,Message,Lenght);
The only problem is to toggle the DIRECTION-Pin immediately after the last byte is written on the BUS =(
While developing on microcontrollers its no problem to react on various interrupts and so on.
Is there any solution - deep in the kernel? - to toggle a pin DIRECT after the succesful transmit of the message?
Normally on a small microcontroller upon fifoing the last character you can either enable a transmission complete interrupt, or just busy wait on the transmit complete flag in your send routine, then disable the driver.
However, some heavier-weight MCU's don't have a transmission complete interrupt, and a multitasking OS may dislike busy waiting (and introduce undesired latency if you yield between polls). Two ways of dealing with that come to mind.
Since you have a driver to disable, it sounds like you have a single bidirectional pair, and will receive everything you transmit. Coupled with some state tracking, you could then use the receive interrupt to know that your last character has been sent, and disable the driver. (Also handle RX errors if somebody else jams the bus)
Determine the baudrate-dependent time from enqueueing the last character until transmission complete, and set a timer interrupt for that amount of time, then disable the driver in the ISR.

Getting notification that the serial port is ready to be read from

I have to write a C++ application that reads from the serial port byte by byte. This is an important need as it is receiving messages over radio transmission using modbus and the end of transmission is defined by 3.5 character length duration so I MUST be able to get the message byte by byte. The current system utilises DOS to do this which uses hardware interrupts. We wish to transfer to use Linux as the OS for this software, but we lack expertise in this area. I have tried a number of things to do this - firstly using polling with non-blocking read, using select with very short timeout values, setting the size of the read buffer of the serial port to one byte, and even using a signal handler on SIGIO, but none of these things provide quite what I require. My boss informs me that the DOS application we currently run uses hardware interrupts to get notification when there is something available to read from the serial port and that the hardware is accessible directly. Is there any way that I can get this functionality from a user space Linux application? Could I do this if I wrote a custom driver (despite never having done this before and having close to zero knowledge of how the kernel works) ??. I have heard that Linux is a very popular OS for hardware control and embedded devices so I am guessing that this kind of thing must be possible to do somehow, but I have spent literally weeks on this so far and still have no concrete idea of how best to proceed.
I'm not quite sure how reading byte-by-byte helps you with fractional-character reception, unless it's that there is information encoded in the duration of intervals between characters, so you need to know the timing of when they are received.
At any rate, I do suspect you are going to need to make custom modifications to the serial port kernel driver; that's really not all that bad as a project goes, and you will learn a lot. You will probably also need to change the configuration of the UART "chip" (really just a tiny corner of some larger device) to make it interrupt after only a single byte (ie emulate a 16450) instead of when it's typically 16-byte (emulating at 16550) buffer is partway full. The code of the dos program might actually be a help there. An alternative if the baud rate is not too fast would be to poll the hardware in the kernel or a realtime extension (or if it is really really slow as it might be on an HF radio link, maybe even in userspace)
If I'm right about needing to know the timing of the character reception, another option would be offload the reception to a micro-controller with dual UARTS (or even better, one UART and one USB interface). You could then have the micro watch the serial stream, and output to the PC (either on the other serial port at a much faster baud rate, or on the USB) little packages of data that include one received character and a timestamp - or even have it decode the protocol for you. The nice thing about this is that it would get you operating system independence, and would work on legacy free machines (byte-by-byte access is probably going to fail with an off-the-shelf USB-serial dongle). You can probably even make it out of some cheap eval board, rather than having to manufacture any custom hardware.

How do event listeners work?

Do they repeatedly check for the condition and execute if the condition is met. Ex, how the OS knows exactly when a USB device is plugged in, or how MSN knows exactly when you get an email. How does this work?
Thanks
At the low level, the OS kernel "knows" when something happens, because the device in question sends the CPU a hardware interrupt.
So when, say a network packet arrives, the network controller sends an interrupt, and the OS kernel responds as appropriate.
At the program level, it works quite differently - most application programs run an "event loop", where they fetch a message (say, a message from the OS saying that "the mouse was clicked on this point in your application"), perform the appropriate actions in response to that, and then, listen for more messages. If there is no message, the OS sleeps the thread until it has a message to deliver.
Take a look at Interrupts this should explain how the hardware initiates certain 'events'
Depends.
Often an event listener is registered with the object that generates the event. When the event occurs, the object iterates through all listeners registered with it informing them of the event. Have a look at the AWT/Swing event model in Java for example.
ow the OS knows exactly when it gets a USB
At a low level I suspect thats a hardware interupt (someone correct me if I'm mistaken) which is handled by the kernel/USB driver. There's often higher level systems (e.g. DBUS) that listen for this and have event listeners listening to them.
or how MSN knows exactly when you get an email.
I suspect that's a simple case of polling the mail box (e.g. over POP3) every x seconds and checking the message count (could be wrong though).
Anon. explains the difference between hardware interrupts and software level event listening quite well.
Programs like email checkers will usually be running background services that query their email server every X period checking for new mail. There are other ways of doing it, but for software level events, it's almost certainly going to be something like that.