mirror of
https://bitbucket.org/myhomie/mycorerepository.git
synced 2025-12-06 09:41:19 +00:00
83 lines
2.7 KiB
C#
83 lines
2.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 Mqtt.Client.AspNetCore.Services;
|
|
using MQTTnet;
|
|
using MQTTnet.Client;
|
|
using MQTTnet.Client.Options;
|
|
using MyCore.Interfaces.DTO;
|
|
|
|
namespace MyCore.Controllers
|
|
{
|
|
[Authorize] // TODO role (Roles = "Admin")]
|
|
[Route("api/mqtt")]
|
|
[ApiController]
|
|
public class MQTTController : ControllerBase
|
|
{
|
|
private readonly IMqttClientService _mqttClientService;
|
|
private readonly IMqttOnlineClientService _mqttOnlineClientService;
|
|
|
|
public MQTTController(MqttClientServiceProvider provider, MqttClientOnlineServiceProvider onlineProvider)
|
|
{
|
|
this._mqttClientService = provider.MqttClientService;
|
|
this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Publish mqtt test
|
|
/// </summary>
|
|
/// <param name="mqttMessageDTO">Message to send</param>
|
|
[ProducesResponseType(typeof(bool), 200)]
|
|
[ProducesResponseType(typeof(string), 400)]
|
|
[ProducesResponseType(typeof(string), 500)]
|
|
[HttpPost]
|
|
public async Task<ObjectResult> PublishMessage([FromBody] MqttMessageDTO mqttMessageDTO)
|
|
{
|
|
try
|
|
{
|
|
if (mqttMessageDTO == null)
|
|
throw new ArgumentNullException("Incorrect parameters");
|
|
|
|
bool isSucess = false;
|
|
|
|
await MqttClientService.PublishMessage(mqttMessageDTO.Topic, mqttMessageDTO.Message).ContinueWith(res => {
|
|
|
|
if (res.Status == TaskStatus.RanToCompletion)
|
|
{
|
|
isSucess = true;
|
|
}
|
|
});
|
|
|
|
if (mqttMessageDTO.Online)
|
|
{
|
|
await MqttClientOnlineService.PublishMessage(mqttMessageDTO.Topic, mqttMessageDTO.Message).ContinueWith(res => {
|
|
|
|
if (res.Status == TaskStatus.RanToCompletion)
|
|
{
|
|
isSucess = true;
|
|
}
|
|
else
|
|
{
|
|
isSucess = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
return new OkObjectResult(isSucess);
|
|
}
|
|
catch (ArgumentNullException ex)
|
|
{
|
|
return new BadRequestObjectResult(ex.Message) {};
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new ObjectResult(ex.Message) { StatusCode = 500 };
|
|
}
|
|
}
|
|
}
|
|
} |