Develop the publisher NetLogic and interface
Develop a NetLogic and integrate it with the interface.
Develop the NetLogic
- In Project view, expand UI.
- Right-click MainWindow (type) and select .
-
Hover-over the NetLogic, select
, and enter PublisherLogic.
-
Double-click the NetLogic.
The external code editor opens.
-
In the code editor, replace the existing code with the following code:
#region StandardUsing using System; using FTOptix.CoreBase; using FTOptix.HMIProject; using UAManagedCore; using OpcUa = UAManagedCore.OpcUa; using FTOptix.NetLogic; using FTOptix.UI; using FTOptix.OPCUAServer; #endregion using uPLibrary.Networking.M2Mqtt; using uPLibrary.Networking.M2Mqtt.Messages; public class PublisherLogic : BaseNetLogic { public override void Start() { var brokerIpAddressVariable = Project.Current.GetVariable("Model/BrokerIpAddress"); // Create a client connecting to the broker (default port is 1883) publishClient = new MqttClient(brokerIpAddressVariable.Value); // Connect to the broker publishClient.Connect("PublisherClient"); // Assign a callback to be executed when a message is published to the broker publishClient.MqttMsgPublished += PublishClientMqttMsgPublished; } public override void Stop() { publishClient.Disconnect(); publishClient.MqttMsgPublished -= PublishClientMqttMsgPublished; } private void PublishClientMqttMsgPublished(object sender, MqttMsgPublishedEventArgs e) { Log.Info("Message " + e.MessageId + " - published = " + e.IsPublished); } [ExportMethod] public void PublishMessage() { var variable1 = Project.Current.GetVariable("Model/Variable1"); variable1.Value = new Random().Next(0, 101); // Publish a message ushort msgId = publishClient.Publish("/my_topic", // topic System.Text.Encoding.UTF8.GetBytes(((int)variable1.Value).ToString()), // message body MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // QoS level false); // retained } private MqttClient publishClient; }
Note: The code retrieves the value to publish from the variable that you will create later on. - Save the code.
Create the interface elements
-
In Project view, right-click Model and select .
If needed, rename the variable to Variable1.
Variable1 is created. The variable value is retrieved by the PublisherLogic script.
-
Add the publish button by performing the following actions:
- In Project view, right-click MainWindow (type) and select .
-
Hover-over the button, select
, and enter PublishButton.
- In Properties, set Text to Publish
-
In Events, next to MouseClick event, select
and select .