How to fix a simple callback function with a tcpip object?

17 views (last 30 days)
Hi Everyone,
I have a very simple problem: I am trying to get a callback function to execute after receiving data through a tcp/ip connection. I have been reading the asynchronuous writing and reading section of the MATLAB documentation here, and I am essentially reproducing what they suggest without any success.
Here is a simple script which illustrates my issue, when I execute it, I get a series of error and warning messages:
echotcpip('on',4000);
t = tcpip('127.0.0.1',4000);
t.BytesAvailableFcn = 'dispcallback';
fopen(t);
% Send some data:
fprintf(t, 'Test 123');
When I run the above script, I get these messages:
Error using dispcallback (line 13)
Not enough input arguments.
Error in instrcb (line 20)
evalin('base', val);
Warning: The BytesAvailableFcn is being disabled. To enable the callback property
either connect to the hardware with FOPEN or set the BytesAvailableFcn property.
Why is this? How can I properly invoke the callback function? I have tried with MATLAB 2014b and 2015b with the same result.
Thanks!

Answers (2)

Dave Behera
Dave Behera on 25 Mar 2016
Try replacing the line
t.BytesAvailableFcn = 'dispcallback';
with
set(t, 'BytesAvailableFcn', @dispcallback)
In the former, the event arguments were not being passed to the callback function, for some reason. Using the 'set' command should fix the issue.
  1 Comment
Andy
Andy on 2 Apr 2020
is there a way to open a useful udp server in Matlab (no echoudp...)?

Sign in to comment.


Andy
Andy on 2 Apr 2020
Edited: Andy on 2 Apr 2020
Should we specify a function:
function dispcallback(obj,event)
callbackTime = datestr(datenum(event.Data.AbsTime));
fprintf(['A ' event.Type ' event occurred for ' obj.Name ' at ' callbackTime '. Obj is the UDP object. Event is a struct w/ two fields: Type and Data. Data received over UDP: ' fscanf(obj) '\n']);
end
is required in the execution folder ... dispcallback doesn't seem to be available by default.
Main code:
% this opens a UDP server listening on ALL local IPs and port 8000
echoudp('on', 8000);
% this enacts a client conneting into 127.0.0.1:8000
u = udp('127.0.0.1', 8000);
fopen(u);
u.Status
% the below makes sure anything sent back to the client, gets echoed through the dispcallback
u.ReadAsyncMode = 'continuous';
set(u, 'BytesAvailableFcn', @dispcallback);
Run:
% this writes / sends an udp packet towards 127.0.0.1:8000
fprintf(u, 'Hello net.')
Output:
% Since echoudp will echo back anything you throw at it ... the below is the result of us running the fprintf above command.
"A BytesAvailable event occurred for UDP-127.0.0.1 at 02-Apr-2020 16:00:29. Obj is the UDP object. Data: Hello net."

Categories

Find more on Instrument Connection and Communication in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!