mirror of
https://bitbucket.org/myhomie/mycorerepository.git
synced 2025-12-06 09:41:19 +00:00
59 lines
1.7 KiB
C#
59 lines
1.7 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;
|
|
using MQTTnet.Client.Options;
|
|
|
|
namespace MyCore.Controllers
|
|
{
|
|
[Authorize(Roles = "Admin")]
|
|
[Route("api/mqtt")]
|
|
[ApiController]
|
|
public class MQTTController : ControllerBase
|
|
{
|
|
private string _mqttServer = "192.168.31.140";
|
|
/// <summary>
|
|
/// It's a mqtt publish test ! :)
|
|
/// </summary>
|
|
[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();
|
|
}
|
|
}
|
|
}
|
|
} |