Files
ExemploAppMAUI/GuilhermesApp/Pages/SensorPage.xaml.cs
Guilherme Gaspar 44f456eb29 Guilhermes
2026-03-23 17:42:36 +00:00

83 lines
2.6 KiB
C#

using MQTTnet;
using System.Text;
using System.Buffers;
namespace GuilhermesApp.Pages;
public partial class SensorPage : ContentPage
{
private IMqttClient? _mqttClient;
private MqttClientOptions? _options;
private bool _isLedOn = false;
public SensorPage()
{
InitializeComponent();
ConfigurarMqtt();
}
private async void ConfigurarMqtt()
{
try
{
// TENTATIVA A: MqttClientFactory (Novo padrão em algumas versões v5)
// Se der erro aqui, tenta mudar para: var factory = new MqttFactory();
var factory = new MqttClientFactory();
_mqttClient = factory.CreateMqttClient();
_options = new MqttClientOptionsBuilder()
.WithTcpServer("broker.hivemq.com", 1883)
.Build();
_mqttClient.ApplicationMessageReceivedAsync += e =>
{
// Extração manual de bytes para evitar o erro do ToArray
var buffer = e.ApplicationMessage.Payload;
byte[] payloadBytes = new byte[buffer.Length];
buffer.CopyTo(payloadBytes);
string payload = Encoding.UTF8.GetString(payloadBytes);
MainThread.BeginInvokeOnMainThread(() =>
{
if (payload == "PRESSIONADO")
{
StatusLabel.Text = $"Último clique: {DateTime.Now:HH:mm:ss}";
StatusLabel.TextColor = Colors.Green;
}
});
return Task.CompletedTask;
};
await _mqttClient.ConnectAsync(_options);
await _mqttClient.SubscribeAsync("guilherme/app/botao");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Erro crítico MQTT: {ex.Message}");
}
}
private async void OnLedClicked(object sender, EventArgs e)
{
if (_mqttClient == null || !_mqttClient.IsConnected)
{
await DisplayAlert("Erro", "O MQTT não está ligado.", "OK");
return;
}
_isLedOn = !_isLedOn;
string comando = _isLedOn ? "ON" : "OFF";
var message = new MqttApplicationMessageBuilder()
.WithTopic("guilherme/app/led")
.WithPayload(comando)
.Build();
await _mqttClient.PublishAsync(message);
LedBtn.Text = _isLedOn ? "DESLIGAR LED" : "LIGAR LED";
LedBtn.BackgroundColor = _isLedOn ? Colors.Red : Colors.DarkSlateGray;
}
}