using System; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; 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.ModuleName.ViewModels { public class MqttControlViewModel : RegionViewModelBase { private readonly IEventAggregator _eventAggregator; private MqttHelper? _mqttHelper; private SubscriptionToken _token; public MqttControlViewModel( IRegionManager regionManager, IEventAggregator eventAggregator) : base(regionManager) { _eventAggregator = eventAggregator; _token = _eventAggregator.GetEvent().Subscribe(OnScanEventReceived, ThreadOption.UIThread, true); InitializeMqttAsync().ConfigureAwait(false); } private async Task InitializeMqttAsync() { try { _eventAggregator.GetEvent().Publish($"Mqtt初始化……"); string serverUrl = GetMqttConfigValue(MqttConfigs.Current?.ServerUrl); string clientId = GetMqttConfigValue(MqttConfigs.Current?.ClientId) + Guid.NewGuid().ToString("N"); _mqttHelper = new MqttHelper(serverUrl, 1883, clientId); _mqttHelper.MessageReceived += HandleMqttMessage; _mqttHelper.ConnectionFailed += HandleMqttConnectionFailed; if (await ConnectMqttAsync()) { await SubscribeToTopicsAsync(); await PublishInitialMessageAsync(); } _eventAggregator.GetEvent().Publish($"Mqtt初始化完成"); } catch (Exception ex) { _eventAggregator.GetEvent().Publish($"Mqtt初始化失败: {ex.Message}"); } } private string GetMqttConfigValue(string? configValue) { return configValue ?? "noConfig"; } private async Task ConnectMqttAsync() { if (_mqttHelper == null) return false; bool isConnected = await _mqttHelper.ConnectAsync(); if (!isConnected) { _eventAggregator.GetEvent().Publish($"MQTT连接失败"); } return isConnected; } private async Task SubscribeToTopicsAsync() { if (_mqttHelper == null || MqttConfigs.Current == null || SiteConfigs.Current == null) return; string printTopic = $"{MqttConfigs.Current.Topic}/print/{SiteConfigs.Current.SiteName}"; if (await _mqttHelper.SubscribeAsync(printTopic)) { _eventAggregator.GetEvent().Publish($"订阅:{printTopic}"); } } private async Task PublishInitialMessageAsync() { if (_mqttHelper == null || MqttConfigs.Current == null || SiteConfigs.Current == null) return; string connectTopic = $"{MqttConfigs.Current.Topic}/connect/{SiteConfigs.Current.SiteName}"; if (await _mqttHelper.PublishAsync(connectTopic, "已连接")) { _eventAggregator.GetEvent().Publish($"发布连接消息到: {connectTopic}"); } } public void HandleMqttMessage(object sender, MqttApplicationMessageReceivedEventArgs e) { try { string topic = e.ApplicationMessage.Topic; string payload = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); _eventAggregator.GetEvent().Publish($"收到信息'{topic}': {payload}"); if (MqttConfigs.Current == null || SiteConfigs.Current == null) return; // 处理mqtt打印消息 if (topic == $"{MqttConfigs.Current.Topic}/print/{SiteConfigs.Current.SiteName}") { var printMessage = ParsePrintMessage(payload); if (printMessage != null) { _eventAggregator.GetEvent().Publish(printMessage); } } } catch (Exception ex) { _eventAggregator.GetEvent().Publish($"处理MQTT消息时出错: {ex.Message}"); } } private PrintDto? ParsePrintMessage(string payload) { try { var jsonData = JsonSerializer.Deserialize(payload); return jsonData; } catch (JsonException ex) { _eventAggregator.GetEvent().Publish($"JSON 解析错误: {ex.Message}"); return null; } } private void HandleMqttConnectionFailed(object sender, Exception ex) { _eventAggregator.GetEvent().Publish($"MQTT连接失败: {ex.Message}"); } private async void OnScanEventReceived(string message) { if (_mqttHelper == null || MqttConfigs.Current == null || SiteConfigs.Current == null || SerialConfigs.Current == null) return; try { var jsonObject = new { SiteNo = SiteConfigs.Current.SiteName, ComNo = SerialConfigs.Current.ComName, Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), LabelCode = message }; string jsonMessage = JsonSerializer.Serialize(jsonObject); string topic = $"{MqttConfigs.Current.Topic}/SiteComLabelCode"; if (await _mqttHelper.PublishAsync(topic, jsonMessage)) { _eventAggregator.GetEvent().Publish($"发布扫描消息到: {topic}"); } } catch (Exception ex) { _eventAggregator.GetEvent().Publish($"发布扫描消息时出错: {ex.Message}"); } } public async void Destroy() { _token?.Dispose(); if (_mqttHelper != null) { await _mqttHelper.DisconnectAsync(); _mqttHelper.Dispose(); } } } }