private void DisplayAlarm(string level, string alarmMessage)
        {
            Debug.WriteLine($"\n{alarmMessage}\n");
            MqttMessageTransport mmt = new MqttMessageTransport();

            // string now = string.Format("{0:HH:mm:ss tt}", DateTime.Now);
            mmt.Topic   = level;
            mmt.Message = $"{string.Format("{0:HH:mm:ss tt}", DateTime.Now)}; {alarmMessage}";
            _eventAggregator.GetEvent <MqttMessageTransport>().Publish(mmt);
        }
Пример #2
0
        private void _client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            var message = System.Text.Encoding.Default.GetString(e.Message);
            MqttMessageTransport mmt = new MqttMessageTransport();

            mmt.Topic   = e.Topic;
            mmt.Message = message;
            Debug.WriteLine($"Message received in MqttDataService _client_MqttMsgPublishReceived {message}");
            _eventAggregator.GetEvent <MqttMessageTransport>().Publish(mmt);
        }
Пример #3
0
        // TODO: Why would I use either DelegateCommand or ICommand over the other ???
        //private DelegateCommand _publishFritzMessageCommand;
        //public DelegateCommand PublishFritzMessageCommand =>
        //    _publishFritzMessageCommand ?? (_publishFritzMessageCommand = new DelegateCommand(ExecutePublishFritzMessageCommand));

        private void MqttMessageTransportMessageReceived(MqttMessageTransport obj)
        {
            MqttMessageTransportMessages.Add(obj);
            Debug.WriteLine($"MqttMessageTransport message received in MqttViewViewModel: Topic: '{obj.Topic}' Message: '{obj.Message}");
        }
        public async Task Initialize()
        {
            Debug.WriteLine($"\n\n in MqttDataService Initialize() \n\n");
            DisplayAlarm("Info", "Mqtt chat starting");

            string clientId = "";

            switch (Device.RuntimePlatform)
            {
            case Device.UWP:
                clientId = "XamarinChatAppUWP";
                break;

            case Device.Android:
                clientId = "XamarinChatAppAndroid";
                break;

            default:
                clientId = "XamarinChatAppiOS";
                break;
            }

            try
            {
                var factory = new MqttFactory();
                _client = factory.CreateMqttClient();

                if (_xpdSetting.UseTls)
                {
                    _options = new MqttClientOptionsBuilder()
                               .WithClientId(clientId)
                               .WithTcpServer(_xpdSetting.MqttBrokerAddress, Int16.Parse(_xpdSetting.MqttBrokerTlsPort)) // old M2MqttDotNet used string port.
                               .WithCredentials(_xpdSetting.MqttBrokerUserName, _xpdSetting.MqttBrokerUserPassword)
                               .WithCleanSession()
                               .WithTls()
                               .Build();
                }
                else
                {
                    _options = new MqttClientOptionsBuilder()
                               .WithClientId(clientId)
                               .WithTcpServer(_xpdSetting.MqttBrokerAddress, Int16.Parse(_xpdSetting.MqttBrokerPort))
                               .WithCredentials(_xpdSetting.MqttBrokerUserName, _xpdSetting.MqttBrokerUserPassword)
                               .WithCleanSession()
                               .Build();
                }

                _client.ConnectAsync(_options).Wait();
                _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(_xpdSetting.MqttBrokerTopic).Build()).Wait();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            _client.UseConnectedHandler(e =>
            {
                Debug.WriteLine("Connected successfully with MQTT Brokers.");
                _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(_xpdSetting.MqttBrokerTopic).Build()).Wait();
            });

            _client.UseDisconnectedHandler(async e =>
            {
                Debug.WriteLine("\nDisconnect\n");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await _client.ConnectAsync(_options, CancellationToken.None); // Since 3.0.5 with CancellationToken
                    Debug.WriteLine("### Reconnection Success! ###");
                    _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(_xpdSetting.MqttBrokerTopic).Build()).Wait();
                }
                catch
                {
                    Debug.WriteLine("### RECONNECTING FAILED ###");
                }
            });

            _client.UseApplicationMessageReceivedHandler(e =>
            {
                MqttMessageTransport mmt = new MqttMessageTransport
                {
                    Topic   = e.ApplicationMessage.Topic,
                    Message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload)
                };
                Debug.WriteLine($"Message received in MqttDataService _client_MqttMsgPublishReceived {mmt.Message}");
                _eventAggregator.GetEvent <MqttMessageTransport>().Publish(mmt);
            });
        }