Simulink Desktop Real-Time and UDP communication with Python

17 views (last 30 days)
I have a main Python program that has two(three) subprocesses:
  • execMainModel (a matlab function that it calls a simulink model, in this model I have a real-time sync block, an UDP receiver block, and two UDP sender blocks)
  • play.py (a Python program that sends 2 UDP messages every 0.1 s { [p1],[p2], wait......,[][]...}
  • reed.py (read Simulink output, debugging script)
Currently my flow is:
1) Run mainPythonScript
2) call execMainModel.m function (subprocess, bash command), initialize some dictionary parameters, and start Simulink model.
3) Time = 0.0 send over UDP1 a "sync" message to the pythonMain.
4) When the sync message is received the real sender is started (play.py).
5) The loop is completed, I can proceed with the real execution loop where I read the UDP packet and, after some processing, send it or a similar copy via UDP2 to another process (this is not so important).
Currently, my model rate is 50 Hz, and the UDP buffer can contain only two messages (my choice), blocking time = 0 (or very small).
Execution output:
I receive and resend correctly the first UDP message from player.py (after the sync) then I lose 2 to 6 messages (it's variable), then the program goes on without problems and synchronized. If I increase the buffer size (5/10 elements) it proceeds without losing data packets. At the same time, if I wait 1 second after the sync acknowledgement before starting player.py it works well.
My thoughts:
Also if Simulink sends the sync message it seems that Simulink requires more init time to start.. it's possibile to solve this problem without waiting and keeping the small buffer? real-time sync block parameters can affect this problem? (sample time / maximum missed ticks)
MATLAB release 2022b
thanks.

Answers (1)

Jan Houska
Jan Houska on 29 Jul 2023
Hi Matteo,
just some random thoughts that may or may not help you with your problem:
  • All Simulink Desktop Real-Time blocks synchronize to their sampling period. So if you use e.g. Packet Input or Packet Output for the UDP, you don't need to use Real-Time Sync at all. And if you are not using Packet Input/Output for UDP, then you probably should - they work better with Simulink Desktop Real-Time models than other UDP blocks.
  • The Packet Input block has an optional Data Ready output. Please enable it and use it to check whether a message has arrived. The Packet Input block does not wait for a message to be received because it cannot block the real-time operation.
Good Luck, Jan

Categories

Find more on Hardware-in-the-Loop Simulation with Simulink Real-Time 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!