mirror of
https://bitbucket.org/myhomie/mycorerepository.git
synced 2025-12-06 17:51:20 +00:00
48 lines
1.3 KiB
C#
48 lines
1.3 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// It's a mqtt publish test ! :)
|
|
/// </summary>
|
|
[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();
|
|
}
|
|
}
|
|
}
|
|
} |