94 lines
3.4 KiB
C#
94 lines
3.4 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using Mqtt.Hubs;
|
|
using Mqtt.Models;
|
|
using Mqtt.Services;
|
|
using MQTTnet.Client;
|
|
using Repository.BackendRepository.Interface;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.Json.Serialization;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Mqtt.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/[controller]/[action]")]
|
|
public class AlarmController : ControllerBase
|
|
{
|
|
Dictionary<string, object> dic = new Dictionary<string, object>();
|
|
|
|
private readonly ILogger<MqttClientService> _logger;
|
|
private readonly IBackendRepository _backendRepository;
|
|
private readonly IBackgroundServicePostgresqlRepository _backgroundServicePostgresqlRepository;
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public AlarmController(ILogger<MqttClientService> logger, IBackgroundServicePostgresqlRepository backgroundServicePostgresqlRepository, IBackendRepository backendRepository,
|
|
IConfiguration configuration)
|
|
{
|
|
this._logger = logger;
|
|
this._configuration = configuration;
|
|
this._backendRepository = backendRepository;
|
|
this._backgroundServicePostgresqlRepository = backgroundServicePostgresqlRepository;
|
|
}
|
|
|
|
[HttpGet]
|
|
public async Task<IActionResult> AlarmList()
|
|
{
|
|
dic.Add("data", await new MqttClientService(_logger, _configuration, _backgroundServicePostgresqlRepository, _backendRepository).GetAlarmSettings());
|
|
return new OkObjectResult(dic);
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<IActionResult> AlarmRefresh()
|
|
{
|
|
try
|
|
{
|
|
await new MqttClientService(_logger, _configuration, _backgroundServicePostgresqlRepository, _backendRepository).RefreshAlarmSettings();
|
|
dic.Add("ok", true);
|
|
dic.Add("msg", "重新設定成功");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
dic.Add("ok", false);
|
|
dic.Add("msg", "重新設定失敗");
|
|
_logger.LogError($"重新設定失敗, Message: {e.Message}");
|
|
}
|
|
|
|
return new OkObjectResult(dic);
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<IActionResult> Publish([FromBody] HTTPBody body)
|
|
{
|
|
try
|
|
{
|
|
if (!body.data.ContainsKey("topic"))
|
|
{
|
|
dic.Add("ok", false);
|
|
dic.Add("msg", "請輸入標題");
|
|
}
|
|
|
|
if (!body.data.ContainsKey("message"))
|
|
{
|
|
dic.Add("ok", false);
|
|
dic.Add("msg", "請輸入内容");
|
|
}
|
|
|
|
await new MqttClientService(_logger, _configuration, _backgroundServicePostgresqlRepository, _backendRepository).PublishAsync(body.data["topic"].ToString(), body.data["message"].ToString());
|
|
dic.Add("ok", true);
|
|
dic.Add("msg", $"{body.data["topic"].ToString()}發佈成功");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
dic.Add("ok", false);
|
|
dic.Add("msg", "發佈失敗");
|
|
_logger.LogError($"發佈失敗, Message: {e.Message}");
|
|
}
|
|
|
|
return new OkObjectResult(dic);
|
|
}
|
|
}
|
|
} |