MATLAB: Don’t I receive any data from the hardware device if I try reading the data in a callback function using “parfeval”

fopenhardwarelockParallel Computing Toolboxparfevalserial

I am trying to read data from a Bluetooth device. I have code which works perfectly fine in MATLAB. But when I was reading the data in MATLAB, current MATLAB session remained busy till the data was read. However, I wanted to acquire this data in parallel, so I decided to use "parfeval" to read data on a different worker. I am creating Bluetooth object and using "fopen" to open Bluetooth connection in MATLAB. I have a  call back function which will be used in "parfeval", this function accepts this Bluetooth object and reads data from Bluetooth device. However, when I call this function using "parfeval", I get an error saying:
Error using parallel.FevalFuture/fetchOutputs (line 147)
One or more futures resulted in an error.
Error in parallelProcessingTest (line 61)
val = fetchOutputs(f)
Cause by:
Error using icinterface/fscanf (line 208)
| OBJ must be connected to the hardware with FOPEN.|
Since, this function was working correctly when I was not using "parfeval", I believe the issue is because of "parfeval". How can I collect Bluetooth data in callback function using "parfeval"?

Best Answer

This is an expected behavior in MATLAB. This behavior is caused because 2 different processes try to access a single Bluetooth object which is not supported by MATLAB. You are trying to use "fopen" to open a connection in MATLAB. Once this connection is opened Bluetooth object is locked by the process (process1). However, when you pass this object to "parfeval", since the "parfeval" runs this function asynchronously on different worker, it runs in a different process (process 2). When you try to read the data in process2, process2 tries to access the object but since it was locked by process1, process2 can not access it causing the issue. To resolve the issue, move the call of "fopen" in your call back function.