You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

52 lines
1.5 KiB

  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.AspNetCore.Mvc;
  6. using MQTTnet.Protocol;
  7. using MQTTnet.Server.Mqtt;
  8. namespace MQTTnet.Server.Controllers
  9. {
  10. [Authorize]
  11. [ApiController]
  12. public class MessagesController : Controller
  13. {
  14. private readonly MqttServerService _mqttServerService;
  15. public MessagesController(MqttServerService mqttServerService)
  16. {
  17. _mqttServerService = mqttServerService ?? throw new ArgumentNullException(nameof(mqttServerService));
  18. }
  19. [Route("api/v1/messages")]
  20. [HttpPost]
  21. public async Task<ActionResult> PostMessage(MqttApplicationMessage message)
  22. {
  23. await _mqttServerService.PublishAsync(message);
  24. return Ok();
  25. }
  26. [Route("api/v1/messages/{*topic}")]
  27. [HttpPost]
  28. public async Task<ActionResult> PostMessage(string topic, int qosLevel = 0)
  29. {
  30. byte[] payload;
  31. using (var memoryStream = new MemoryStream())
  32. {
  33. await HttpContext.Request.Body.CopyToAsync(memoryStream);
  34. payload = memoryStream.ToArray();
  35. }
  36. var message = new MqttApplicationMessageBuilder()
  37. .WithTopic(topic)
  38. .WithPayload(payload)
  39. .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qosLevel)
  40. .Build();
  41. return await PostMessage(message);
  42. }
  43. }
  44. }