Is it possible to send CAN messages out of a callback function? - matlab

I have following problem: I would like to send CAN messages out of a callback function. This callback function is called by an timerobject. Everytime when the callback function is executed it should send the CAN message.
I coded:
canch = canChannel('PEAK-System', 'PCAN_USBBUS1');
configBusSpeed(canch, 1000000)
start(canch)
canch.Database = canDatabase('\\psf\Home\Desktop\02 CAN DBC\CAN4.dbc');
message = canMessage (canch.Database,'IPSS_RX_1_1ms');
transmitPeriodic(canch,message, 'On', 0.01);
T= timer('ExecutionMode','fixedrate','Period',0.2,...
'TimerFcn',#TEST_timer_callback_fcn,'StopFcn','disp(''Timer has stopped'')');
start(T)
Callback function:
function TEST_timer_callback_fcn(src,event)
message.Signals.In_ti= 39;
The CAN Channel starts - but the message is not send.
Can somebody help?

It's likely that your timer function simply doesn't have access to the message object (i.e. it exists in a different scope). One option is to nest your timer function within a function where you initialize message. Alternatively, you can pass message to your timer function. You could do this by changing the timer creation line to this:
T = timer('ExecutionMode','fixedrate','Period',0.2,...
'TimerFcn',#(~,~) TEST_timer_callback_fcn(message),...
'StopFcn','disp(''Timer has stopped'')');
And the callback function to this:
function TEST_timer_callback_fcn(message)
message.Signals.In_ti= 39;

Related

How to cancel a tokio tcp connecting gracefully?

When we connect to a remote host via tcp, it can be a time-consuming operation. And while waiting for a connection, the user may cancel the operation at any time.
When connecting using async tokio, TcpStream::connect() returns a Future<TcpStream, io::Error> object, assumed to be called tcps_ft.
There are two parts, one is the normal logic of the program, which should call .awati() on tcp_ft above, and the other part is the UI of the program, where the user wants to call drop(tcps_ft) if he clicks the cancel button. But this seems impossible to do, because both calls consume tcps_ft.
#[tokio::test]
async fn test_cancel_by_drop() {
let addr = "192.168.1.100:8080";
let tcps_ft = TcpStream::connect(addr);
let mut tcps = tcps_ft.await.unwrap();
// simulate user's operation.
let cancel_jh = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
drop(tcps_ft); // can not compile:: tcps_ft moved when await
});
// simulate user's program
tcps.shutdown().await;
cancel_jh.await;
}
So I considered using Task to do it, after all the Task::abort() function will not consume the atjh: Future<JoinHandle> object corresponding to this task. But I still can't call atjh.await before abort() returns synchronously, and in any case, await will consume the variable, making it impossible to call abort() asynchronously. (In other words, the call to abort() must be executed synchronously before await.)
#[tokio::test]
async fn test_cancel_by_abort() {
let addr = "192.168.1.100:8080";
let atjh = tokio::spawn(async move { TcpStream::connect(addr).await.unwrap() });
// simulate user's operation.
let cancel_jh = tokio::spawn(async {
tokio::time::sleep(Duration::from_millis(100)).await;
&atjh.abort();
});
// simulate user's program
let mut tcps = atjh.await.unwrap(); // can not compile:: atjh moved when await
tcps.shutdown().await;
cancel_jh.await;
}
Of course, one less direct way is to use callback functions. In my asynchronous connection task, when connect().await returns, the user's callback function is called to notify the user to call atjh.await.
But here the callback function is introduced again, and I know await/async itself is designed to solve the callback hell problem.
Further, for user-supplied asynchronous callback functions, the compiler may impose very many requirements, such as implementing Send, avoiding cross-thread safety issues, etc. This is certainly not something that async would like to encounter.
How can I do it asynchronously and gracefully to cancel this asynchronous connection process? Is there a suggested model to handle it?

Awaiting the same method (passed as a parameter) twice

I'm trying to write a method inside a package I'm currently developing but I got stuck trying to await the same method a second time.
This is the pseudo code for my method:
Future<MyResultClass> ErrorHandlingMethod(Future<MyResultClass> MyMethod) async {
MyResultClass result = await MyMethod;
(if result.failed && result.cause.canBeFixed){
...
...
// Do something that may cause MyMethod to complete successfully
...
...
result = await MyMethod;
}
return result;
}
MyMethod (a DIO request with a bunch of interceptors) completes but the server returns an error code, now in some cases I can fix whatever caused the problem so after doing that I want to make the same call again and return the new result.
The problem is the second time I'm awaiting MyMethod it returns the result I got the first time without making a new DIO request.
The real code is a little more complicated than this but this is the main problem I'm having right now.
Does anyone know how can I force MyMethod to be actually executed again?
Thanks in advance for your help

Implement typing delay in ScalaJS?

I have a search input field in a ScalaJS app that fires off requests to a backend server whilst the user types in a city name. However, I need to implement a delay so that the request is not fired until after a certain delay (say 1000ms). Without such a delay, there is the chance that I'll get back false positives on the search (E.G. If the user wants to search for "paris", then there will be a false hit on "par" - a small town in Cornwall, England - when the third character is entered)
I've tried transcribing the JavaScript equivalent into Scala, but the setTimeout part doesn't seem to work.
import scala.scalajs.js.timers.{SetTimeoutHandle, clearTimeout, setTimeout}
private def delay = () => {
// Set initial timeout to do nothing after 0 ms
var handle: SetTimeoutHandle = setTimeout(0)(() => {})
(fn: Function0[Unit], ms: Double) => {
clearTimeout(handle)
handle = setTimeout(ms)(fn)
}
}
Then I'm handling the user input event using an Akka Actor
def receive = {
/************************************************
* Client event
* The user has typed something into the search field
*/
case evt: Event =>
delay()(handleInput, 1000.0)
}
Where handleInput is the zero parameter function that obtains the user's input and then fires off a request to the backend.
The anonymous inner function that clears and then resets the timeout is executed, but the handleInput function never gets called
Thanks
Chris W
The problem in your code is that you are giving a function of type () => Unit to setTimeout, but setTimeout takes a by-name parameter. In other words, the argument to setTimeout should be a statement to execute when the timeout expires. If you give it a function, then after the timeout that function value will be evaluated, but the function will not be called!
It is similar to mistakenly trying to do
val result = fn // result is the *function* itself, but does not call it
instead of
val result = fn() // fn is called, result is what it returns
You can fix your call to setTimeout by replacing fn by fn(). Also, it is typically more idiomatic, in those circumstances, to use {} instead of () for the parameter to setTimeout, which also gives a visual clue that it is a by-name parameter:
(fn: Function0[Unit], ms: Double) => {
clearTimeout(handle)
handle = setTimeout(ms) {
fn()
}
}
You should also adapt your first dummy setTimeout for consistency, although since it is a dummy anyway, that will not change the behavior:
// Set initial timeout to do nothing after 0 ms
var handle: SetTimeoutHandle = setTimeout(0) {}

rxjs: Can an Observable implementation invoke onNext on the same thread of execution?

In ReactiveX an Observable might invoke
the following methods
onNext
onError
onCompleted
according to a very clear contract http://reactivex.io/documentation/contract.html
I am writing the code for the Observable and I have realized that under certain circumstances I might invoke onNext within the same thread of execution.
Is that a mistake ?
For example, if I have code like this:
// call onNext twice on the same thread execution.
o.onNext(event1);
o.onNext(event2);
Should I rewrite it like this:
// call onNext and then schedule the next call via setTimeout
o.onNext(event1);
setTimeout(function() { o.onNext(event2); },0);
= = = = = = = =
Clarification: why am I asking ?
In a browser, let's imagine the observer wants to update an HTML element with the content of onNext then if it is called serially that code would not work.
function onNext() {
count++;
htmlElement.innerHTML = 'count:'+count; // <-- this will work only if onNext is invoked on different thread of executions.
}

Protractor controlflow scheduler not handling anonymous function declaration and execution in thenable manner

Here is example code:
//some code in "OuterFunction"
var outterProm = protractor.promise.Deferred();
(function doMore(arg){
var innerProm = protractor.promise.Deffered();
callSomeFunctionWhichReturnsPromise().then(function(value){
//code to process value
innerProm.fulfill();
};
return innerProm;
})("something").then(function(){
outterProm.fulfill();
});
I am observing that protractor schedules and then begins executing OutterFunction but when it comes across the doMore function declaration (during OutterFunction execution) it schedules doMore, but not executes doMore... resulting in then attempting to continue exec of OutterFunction resulting in a .then() call on the doMore return value (which is undefined because doMore never executed to return the promise).
Am I correct on this? Would this be a protractor issue? Any workarounds?
I mis-troubleshoot'd the code.
The issue is that:
var prom = protractor.promise.Deferred();
should be:
var prom = new protractor.promise.Deferred();
Hence, my original question is no longer valid.