You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
3.0 KiB
84 lines
3.0 KiB
using PMqttClient;
|
|
|
|
namespace MqttMultiTopicClientApp
|
|
{
|
|
internal class Program
|
|
{
|
|
private static string SERVER_IP = "localhost";
|
|
private static readonly int PORT = 1883;
|
|
|
|
private static MqttMultiTopicClient _mqttClient;
|
|
|
|
static async Task Main(string[] args)
|
|
{
|
|
_mqttClient = new MqttMultiTopicClient();
|
|
_mqttClient.LogHandler += MqttClient_LogHandler;
|
|
_mqttClient.MessageHandler += MqttClient_MessageHandler;
|
|
|
|
await _mqttClient.AddTopicAsync("home/livingroom/temperature", MqttQoSLevel.AtLeastOnce);
|
|
|
|
await Task.Delay(1000);
|
|
|
|
await _mqttClient.ConnectAsync(SERVER_IP, PORT, $"cid_{Random.Shared.Next(1, 1000)}");
|
|
|
|
await _mqttClient.AddTopicAsync("home/bedroom/humidity", MqttQoSLevel.AtMostOnce);
|
|
await _mqttClient.AddTopicAsync("home/kitchen/temperature", MqttQoSLevel.AtMostOnce);
|
|
|
|
while (true)
|
|
{
|
|
Console.WriteLine();
|
|
Console.WriteLine("----------------------");
|
|
Console.WriteLine("Add topic(1)");
|
|
Console.WriteLine("Publish message(2)");
|
|
Console.WriteLine("Else: Exit");
|
|
Console.WriteLine("----------------------");
|
|
Console.Write(">");
|
|
string command = Console.ReadLine();
|
|
await HandleCommand(command);
|
|
}
|
|
}
|
|
|
|
private static void MqttClient_MessageHandler(object? sender, string e)
|
|
{
|
|
Console.WriteLine($"[Message] {e}");
|
|
}
|
|
|
|
private static void MqttClient_LogHandler(object? sender, string e)
|
|
{
|
|
Console.WriteLine($"[Log] {e}");
|
|
}
|
|
|
|
static async Task HandleCommand(string command)
|
|
{
|
|
if (command.Contains("1", StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
Console.WriteLine("Topic?");
|
|
Console.Write(">");
|
|
string topic = Console.ReadLine();
|
|
Console.WriteLine("QoS(0-2)");
|
|
Console.Write(">");
|
|
string qos = Console.ReadLine();
|
|
int.TryParse(qos, out int convertedQos);
|
|
await _mqttClient.AddTopicAsync(topic, (MqttQoSLevel)convertedQos);
|
|
}
|
|
else if (command.Contains("2", StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
Console.WriteLine("Topic?");
|
|
Console.Write(">");
|
|
string topic = Console.ReadLine();
|
|
Console.WriteLine("Message?");
|
|
Console.Write(">");
|
|
string message = Console.ReadLine();
|
|
Console.WriteLine("QoS(0-2)");
|
|
Console.Write(">");
|
|
string qos = Console.ReadLine();
|
|
int.TryParse(qos, out int convertedQos);
|
|
await _mqttClient.PubishAsync(topic, message, (MqttQoSLevel)convertedQos);
|
|
}
|
|
else
|
|
{
|
|
await _mqttClient.DisconnectAsync();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|