Пример #1
0
 private void btnEncenderLed_Clicked(object sender, EventArgs e)
 {
     if (mqtt.IsConnected)
     {
         mqtt.Publish("ESP8266PruebaCin", "L1", QoS.FireAndForget, false);
     }
 }
Пример #2
0
 /// <summary>
 /// 发布消息(JSON字符串作为参数)
 /// </summary>
 /// <param name="topic">主题</param>
 /// <param name="jsonContent">JSON字符串</param>
 /// <param name="errMsg">错误提示</param>
 /// <returns>发布是否成功</returns>
 private bool Publish(string topic, string jsonContent, ref string errMsg)
 {
     if (!Client.IsConnected)
     {
         errMsg = "消息服务器连接异常。";
         LogHelper.WriteError("[MqttService_Publish]" + errMsg);
         return(false);
     }
     try
     {
         Stopwatch stopWatch = new Stopwatch();
         stopWatch.Start();
         string finalJson        = DataConverter.AESEncrypt(jsonContent, GlobalVariable.AES_Key, GlobalVariable.AES_IV);
         byte[] gzipCompressJson = DataConverter.GzipCompress(System.Text.Encoding.UTF8.GetBytes(finalJson));
         Client.Publish(topic, gzipCompressJson, QoS.AcknowledgeDelivery, false);
         stopWatch.Stop();
         if (topic != "heartbeat")//屏蔽掉发心跳的日志
         {
             LogHelper.WriteDebug(string.Format("发布MQTT消息成功({0}毫秒):topic={1},content={2}", stopWatch.Elapsed.TotalMilliseconds, topic, jsonContent));
         }
         return(true);
         //Client.Publish("zxfTopic111", "ZXFTOPIC111", QoS.AcknowledgeDelivery, false);
     }
     catch (Exception ex)
     {
         errMsg = ex.Message;
         LogHelper.WriteError("发布MQTT消息失败:" + errMsg + "," + ex.StackTrace);
         return(false);
     }
 }
Пример #3
0
        void WyslijWiadomosc()
        {
            var    receivedMessage = false;
            string message         = "";
            // create the client
            var client = new MQTTClient("xxx.xxx.xxx.xxx", 10883);

            // hook up the MessageReceived event with a handler
            //client.MessageReceived += (topic, qos, payload) =>
            //{
            //    MessageBox.Show("Odebrano: " + topic);
            //    receivedMessage = true;
            //};

            // connect to the MQTT server
            message = Guid.NewGuid().ToString();
            client.Connect("Klient1234");
            // wait for the connection to complete

            // add a subscription
            client.Subscriptions.Add(new Subscription("test"));

            string User = "";

            User = client.BrokerHostName;
            var data = DateTime.Now;

            client.Publish("test", data + " Wiadomosc: " + message, QoS.AcknowledgeDelivery, false);
            status.Content = "Wysłano";
            if (client.IsConnected)
            {
                client.Disconnect();
            }
        }
Пример #4
0
 /// <summary>
 /// 发布消息(JSON字符串作为参数)
 /// </summary>
 /// <param name="topic">主题</param>
 /// <param name="jsonContent">JSON字符串</param>
 /// <param name="isheartBeat">是否心跳消息</param>
 /// <param name="errMsg">错误提示</param>
 /// <returns>发布是否成功</returns>
 private bool Publish(string topic, string jsonContent, bool isheartBeat, ref string errMsg)
 {
     if (!_client.IsConnected)
     {
         errMsg = Resources.SdkMqServiceException;
         return(false);
     }
     try
     {
         var stopWatch = new Stopwatch();
         stopWatch.Start();
         var payload = System.Text.Encoding.UTF8.GetBytes(jsonContent);
         _client.Publish(topic, payload, QoS.AcknowledgeDelivery, false);
         stopWatch.Stop();
         if (!isheartBeat || SdkService.HeartBeatLog) //屏蔽掉发心跳的日志
         {
             LogHelper.WriteDebug(
                 $"{Resources.SdkMsPublishSuccess}({stopWatch.Elapsed.TotalMilliseconds} millisecond):topic={topic},content={jsonContent}");
         }
         //发送消息,需要重置心跳计数器[心跳消息,主要是判断上行消息的情况]
         _heartbeatnumber = 0;
         return(true);
     }
     catch (Exception ex)
     {
         errMsg = ex.Message;
         LogHelper.WriteError($"{Resources.SdkMsPublishFail}:{errMsg},{ex.StackTrace}");
         return(false);
     }
 }
Пример #5
0
 private static void SendMQTT(string message)
 {
     System.Media.SystemSounds.Asterisk.Play();
     Task.Run(() =>
     {
         //Send the message with exactly once semantics
         MQTTClient.Publish(Setting.Default.Topic, Encoding.UTF8.GetBytes(message),           // message body
                            MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE,                              // QoS level
                            true);
     });
 }
 public static void Publicar(string topic, string mensaje)
 {
     if (mqtt.IsConnected)
     {
         Debug.WriteLine($"-> [{topic}] {mensaje}");
         mqtt.Publish(topic, mensaje, QoS.FireAndForget, false);
     }
     else
     {
         Error(null, "No hay conexion al servidor MQTT, no se puede enviar el mensaje");
     }
 }
Пример #7
0
        public async Task SubscribeAndSendMessage()
        {
            MQTTClient client = new MQTTClient();

            _ = await client.Connect(this.IP, this.PORT, this.PASSWORD);

            client.Subscribe(this.TESTCHANNEL);
            client.Publish(this.TESTCHANNEL, "hello world");
            Thread.Sleep(100);
            MQTTMessage message = client.MQTTMessageStore.GetLatestMessageFromTopic(this.TESTCHANNEL);

            Assert.AreEqual("hello world", message.Message);
        }
Пример #8
0
        public void ClientReceiveTest()
        {
            var receivedMessage = false;

            var client = new MQTTClient("ec2-18-217-218-110.us-east-2.compute.amazonaws.com", 1883);

            client.MessageReceived += (topic, qos, payload) =>
            {
                Debug.WriteLine("RX: " + topic);
                receivedMessage = true;
            };

            var i = 0;

            client.Connect("solution-family", "solution-family", "s36158");
            while (!client.IsConnected)
            {
                Thread.Sleep(1000);

                if (i++ > 10)
                {
                    Assert.Fail();
                }
            }

            Assert.IsTrue(client.IsConnected);
            client.Subscriptions.Add(new Subscription("solution-family/#"));

            i = 0;
            while (true)
            {
                if (receivedMessage)
                {
                    break;
                }

                Thread.Sleep(1000);
                client.Publish("solution-family/Test", "Hello", QoS.FireAndForget, false);

                if (i++ > 10)
                {
                    break;
                }
            }

            Assert.IsTrue(receivedMessage);
        }
Пример #9
0
        static void Main(string[] ass)
        {
            ////
            int        count    = 0;
            var        ClientId = DateTime.Now.Ticks.ToString();
            MQTTClient client   = new MQTTClient("my.hnlyf.com");

            client.Connect(new MQTTConnectInfo()
            {
                UserName = "******", Password = "******", ClientId = ClientId
            });
            // client.Subscribe("iot/log/#"); ;
            System.Timers.Timer timer = new System.Timers.Timer(1000);
            timer.Elapsed += (o, e) =>
            {
                Console.Title = ($"{ClientId}--{ass[0]}:当前每秒:{count}个,总个数:{TotalCount}");
                count         = 0;
            };

            timer.Start();
            while (true)
            {
                //Console.WriteLine("请随意输入");
                var text = Guid.NewGuid().ToString();
                if (string.IsNullOrEmpty(text))
                {
                    client.UnSubscribe("iot/log/#");;
                    client.Disconnect();
                }
                PublishDataPackage applicationMessage = new PublishDataPackage()
                {
                    Topic = $"iot/log/{ass[0]}", Text = text
                };
                if (!client.Publish(applicationMessage))
                {
                    Console.WriteLine("断线了?");
                    Console.ReadLine();
                }
                System.Threading.Interlocked.Increment(ref count);
                System.Threading.Interlocked.Increment(ref TotalCount);
                System.Threading.Thread.Sleep(10);
            }



            Console.ReadLine();
        }
Пример #10
0
        public async Task MQTTPublish(string deviceId, object attribs, string user)
        {
            var topic   = $"/{ user }/{deviceId}/attrs";
            var content = JsonConvert.SerializeObject(attribs);

            client.Connect(GenerateRandomKey());
            var i = 0;

            while (!client.IsConnected)
            {
                await Task.Delay(1000);

                if (i++ > timeout)
                {
                    throw new TimeoutException();
                }
            }


            client.Publish(topic, content, QoS.FireAndForget, false);
        }
 // Use this to publish a payload(message) to a topic
 public void Publish(string topicToPublishTo, string payload)
 {
     // Publish the payload to the topic
     client.Publish(topicToPublishTo, payload, QoS.FireAndForget, false);
 }