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; namespace MyCore.Controllers { [Authorize(Roles = "Admin")] [Route("api/mqtt")] [ApiController] public class MQTTController : Controller { /// /// It's a mqtt publish test ! :) /// [AllowAnonymous] [HttpGet] public void GetToPublishMqtt() { Client_Publish(); } public async Task Client_Publish() { var server = new MqttFactory().CreateMqttServer(); try { var client1 = new MqttFactory().CreateMqttClient(); await client1.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("192.168.0.8").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(); } } } }