implemented functionality to subscribe on connect

main
Jonas Arnold 4 years ago
parent f7720ffc67
commit a3fc254f44
  1. 6
      ADIS_Csharp/RobotClientWpf/ChallengeFactory.cs
  2. 30
      ADIS_Csharp/RobotLib/Communication/MqttPublisherSubscriber.cs

@ -3,7 +3,7 @@ using RobotLib.Communication;
namespace RobotClientWpf
{
internal class ChallengeFactory
public class ChallengeFactory
{
public MqttPublisherSubscriber PublisherSubscriber { get; }
public Robot RobotStationary { get; }
@ -12,8 +12,8 @@ namespace RobotClientWpf
public ChallengeFactory()
{
this.PublisherSubscriber = MqttPublisherSubscriber.Instance;
//this.RobotStationary = new Robot(this.PublisherSubscriber);
//this.RobotMobile = new Robot(this.PublisherSubscriber);
this.RobotStationary = new Robot(this.PublisherSubscriber);
this.RobotMobile = new Robot(this.PublisherSubscriber);
}
}
}

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
@ -10,6 +11,7 @@ namespace RobotLib.Communication
private MqttClient client;
private static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
private object clientLock = new object();
private List<string> toBeSubscribedTopics = new List<string>();
/// <summary>
/// Singleton pattern.
@ -99,6 +101,15 @@ namespace RobotLib.Communication
success = client.IsConnected;
log.Info($"Connecting done. Success = {success}");
// subscribe to topics that have already been appended
if(success)
{
foreach (var topic in toBeSubscribedTopics)
{
this.OnlineSubscribe(topic);
}
}
}
return success;
}
@ -141,6 +152,11 @@ namespace RobotLib.Communication
public void Publish(string topic, string message)
{
if(this.IsConnected == false)
{
log.Warn($"Message was discarded, Mqtt broker not connected. Destination topic={topic}");
return;
}
lock (clientLock)
{
var msgId = client.Publish(topic, Encoding.ASCII.GetBytes(message));
@ -149,6 +165,20 @@ namespace RobotLib.Communication
}
public void Subscribe(string topic)
{
// add to list if not already there
if(toBeSubscribedTopics.Contains(topic) == false)
{
toBeSubscribedTopics.Add(topic);
log.Debug($"Added topic '{topic}'. To the to be subscribed list.");
}
if (this.IsConnected)
{
OnlineSubscribe(topic);
}
}
private void OnlineSubscribe(string topic)
{
lock (clientLock)
{

Loading…
Cancel
Save