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.

42 lines
1.4 KiB

using MQTTnet.Server;
using MQTTnet;
using MQTTnet.Client;
using System.Text;
namespace MqttPublisherApp
{
internal class Program
{
private static string CLIENT_ID = "PublisherClient";
private static string SERVER_IP = "localhost";
private static readonly int PORT = 1883;
private static readonly string TOPIC = "home/kitchen/temperature";
static async Task Main(string[] args)
{
var mqttFactory = new MqttFactory();
var mqttClient = mqttFactory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithClientId(CLIENT_ID)
.WithTcpServer(SERVER_IP, PORT)
.Build();
await mqttClient.ConnectAsync(options);
while (true)
{
Console.WriteLine("Enter a message to publish: ");
var message = Console.ReadLine();
var mqttMessage = new MqttApplicationMessageBuilder()
.WithTopic(TOPIC)
.WithPayload(Encoding.UTF8.GetBytes(message))
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
.Build();
await mqttClient.PublishAsync(mqttMessage);
Console.WriteLine($"Message '{message}' published.");
}
}
}
}