Add a delay method to WinForm application - winforms

I'm using a WinForm app to communicate with a micro processor (Arduino Micro). The MCU's serial port requires a few seconds to become available after calling a 'serialPort1.Open();'. So I need to add some kind of delay of perhaps 2 or 3 seconds before attempting to read from the serial port. In addition, I am sending and receiving commands to the MCU during which time I also require a 100ms delay between serial writes and reads.
I've tried using Thread.Sleep (which of course locks up the form) and various timer methods with no luck. I'd be using this delay often so I'd like to have a method that looks something like this:
Anywhere in my form: invokeTimer(2000); // call a delay method with time in ms
private void invokeDelay(int time)
{
// delay here and do nothing for specified time in milliseconds
}
Simple examples:
serialPort1.Open(); // connect to MCU
invokeDelay(3000); // give MCU time to make serial stream available
// serial stream should now be available so ...
serialPort1.WriteLine("?"); // ask MCU to provide a response
invokeDelay(100); // 10-100ms depending on baud rate of MCU to respond
string response = serialPort1.ReadLine();
Alternatively, I'd be happy with any way of checking if there is serial data available and in this way avoid delays/timers all together. In the Arduino IDE there is a Serial.Available() function, but I don't see anything similar to this in Visual Studio. Otherwise I'd sit in a while loop until a serial stream became available.
Any advice would be most appreciated!

Related

Embedded system: How to identify required tasks/threads?

I'm studying embedded programming, so I'm new in this field.
Can someone explain how to identify tasks/threads from given system description. Also, how can I estimate timing constraints, execution times... I'm really stuck.
Here is system description I'm working on:
Implement a 2 degree of freedom servo motor system. A two-axis joystick is used for controlling servo motors. Additionally, enable recording and reproducing the user path of the joystick, so that identical movement could be replicated multiple times. It is necessary to support the recording of 3 motion profiles with a length of at least 5 minutes. The profile needs to be recorded to a non-volatile memory, and the recording/playback control via the joystick button. Provide appropriate signalling for the current selected profile and operating mode (recording / playback) using one LED for each profile. In the RT-Thread system realize the necessary drivers on the Raspberry Pi Pico platform as support for the devices used and the application itself that implements the described system with clear separated threads for each of the observed functionalities.
It is tempting to partition functionally, but in practice you should partition based on deadlines, determinism and update rates. For simple systems, that may turn out to be the same as a functional partitioning. The part:
clear separated threads for each of the observed functionalities
May lead you to an inappropriate partitioning. However that may be the partitioning your tutor expects even if it is sub-optimal.
There is probably no single solution, but obvious candidates for tasks are:
Joystick reader,
Servo controller,
Recorder,
Replayer.
Now considering these candidates, it can be seen that the joystick control and replay control are mutually exclusive, and also that replay itself is selected through the joystick button. Therefore it makes sense to make that a single task. Not least because the replayer will communicate with the servo controller in the same way as the joystick. So you might have:
Joystick reader / replayer,
Servo controller,
Recorder.
The recorder is necessarily a separate thread because access to NV memory may be slower and non-deterministic. You would need to feed time and x/y position data in a message queue of sufficient length to ensure the recording does not affect the timing motion control.
It is not clear what king of servo you are using or if your application is responsible for the PID motion control or simply sends a position signal to a servo controller. If the latter, there may be no reason to separate teh servo control from the reader/replayer. In which case you would have:
Joystick reader / replayer / Servo controller,
Recorder.
Other solutions are possible. For example the recorder might record the servo position over time rather the joystick position, and have the servo controller handle replay.
Joystick reader,
Servo controller / replayer,
Recorder.
That makes sense if the Joystick polling and Servo update rates differ, because you'd what to replay what the servo did, not what the joystick did.

Using Broadcast State To Force Window Closure Using Fake Messages

Description:
Currently I am working on using Flink with an IOT setup. Essentially, devices are sending data such as (device_id, device_type, event_timestamp, etc) and I don't have any control over when the messages get sent. I then key the steam by device_id and device_type to preform aggregations. I would like to use event-time given that is ensures the timers which are set trigger in a deterministic nature given a failure. However, given that this isn't always a high throughput stream a window could be opened for a 10 minute aggregation period, but not have its next point come until approximately 40 minutes later. Although the calculation would aggregation would eventually be completed it would output my desired result extremely late.
So my work around for this is to create an additional external source that does nothing other than pump fake messages. By having these fake messages being pumped out in alignment with my 10 minute aggregation period, even if a device hadn't sent any data, the event time windows would have something to force the windows closed. The critical part here is to make it possible that all parallel instances / operators have access to this fake message because I need to close all the windows with this single fake message. I was thinking that Broadcast state might be the most appropriate way to accomplish this goal given: "Broadcast state is replicated across all parallel instances of a function, and might typically be used where you have two streams, a regular data stream alongside a control stream that serves rules, patterns, or other configuration messages." Quote Source
Questions:
Is broadcast state the best method for ensuring all parallel instances (e.g. windows) receive my fake messages?
Once the operators have access to this fake message via the broadcast state can this fake message then be used to advance the event time watermark?
You can make this work with broadcast state, along the lines you propose, but I'm not convinced it's the best solution.
In an ideal world I'd suggest you arrange for the devices to send occasional keepalive messages, but assuming that's not possible, I think a custom Trigger would work well here. You can extend the EventTimeTrigger so that in addition to the event time timer it creates via
ctx.registerEventTimeTimer(window.maxTimestamp());
you also create a processing time timer, as a fallback, and you FIRE the window if the window still exists when that processing time timer fires.
I'm recommending this approach because it's simpler and more directly addresses the specific need. With the broadcast state approach you'll have to introduce a source for these messages, add a broadcast state descriptor and stream, add special fake watermarks for the non-broadcast stream (set to Watermark.MAX_WATERMARK), connect the broadcast and non-broadcast streams and implement a BroadcastProcessFunction (that probably doesn't really do anything), etc. It's a lot of moving parts spread across several different operators.

Call back function to be called whenever hardware timer elapses a specified elapse time in STM32F101

Hi I want to toggle LED with timing as follows
100ms ON1, 250ms Off1
1250ms ON2, 1500ms off2
and this cycle gets repeated (Both ON1 off1 and ON2 off2 pair repeats)
For this I have planned to utilize hardware timer with elapsing timings as 100,250,1250 and 1500 and this will repeat.
I am pretty new to the embedded field,
My questions are as follows
How to trigger this using a hardware timer? (How to enable and alternate the timings dynamically?)
How to set a call back function that toggles LED based on the timer elapse ?
Note : This is not a standalone code but an application will
Be running .From OS the callback will be triggered in the background so that other normal application is not affected during this process
Use the OS's software timer service. Create four software timers with the specified periods. The timers should be configured to count once and then stop each time they are started (i.e., they should be "one-shot", not "auto-reloading" nor "continuous" or whatever terminology your OS uses). Each software timer will have a unique callback function that you specify when you create the software timer.
From main, or wherever is appropriate, start the first timer once to get things started. Then start the second timer from the first timer's callback function. And start the third timer from the second timer's callback function. And so on until the last timer's callback function restarts the first timer and the circle of timers repeats.
Use timer interrupt for it.
You have the ready example here:
https://www.diymat.co.uk/arm-blinking-led-driver/
It does what you need and a bit more as well :)

Advice: trying to recognize when a device is not connected

I have some hard time trying to find a method to restart my state machine. In other words some part of what I ve got:
I have a module that when is powered up it stays for a debounce time of 0.5 s and then it goes in a state machine: first it send a string#anotherstring# then he start a timer of some period and when timer elapsed, it converts an analog signal/read a data (SPI,I2C) and sends that data followed by another #. The state machine goes back and start again the timer and send again the data ...
On another chip. I receive info from that module. So here is a state machine that complete the first string, second string, and then cumulates values in a buffer, again and again.
In some moment some external device ask for data, moment when the chip make some computation and sends it.
SO far so good. Every single part of this is working exept the part when the module is disconnected. Ok you may say no problem no data is send. Yes this is true, but what happens if the module is connected back. Until now to test my work I have reseted the chip disconect and connect the module. By doing this the chip is on the first state and the module goes from first state, everything is ok.
My qestion is how to determine when the device is disconected from the chip to restart the chip stat machine and to wait for the string#anotherstring# combination(first state).
Another question is how to determine if the communication is broken and not the power down. When putting back the comunication the data should be again send,preferably both modules to go from init state.
What I have in mind is to send some ack to the module from the chip. But I do not know exactly how. Basically I want this: when the module is disconected its state machine obviously start over and the chip state I want again to goes back to initial state.
if the comunication of the module is unplugged some how both statemachines to start over.
I do not know if I am clear with this. but please if there are questions ask. I will come with edits if I found something.
OTHER INFO: The module and the chip are some microcontrolers, the comunicaiton is UART.
Let me sketch a basic scheme you can use on the receiving side:
On your receiving side, you'll want to time-out if no valid/complete message is received within a reasonable time frame. This way, you'll detect when the module goes offline for whatever reason at any point in time.
The state machine that receives and processes the messages will also be reset in this case. This means you'll have a timer which, for example, is started when data is received and stopped when a message was correctly and fully received. If the timer times out, any message currently being received is declared invalid and discarded, and the receiver goes back to the start, looking for the next message.
Then, you'd have to implement in the receiver the code to detect when a message starts and/or ends. So if the module always starts by sending string#anotherstring# then the receiver will wait until it sees string# for example; anything else received is ignored by the receiver. Only after the expected prefix was detected the rest of the message receiving is done.
During the whole process, the receiver's messsage timeout timer is active and if any part of the message is not received in time the receiver assumes transmission problems and goes back to waiting for the start of the next message.

speedup or mute audio playback in a windows process via hooking calls

I have an application which I do not have source code for that plays back audio but lacks the facility to speed up or temporarily mute audio playback. I am trying to add these two functionalities by injecting a dll and hooking waveOutOpen, waveOutWrite (and either preventing playback or trying to waveOutSetPlaybackRate for mute and speedup respectively). I have a couple of problems however.
Lets first talk about the "mute" button since that was my first order of business:
I will refer to the hooked versions of functions as MyWaveOut...
1)
I am able to hook the functions no problem and I see them being called in dbgView log statements. My first attempt was to just intercept waveOutWrite function calls and if my "mute" button is pressed to just return MMSYSERR_NOERROR in MyWaveOutWrite function and not call the real waveOutWrite. This correctly prevents the audio from playing however I encounter a problem when I turn off the "mute" . The audio does not play again when I disable the mute, in fact the hooked function (nor the real one) is ever called again by the hooked process.
My first suspicion was that I was not calling the callback waveOutProc that is registered by the application when it calls WaveOutOpen. I therefore also hooked the waveOutOpen and kept and switched the address of the waveOutProc to MyWaveOutProc and added logic to call the real waveOutProc before returning the same MMSYSERR_NOERROR in MyWaveOutWrite. This had weird results causing the playback visual to skip forward very fast but then I had the same problem with the audio not returning (MyWaveOutWrite function never called again).
2)
As for the audio speedup portion I tried using waveOutSetPlaybackRate but this simply returned MSYSERR_NOTSUPPORTED so I arrived at a dead end with that. Hooking GetTickCount and QueryPerformanceCounter had no affect on the audio playback at all, the visual playback indicator would skip forward ahead fast if the audio is disabled, but when the audio device is enabled the visual seems even to be bound to the rate of the audio playback.
Any help with with those experienced with either of these problems would be appreciated. I do not usually work with windows audio so it is a bit of a learning experience for me.
Thanks
A suggestion for a different approach.
This assumes the OS is from Vista Kernnel or higher.
In these operation systems there is a pr application volume control, it might be simpler to mute it here then with any hooks.

Resources