using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MQTTnet; using MQTTnet.Client; using MQTTnet.Client.Options; namespace MyCore.Controllers { [Authorize(Roles = "Admin")] [Route("api/mqtt")] [ApiController] public class MQTTController : ControllerBase { private string _mqttServer = "192.168.0.8"; /// /// It's a mqtt publish test ! :) /// [AllowAnonymous] [HttpGet] public void GetToPublishMqtt() { Client_Publish().ContinueWith(res => { if (res.Status == TaskStatus.RanToCompletion) { Console.WriteLine("It's a success !"); } else { Console.WriteLine("We have an issue here.. "); } }); } protected async Task Client_Publish() { var server = new MqttFactory().CreateMqttServer(); try { var client1 = new MqttFactory().CreateMqttClient(); await client1.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer(_mqttServer).Build()); var message = new MqttApplicationMessageBuilder().WithPayload("It's a test").WithTopic("IpAddress").WithRetainFlag().Build(); await client1.PublishAsync(message); await Task.Delay(500); } finally { await server.StopAsync(); } } } }