mqtt修改

This commit is contained in:
小魔仙
2025-05-23 08:45:58 +08:00
parent 9d66ffc55b
commit 6646e6b5e5
5 changed files with 119 additions and 43 deletions

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using MQTTnet.Client;
using Prism.Events;
using Prism.Regions;
@@ -17,7 +18,7 @@ namespace RIZO_Application.Modules.ModuleName.ViewModels
private readonly IEventAggregator _eventAggregator;
private MqttHelper? _mqttHelper;
private SubscriptionToken _token;
public MqttControlViewModel(
IRegionManager regionManager,
IEventAggregator eventAggregator)
@@ -40,7 +41,7 @@ namespace RIZO_Application.Modules.ModuleName.ViewModels
_mqttHelper = new MqttHelper(serverUrl, 1883, clientId);
_mqttHelper.MessageReceived += HandleMqttMessage;
_mqttHelper.ConnectionFailed += HandleMqttConnectionFailed;
_mqttHelper.Disconnected += Publish;
if (await ConnectMqttAsync())
{
await SubscribeToTopicsAsync();
@@ -81,6 +82,7 @@ namespace RIZO_Application.Modules.ModuleName.ViewModels
{
_eventAggregator.GetEvent<SystemLogEvent>().Publish($"订阅:{printTopic}");
}
}
private async Task PublishInitialMessageAsync()
@@ -165,7 +167,14 @@ namespace RIZO_Application.Modules.ModuleName.ViewModels
_eventAggregator.GetEvent<SystemLogEvent>().Publish($"发布扫描消息时出错: {ex.Message}");
}
}
public void Publish(string message, int retries, int maxRetries)
{
_eventAggregator.GetEvent<SystemLogEvent>().Publish(message);
if (retries>=maxRetries)
{
MessageBox.Show("MQTT已掉线请停止扫码");
}
}
public async void Destroy()
{
_token?.Dispose();