QTextEdit for input and output - c++

I am considering using QTextEdit as console-like IO element (for serial data).
The problem with this approach is that (user) input and (communication) output are mixed and they might not be synchronous.
To detect new user input, it might be possible to store and compare plainText on certain input events, e.g. when Enter/Return is pressed.
Another approach might be to use the QTextEdit as view only for separately managed input and output buffers. This could also simplify the problem of potentially asynchronous data (device sends characters while user is typing, very unlikely in my case).
However, even merging the two "streams" by single-character timestamp holds potential for conflict.
Is there a (simple) solution or should I simply use separate and completely independent input/output areas?

Separate I/O areas is the simplest way to proceed if your UI is command driven and the input is line-oriented.
Alternatively, the remote device can be providing the echo, without a local echo. The remote device will then echo the characters back when it makes sense, to maintain coherent display.
You can also display a local line editing buffer to provide user feedback in case the remote echo was delayed or unavailable. That buffer would be only for feedback and have no impact on other behavior of the terminal; all keystrokes would be immediately sent to the remote device.

Related

Scheduling concept in programming - user input

I am curious how the user input is handled in micro-controllers in way that all other work is not blocked.
For instance, I have modern gas boiler - Vaillant, boiler is running his own tasks while I can scroll in the user menu, press buttons and so on.
How this is worked out from conceptual point of view?
Is there another micro-controller which handles user input and then it pushes selected inputs to main controller?
Or there is just some type of scheduller in main controller and it is scheduling so fast so it can handle user inputs AND background tasks?
How this is handled in general so user can play around with menu and so on without blocking the main task.
Thank You
This can be handled in many different ways and, depending on the complexity of the overall application, it can be as simple as a super-loop, or as complex as a multitasking based application with several independent tasks each doing their own thing (e.g., one doing key press detection, another dealing with serial comms, another updating the [G]LCD, etc.).
Your particular example can easily be handled with the super-loop approach, although a multitasker can also be used for (IMO) simplicity in coding.
For example, with the super-loop approach, each time through the loop you call a key press detection routine which checks if a key is pressed and counts time up to some maximum as long as the key press is still present. It does not block, it exits immediately. When the count reaches a minimum to accept the key (e.g., corresponding to about 50-100 msec) you return the key pressed and zero the counter (for auto key repeat), or save the key in a temporary buffer and return it only when the key is eventually released (if no auto key repeat is desired).
The display works in a similar way. The current screen is updated depending on which state the device is in. When the UP/DOWN key (for example) is detected, the index of the scrolling item changes up or down and the screen is redrawn with the new state.
There are certain situations that a multitasker is the only reasonable way to solve such problems if you don't want your app to become a un-debuggable mess of flags, and ifs. Dealing concurrently (and smoothly) with multiple interfaces (e.g., GPS, GSM, user terminal, key/LCD) is one such example.
BTW, interrupts for key presses are IMO an overkill unless you are in some battery saving sleep mode and need a hardware way to wake up. Human key presses are always too slow by comparison to CPU speeds and can be detected reliably by simple polling.
Most CPUs have some form of interrupts (even the PC).
Basically the interrupt tells the CPU to stop what it is doing and handle some realtime event. When the interrupt handler is complete the CPU will resume its original program.
More detailed information on interrupts is available on wikipedia

win32 raw keyboard input remove autorepeat

So the problem at hand is pretty much the following:
Windows key repeat settings affecting Raw Input messages
Although this might be a duplicate then, there is no answer provided, so here it goes:
I am under the impression that e.g. for FPS game development, one should use raw input. The problem then however, is that the input is not so raw after all and includes a delay (for a continuous keydown) and only after that initial delay a continuous key press, that is continuous flow of WM_INPUT messages. When using DirectInput (which is deprecated), I do not have those problems. Is there a way to achieve the same thing using only raw input? To be clear, what I want is that, if I press a key continuously, I continuously get WM_INPUT messages without the initial delay caused by autorepeat.
I am using the raw input standard read, not the buffered one (https://msdn.microsoft.com/en-us/library/windows/desktop/ms645546(v=vs.85).aspx)
Where is the difference between the aforementioned standard raw input reading and the buffered one?
DirectInput is an outdated, async abstraction layer, that does exactly the same thing: processes raw input. It is not recommended to use it unless you need to support joystick or anything legacy, for gamepads XInput is being recommended.
Windows is not a real time OS, the best option is to stick to WM_INPUT messages. This requires maintaining an array of key states (bool keyState[256]) and basing your logic as if(keyState[VK_BACKSPACE] == true){}.
If you want to also catch the press start and release events, you will have to maintain an array of last key state, and analyzing WM_INPUT check for the change, and produce the press start event only if last state of key was false and WM_INPUT message says key is pressed now.
The other option is to use GetAsyncKeyState to manually check all the input regularly. But that will leave you without the ability to catch key press if it happened between your two calls for GetAsyncKeyState. The documentation of the function says that the lower bit tells exactly that, but that bit is shared among all applications and can be reset by other app, which is sad.
If I understand you correctly, what you want is just the momentary key state, which can be easily obtained through helper classes like Keyboard, it does not use WM_INPUT though, so a minor latency may occur due to window check layer.
auto kb = keyboard->GetState();
if (kb.Back)
// Backspace key is down, with no delay of waiting for key repeat

How to interrupt loop/process using terminal input in C++ on a Linux application

I am writing a Linux command line application that ultimately leads to data acquisition from a piece of hardware. The nature of the data acquisition is that it will feed data to the program consistently at some defined data rate. Once the user enters into RxData (the receive loop), we do not want to stop unless we get a command from the terminal to tell it to stop. The problem I foresee is that using getchar() will hang the loop every iteration of the while loop because the program will expect the user to enter input. Am I wrong in this behavior?
On a side note, I know that when working with embedded devices, you can simply check a register to see if the buffer has increased and use that to determine whether or not to read from the buffer or not. I do not have that luxury on a Linux application (or do I?). Does some such function (let's call it getCharAvailable) which I can run, check if data has been input, and THEN signal my program to stop acquiring data?
I can't simply use SIGINT because I need to signal to the hardware to stop data acquisition as well as add a header to the recorded data. There needs to be a signal to stop acquisition.
In Linux (or any other Unix flavour), you can use select to look if there is available data on 2 (or more) file descriptors, sockets or any other thing that can be read. (It is the reason why this system call exists ...)
use the ncurse library and use getch in non-delay mode

How do I clear user input (cin) that occurred while the process was blocked?

I have a C++ program that takes input from the user on std::cin. At some points it needs to call a function that opens a GUI window with which the user can interact. While this window is open, my application is blocked. I noticed that if the user types anything into my application's window while the other window is open, then nothing happens immediately, but when control returns to my application those keystrokes are all acted upon at once. This is not desirable. I would like for all keystrokes entered while the application is blocked to be ignored; alternatively, a way to discard them all upon the application regaining control, but retaining the capability to react to keystrokes that occur after that.
There are various questions on Stack Overflow that explain how to clear a line of input, but as far as I can tell they tend to assume things like "the unwanted input only lasts until the next newline character". In this case this might not be so, because the user could press enter several times while the application is blocked. I have tried a variety of methods (getline(), get(), readsome(), ...) but they generally seem not to detect when cin is temporarily exhausted. Rather, they wait for the user to continue supplying content for cin. For example, if I use cin.ignore(n), then not only is everything typed while the GUI window was open ignored, but the program keeps waiting afterwards while the user types content until a total of n characters have been typed. That's not what I want - I want to ignore characters based on where in time they occurred, not where in the input stream they occur.
What is the idiom for "exhaust everything that's in cin right now, but then stop looking for more stuff"? I don't know what to search for to solve this.
I saw this question, which might be similar and has an answer, but the answer asks for the use of <termios.h>, which isn't available on Windows.
There is no portable way to achieve what you are trying to do. You basically need to set the input stream to non-blocking state and keep reading as long as there are any characters.
get() and getline() will just block until there is enough input to satisfy the request. readsome() only deals with the stream's internal buffer and is only use to non-blockingly extract what was already read from the streams internal buffer.
On POSIX systems you'd just set the O_NONBLOCK with fcntl() and keep read()ing from file descriptor 0 until the read returns a value <= 0 (if it is less than 0 there was an error; otherwise there is no input). Since the OS normally buffers input on a console, you'd also need to set the stream to non-canonical mode (using tcsetattr()). Once you are done you'd probably restore the original settings.
How to something similar on non-POSIX systems I don't know.

Setting a timeout on ifstream in C++?

We're trying to read data from 2 usb mice connected to a linux box (this data is used for odometry/localization on a robot). So we need to continuously read from each mouse how much it moved. The problem is that when a mouse is not moving, it doesn't send any data, so the file stream from which we get the data blocks execution and therefore the program can't do the odometry calculations (which involve time measurement for speed).
Is there a way to set a timeout on the input stream (we're using ifstream in C++ and read from /dev/input/mouse), so that we're able to know when the mouse doesn't move, instead of waiting for an event to be received? Or do we need to mess up with threads (arggh...)? Any other suggestions are welcome!
Thanks in advance!
A common way to read from multiple file descriptors in linux is to use select(). I suggest starting with the manpage. The basic system flow is as follows:
1) Initialize devices
2) Obtain list of device file descriptors
3) Setup the time out
4) Call select with file descriptors and timeout as parameters - it will block until there is data on one of the file descriptors or the time out is reached
5) Determine why select returned and act accordingly (i.e. call read() on the file descriptor that has data). You may need to internally buffer the result of read until an entire data gram is obtained.
6) loop back to 4.
This can become your programs main loop. If you already have a different main loop you, can run the above without looping, but your will need to insure that the function is called frequently enough such that you do not lose data on the serial ports. You should also insure that your update rate (i.e. 1/timeout) is fast enough for your primary task.
Select can operate on any file descriptor such network sockets and anything else that exposes an interface through a file descriptor.
What you're looking for would be an asynchronous way to read from ifstream, like socket communication. The only thing that could help would be the readsome function, perhaps it returns if no data is available, but I doubt this helps.
Using threads would be the best way to handle this.
Take a look at the boost Asio library. This might help you deal with the threading suggested by schnaeder.
No, there is no such method. You'll have to wait for an event, or create a custom Timer class and wait for a timeout to repoll, or use threads.