Пример #1
0
        private void _disconnect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected == false)
                {
                    return;
                }

                DisconnectMessage disconnectMsg = new DisconnectMessage();
                string            payload       = JsonConvert.SerializeObject(disconnectMsg);

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(_scadaConnTopic)
                              .WithPayload(payload)
                              .WithAtLeastOnceQoS()
                              .WithRetainFlag(true)
                              .Build();

                _mqttClient.PublishAsync(message).ContinueWith(t => _mqttClient.StopAsync());
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
Пример #2
0
        public async Task Storage_Queue_Drains()
        {
            using (var testEnvironment = new TestEnvironment())
            {
                testEnvironment.IgnoreClientLogErrors = true;
                testEnvironment.IgnoreServerLogErrors = true;

                var factory = new MqttFactory();

                var server = await testEnvironment.StartServerAsync();

                var managedClient = new ManagedMqttClient(testEnvironment.CreateClient(), new MqttNetLogger().CreateChildLogger());
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithTcpServer("localhost", testEnvironment.ServerPort);
                var storage = new ManagedMqttClientTestStorage();

                TaskCompletionSource <bool> connected = new TaskCompletionSource <bool>();
                managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
                {
                    managedClient.ConnectedHandler = null;
                    connected.SetResult(true);
                });

                await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder()
                                               .WithClientOptions(clientOptions)
                                               .WithStorage(storage)
                                               .WithAutoReconnectDelay(System.TimeSpan.FromSeconds(5))
                                               .Build());

                await connected.Task;

                await testEnvironment.Server.StopAsync();

                await managedClient.PublishAsync(new MqttApplicationMessage { Topic = "1" });

                //Message should have been added to the storage queue in PublishAsync,
                //and we are awaiting PublishAsync, so the message should already be
                //in storage at this point (i.e. no waiting).
                Assert.AreEqual(1, storage.GetMessageCount());

                connected = new TaskCompletionSource <bool>();
                managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
                {
                    managedClient.ConnectedHandler = null;
                    connected.SetResult(true);
                });

                await testEnvironment.Server.StartAsync(new MqttServerOptionsBuilder()
                                                        .WithDefaultEndpointPort(testEnvironment.ServerPort).Build());

                await connected.Task;

                //Wait 500ms here so the client has time to publish the queued message
                await Task.Delay(500);

                Assert.AreEqual(0, storage.GetMessageCount());

                await managedClient.StopAsync();
            }
        }
Пример #3
0
        /// <summary>
        /// Sends the Observations to the MQTT broker
        /// </summary>
        /// <param name="sendAdditionalProperties">If true, the 'Writeable' and 'Forceable' properties will be sent in the Observation</param>
        /// <returns></returns>
        private async Task <bool> UpdateValues(SubscriptionReader si, ReadResult <SubscriptionResultItem> results, bool sendAdditionalProperties = false)
        {
            if (!results.Success)
            {
                Prompts.AddRange(results.Prompts);
                return(false);
            }

            var devices = results.DataRead.GroupBy(a => a.ValueItemChangeEvent.Id.Remove(a.ValueItemChangeEvent.Id.LastIndexOf('/')).Remove(0, 2));

            foreach (var device in devices)
            {
                var observations  = new List <Observation>();
                var deviceMessage = new IotEdgeMessage
                {
                    Format       = "rec2.3",
                    Observations = observations,
                    DeviceId     = device.Key
                };

                AddUpdatedValuesToMessage(observations, device.Key, device.ToList(), si.CachedSubscribedItems, sendAdditionalProperties);

                var messageBuilder = new MqttApplicationMessageBuilder();
                var message        = messageBuilder.WithRetainFlag().WithAtLeastOnceQoS().WithTopic(ValuePushTopic).WithPayload(deviceMessage.ToJson()).Build();
                Logger.LogTrace(LogCategory.Processor, this.Name, $"Sending Message to MQTT Broker: {deviceMessage.ToJson()}");
                await ManagedMqttClient.PublishAsync(message);
            }

            return(true);
        }
Пример #4
0
        public static async Task <bool> SendMQTT(string topic, string payload)
        {
            if (topic == "")
            {
#if DEBUG
                topic = "topic_not_set";
#else
                if (await App.Current.MainPage.DisplayAlert("MQTT sending failed", "do you want to enter settings?", "yes", "no"))
                {
                    await App.Current.MainPage.Navigation.PushAsync(new SettingsPassword(new GuiPage(Views.MainPage.masterMenu, Views.MainPage.bottomMenu)), true);
                }
                return(false);
#endif
            }

            if (mqttClient == null || !mqttClient.IsConnected)
            {
                if (!await ConnectMQTT())
                {
                    return(false);
                }
            }

            try
            {
                Debug.WriteLine("sending mqtt message");
                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(topic)
                              .WithPayload(payload)
                              .WithRetainFlag()
                              .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel) 1)
                              .Build();
                Debug.WriteLine("topic: " + topic + "   payload: " + payload);
                await mqttClient.PublishAsync(message, CancellationToken.None);
            }
            catch (Exception e)
            {
                Debug.WriteLine("error while sending: " + e.Message);
            };
            return(true);
        }
Пример #5
0
        /// <summary>
        /// Sends the Observations to the MQTT broker
        /// </summary>
        /// <param name="sendAdditionalProperties">If true, the 'Writeable' and 'Forceable' properties will be sent in the Observation</param>
        /// <returns></returns>
        private async Task <bool> UpdateValues(SubscriptionReader si, ReadResult <SubscriptionResultItem> results, bool sendAdditionalProperties = false)
        {
            if (!results.Success)
            {
                Prompts.AddRange(results.Prompts);
                return(false);
            }

            if (results.DataRead.Any(a => a.ValueItemChangeEvent.State == EwsValueStateEnum.Error))
            {
                CheckAndRetryValuesWithError(si, results);
            }

            var signalChanges = results.DataRead.GroupBy(a => a.ValueItemChangeEvent.Id.Remove(a.ValueItemChangeEvent.Id.LastIndexOf('/')).Remove(0, 2)).ToList();
            var devices       = _tempSignals.GroupBy(a => a.DatabasePath.Remove(a.DatabasePath.LastIndexOf('/')));

            foreach (var device in devices)
            {
                var observations  = new List <Observation>();
                var deviceMessage = new IotEdgeMessage
                {
                    Format       = "rec2.3",
                    Observations = observations,
                    DeviceId     = device.Key
                };
                var signalChangesForDevice = signalChanges.FirstOrDefault(a => a.Key == device.Key);
                AddUpdatedValuesToMessage(observations, device.Key, signalChangesForDevice == null || !signalChangesForDevice.ToList().Any() ? new List <SubscriptionResultItem>() : signalChangesForDevice.ToList(), si.CachedSubscribedItems, sendAdditionalProperties);

                if (deviceMessage.Observations != null && deviceMessage.Observations.Count > 0)
                {
                    var messageBuilder        = new MqttApplicationMessageBuilder();
                    var managedMessageBuilder = new ManagedMqttApplicationMessageBuilder();
                    var message = messageBuilder.WithRetainFlag().WithAtLeastOnceQoS().WithTopic(ValuePushTopic).WithPayload(deviceMessage.ToJson()).Build();
                    Logger.LogTrace(LogCategory.Processor, this.Name, $"Sending Message to MQTT Broker: {deviceMessage.ToJson()}");
                    await ManagedMqttClient.PublishAsync(managedMessageBuilder.WithApplicationMessage(message).Build());
                }
            }

            return(true);
        }
Пример #6
0
        private void _dataRecoverTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (_mqttClient.IsConnected == false)
            {
                return;
            }

            if (_recoverHelper != null && _recoverHelper.DataAvailable())
            {
                List <string> records = _recoverHelper.Read(DEAFAULT_DATARECOVER_COUNT);
                foreach (var record in records)
                {
                    var message = new MqttApplicationMessageBuilder()
                                  .WithTopic(_dataTopic)
                                  .WithPayload(record)
                                  .WithAtLeastOnceQoS()
                                  .WithRetainFlag(false)
                                  .Build();

                    _mqttClient.PublishAsync(message);
                }
            }
        }
Пример #7
0
 private async Task Publish(String Topic, String Payload)
 {
     await mqttClient.PublishAsync(Topic, Payload).ConfigureAwait(false);
 }