78 lines
2.9 KiB
C#
78 lines
2.9 KiB
C#
using MQTTnet.Client;
|
|
using Prism.Events;
|
|
using Prism.Regions;
|
|
using RIZO_Application.Core;
|
|
using RIZO_Application.Core.Mvvm;
|
|
using RIZO_Application.Infrastructure.Model;
|
|
using RIZO_Helper.Tools;
|
|
|
|
namespace RIZO_Application.Modules.Base.ViewModels
|
|
{
|
|
public class MqttControlViewModel : RegionViewModelBase
|
|
{
|
|
private readonly IEventAggregator _eventAggregator;
|
|
private MqttHelper? _mqttHepler;
|
|
private SubscriptionToken _token;
|
|
public MqttControlViewModel(
|
|
IRegionManager regionManager,
|
|
IEventAggregator eventAggregator)
|
|
: base(regionManager)
|
|
{
|
|
_eventAggregator = eventAggregator;
|
|
_token = _eventAggregator.GetEvent<ScanEvent>().Subscribe(OnScanEventReceived, ThreadOption.UIThread, true);
|
|
Task.Run(Mqtt);
|
|
}
|
|
|
|
public async Task Mqtt()
|
|
{
|
|
string serverUrl = "noConfig";
|
|
string clientId = "noConfig";
|
|
if (MqttConfigs.Current != null)
|
|
{
|
|
serverUrl = MqttConfigs.Current.ServerUrl ?? string.Empty;
|
|
clientId = MqttConfigs.Current.ClientId ?? string.Empty;
|
|
}
|
|
_eventAggregator.GetEvent<SystemLogEvent>().Publish($"Mqtt初始化……");
|
|
_mqttHepler = new MqttHelper(serverUrl, 1883, clientId);
|
|
_mqttHepler.MessageReceived += HandleMqttMessage;
|
|
await _mqttHepler.ConnectAsync();
|
|
await _mqttHepler.SubscribeAsync($"shgg_mes/print/{clientId}");
|
|
await _mqttHepler.PublishAsync($"shgg_mes/connect/{clientId}","已连接");
|
|
// await _mqttHepler.SubscribeAsync("shgg_mes/backEnd/SiteComLabelCode");
|
|
_eventAggregator.GetEvent<SystemLogEvent>().Publish($"Mqtt初始化完成");
|
|
}
|
|
// 定义事件处理方法
|
|
public void HandleMqttMessage(object sender, MqttApplicationMessageReceivedEventArgs e)
|
|
{
|
|
// 获取消息的主题
|
|
string topic = e.ApplicationMessage.Topic;
|
|
// 获取消息的负载并转换为字符串
|
|
string payload = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
|
// 打印接收到的消息信息
|
|
_eventAggregator.GetEvent<SystemLogEvent>().Publish($"收到信息'{topic}': {payload}");
|
|
// 控制打印
|
|
PrintDto printMessage = new()
|
|
{
|
|
Path = "/",
|
|
Name = "需要测试打印",
|
|
Description = "123"
|
|
};
|
|
_eventAggregator.GetEvent<PrintEvent>().Publish(printMessage);
|
|
}
|
|
private async void OnScanEventReceived(string message)
|
|
{
|
|
if(_mqttHepler != null)
|
|
{
|
|
//TODO JSON重新构造发送信息
|
|
|
|
await _mqttHepler.PublishAsync($"shgg_mes/backEnd/SiteComLabelCode", message);
|
|
}
|
|
}
|
|
|
|
public void Destroy()
|
|
{
|
|
_token?.Dispose();
|
|
}
|
|
}
|
|
}
|