%% Broadcast User Datagram Protcol Data Packets
% This example shows how to send and receive broadcast datagram packets using the udpport function.
%% Create udpport Broadcaster
% Create a datagram type udpport broadcaster instance

uBroadcaster = udpport("datagram")

% Set the EnableBroadcast property to allow for broadcasting.

uBroadcaster.EnableBroadcast = true;

%
%% Create udpport Receivers
% Create udpport instances that receive the broadcast data. These receivers are bound to LocalPort 2020 with EnablePortSharing enabled so that multiple udpport objects can bind to the same socket. uReceiver1 is a byte type udpport instance and uReceiver2 is a datagram type udpport instance.

uReceiver1 = udpport("byte","LocalPort",2020,"EnablePortSharing",true)
uReceiver2 = udpport("datagram", "LocalPort",2020,"EnablePortSharing",true)

%
%% Send Broadcast Data
% The broadcaster sends data to the broadcast address "192.168.255.255" and the port 2020, to which the receivers are bound. In this example, the broadcast address is "192.168.255.255", which is determined by the network address and the subnet mask. This address will be different on your computer.
% Write the data 1:5, specified as uint8 data.

write(uBroadcaster,1:5,"uint8","192.168.255.255",2020);

%
%% Receive Broadcast Data
% Now that the broadcaster has sent the data, the receivers receive these data packets.
% Verify that the value of the NumBytesAvailable property of uReceiver1 is 5, indicating that five bytes of data was received.

uReceiver1Count = uReceiver1.NumBytesAvailable

% Verify that the value of the NumDatagramsAvailable property of uReceiver2 is 1, indicating that one datagram was received.

uReceiver2Count = uReceiver2.NumDatagramsAvailable

% Read the 5 bytes of data from uReceiver1.

data1 = read(uReceiver1,uReceiver1Count,"uint8")

% Read the 1 datagram received on uReceiver2.

data2 = read(uReceiver2,uReceiver2Count,"uint8");

% data2 is a udpport.datagram.Datagram object. View the data received.

data2.Data

%
%% Clear Instances
% Clear the udpport broadcaster and receiver instances.

clear uBroadcaster
clear uReceiver1
clear uReceiver2

%
% Copyright 2020 The MathWorks, Inc.