Пример #1
0
        public bool sendMqttMessage(string topic, string payload)
        {
            bool retVal     = false;
            var  factory    = new MqttFactory();
            var  mqttClient = factory.CreateMqttClient();
            var  options    = new MQTTnet.Client.MqttClientOptionsBuilder()
                              .WithClientId(System.Guid.NewGuid().ToString())
                              .WithCommunicationTimeout(TimeSpan.FromSeconds(50))
                              //.WithCredentials("sm_user", "hemligt")
                              .WithTcpServer("192.168.229.101")
                              .Build();

            mqttClient.ConnectAsync(options).Wait();
            var message = new MQTTnet.MqttApplicationMessageBuilder()
                          .WithTopic(topic)
                          .WithPayload(payload)
                          .WithAtLeastOnceQoS()
                          .Build();
            List <MQTTnet.MqttApplicationMessage> mess = new List <MQTTnet.MqttApplicationMessage>();

            mess.Add(message);
            mqttClient.PublishAsync(mess);
            mqttClient.DisconnectAsync();
            return(retVal);
        }
        public void PublishMessage(string datastream, string payload)
        {
            try
            {
                //PublishAsync("GOST/Datastreams(" + datastream + ")/Observations", payload);

                var message = new MQTTnet.MqttApplicationMessageBuilder()
                              .WithTopic("GOST/Datastreams(" + datastream + ")/Observations")
                              .WithPayload(payload)
                              .WithAtMostOnceQoS()
                              .WithRetainFlag(false)
                              .Build();
                List <MQTTnet.MqttApplicationMessage> mqttmess = new List <MQTTnet.MqttApplicationMessage>();
                mqttmess.Add(message);
                mlSend.PublishAsync(mqttmess).Wait();
            }
            catch (Exception e)
            {
                System.Console.WriteLine("Exception:" + e.Message + " " + e.Source + " " + e.StackTrace);
            }
        }