Пример #1
0
        public async Task Publish <T>(string topic, T payload, bool retain = false)
        {
            var contentType = "application/octet-stream";

            byte[] payloadBytes;
            if (payload is byte[])
            {
                payloadBytes = payload as byte[];
            }
            else if (payload is string)
            {
                contentType  = "text/plain";
                payloadBytes = Encoding.UTF8.GetBytes(payload as string);
            }
            else
            {
                contentType = "application/json";
                var payloadString = JsonConvert.SerializeObject(payload);
                payloadBytes = Encoding.UTF8.GetBytes(payloadString);
            }

            await MqttClient.PublishAsync(new MqttApplicationMessage()
            {
                PayloadFormatIndicator = contentType == "application/octet-stream" ? MQTTnet.Protocol.MqttPayloadFormatIndicator.Unspecified : MQTTnet.Protocol.MqttPayloadFormatIndicator.CharacterData,
                ContentType            = contentType,
                Topic   = string.Format(topic, _clientId),
                Payload = payloadBytes,
                Retain  = retain
            });
        }
Пример #2
0
        public async Task <MqttClientPublishResult> SendDiscoveryAsync <TEntityDefinition>(
            string topic,
            TEntityDefinition payload,
            CancellationToken cancellationToken = default)
            where TEntityDefinition : IEntityDefinition
        {
            var payloadString = GetPayloadString(payload);

            var messageBuilder = new MqttApplicationMessageBuilder()
                                 .WithTopic(topic)
                                 .WithPayload(payloadString)
                                 .WithRetainFlag(Settings.Value.Retain);

            if (Settings.Value.QualityOfService.HasValue)
            {
                messageBuilder = messageBuilder.WithQualityOfServiceLevel(Settings.Value.QualityOfService.Value);
            }

            Logger.LogInformation("[{topic}] {payload}", topic, payloadString);

            var message = messageBuilder.Build();

            var result = await MqttClient.PublishAsync(message, cancellationToken);

            return(result);
        }
        /// <summary>
        /// Refreshes current state and publishes changes.
        /// </summary>
        /// <returns>Awaitable <see cref="Task" />.</returns>
        private async Task RefreshStateAsync()
        {
            // Make all of the calls to get current status
            var state = await _client.GetRobotStateAsync()
                        .ConfigureAwait(false);

            var topicMap = GetTopicMap(state);

            // Compare to current cached status
            var updates = CompareStatusObjects(_topicMap, topicMap);

            // If updated, publish changes
            if (updates.Count > 0)
            {
                foreach (var update in updates)
                {
                    await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                                  .WithTopic(update.Key)
                                                  .WithPayload(update.Value.Trim())
                                                  .WithAtLeastOnceQoS()
                                                  .WithRetainFlag()
                                                  .Build())
                    .ConfigureAwait(false);
                }

                _topicMap = topicMap;
            }
        }
Пример #4
0
        private async void btnSend_Click(Object sender, EventArgs e)
        {
            var str = txtSend.Text;

            if (String.IsNullOrEmpty(str))
            {
                MessageBox.Show("发送内容不能为空!", Text);
                txtSend.Focus();
                return;
            }

            _config.Save();

            var topic = cbTopic2.Text;
            var qos   = (QualityOfService)cbQos2.SelectedItem.ToInt();

            // 处理换行
            str = str.Replace("\n", "\r\n");

            if (_Client != null)
            {
                _log.Info(str);

                var rs = await _Client.PublishAsync(topic, str, qos);

                if (rs != null)
                {
                    _log.Info("发布成功,Id={0}", rs.Id);
                }
            }
        }
Пример #5
0
        private Task AggregateResults()
        {
            var sensorResults = GetSensorResults().Take(maxValuesToProcess).ToArray();

            var publishTasks = sensorResults.GroupBy(x => x.Parameter)
                               .Select(Aggregate)
                               .Select(x => MqttClient.PublishAsync(microClimateParametersTopic, x));

            return(Task.WhenAll(publishTasks));

            MicroClimateParameterValue Aggregate(IGrouping <ParameterType, SensorResult> parameterValues)
            {
                var aggregator = _parameterAggregators
                                 .Where(x => x.CanAggregate(parameterValues.Key))
                                 .OrderBy(x => x.Order)
                                 .FirstOrDefault();

                if (aggregator == null)
                {
                    throw new InvalidOperationException($"Can't aggregate parameter: {parameterValues.Key}");
                }

                return(aggregator.Aggregate(parameterValues.ToArray(), parameterValues.Key));
            }
        }
Пример #6
0
        public static async Task Publish(string topic, string payload)
        {
            s_ready.WaitOne(10000); // wait for the first connection attempt to complete (one way or the other) since the connection process is async
            int connectTryCount = 0;

            while (connectTryCount < 2 && !s_client.IsConnected)
            {
                Dbg.Write("MQTTPublish - Client NotConnected");
                await Connect().ConfigureAwait(false);

                connectTryCount++;
                Task.Delay(1000 * 2);
            }

            if (s_client.IsConnected == false)
            {
                Dbg.Write("MQTTPublish - Client NotConnected");
            }
            else
            {
                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(topic)
                              .WithPayload(payload)
                              .WithExactlyOnceQoS()
                              .WithRetainFlag()
                              .Build();

                await s_client.PublishAsync(message).ConfigureAwait(false);
            }
        }
Пример #7
0
        private Task PublishAsync(string topic, string payload)
        {
            var task = MqttClient.PublishAsync(topic, payload, MqttQualityOfServiceLevel.AtMostOnce, true);

            task.Wait();
            return(task);
        }
Пример #8
0
            /// <summary>
            /// 发布主题
            /// </summary>
            /// <param name="Message"></param>
            public void Publish(IotTopic topic, string Message, bool isWait = false)
            {
                if (!Enabled)
                {
                    return;
                }

                try
                {
                    if (mqttClient == null)
                    {
                        return;
                    }
                    if (mqttClient.IsConnected == false)
                    {
                        mqttClient.ConnectAsync(options);
                    }

                    if (mqttClient.IsConnected == false)
                    {
                        Console.WriteLine("Publish >>Connected Failed! ");
                        return;
                    }

                    string tp = topicDeviceId + "/" + Enum.GetName(typeof(IotTopic), topic);

                    Console.WriteLine("Publish >>Message: " + Message);
                    MqttApplicationMessageBuilder mamb = new MqttApplicationMessageBuilder()
                                                         .WithTopic(tp)
                                                         .WithPayload(Message)
                                                         .WithExactlyOnceQoS()
                                                         .WithRetainFlag(false);

                    if (isWait == true)
                    {
                        mqttClient.PublishAsync(mamb.Build()).Wait();
                    }
                    else
                    {
                        mqttClient.PublishAsync(mamb.Build());
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine("Publish exception >>" + exp.Message);
                }
            }
Пример #9
0
        private void PublishUnitState(clsUnit unit)
        {
            MqttClient.PublishAsync(unit.ToTopic(Topic.state), unit.ToState(), MqttQualityOfServiceLevel.AtMostOnce, true);

            if (unit.Number < 385)
            {
                MqttClient.PublishAsync(unit.ToTopic(Topic.brightness_state), unit.ToBrightnessState().ToString(), MqttQualityOfServiceLevel.AtMostOnce, true);
            }
        }
Пример #10
0
 private void OnPublishMessage(string message)
 {
     try
     {
         var msg = new MqttApplicationMessage()
         {
             Topic   = PublishTopic,
             Payload = MessageEncoding.GetBytes(message),
             QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
             Retain = false
         };
         _mqttClient?.PublishAsync(msg);
     }
     catch (Exception e)
     {
         OnErrorMessage?.Invoke(e.Message);
     }
 }
Пример #11
0
 private async Task PublishState()
 {
     var message = new MqttApplicationMessageBuilder()
                   .WithTopic($"{ApplicationPrefix}/STATE")
                   .WithPayload("ALIVE")
                   .WithRetainFlag()
                   .Build();
     await MqttClient.PublishAsync(message);
 }
Пример #12
0
        private void PublishConfig()
        {
            PublishAreas();
            PublishZones();
            PublishUnits();
            PublishThermostats();
            PublishButtons();

            MqttClient.PublishAsync($"{Global.mqtt_prefix}/status", "online", MqttQualityOfServiceLevel.AtMostOnce, true);
        }
        /// <summary>
        /// Try to convert sensor raw-data to parsed data used in HomeAssistant
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public override async Task MqttReceiveHandler(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                string payload     = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                var    payloadObj  = JObject.Parse(payload);
                var    serviceData = payloadObj.ContainsKey("servicedata") ? payloadObj["servicedata"].Value <string>() : "";

                // if serviceData not started with ab03, that we can't parse data - skip parsing
                if (!serviceData.StartsWith("ab03"))
                {
                    return;
                }

                // convert hexadecimal string info byte-array
                var payloadBytes = serviceData.FromHexStringToByteArray();

                // create parsed messages
                var temp = payloadBytes.ParseShortLE(9, 8);
                var humi = payloadBytes.ParseShortLE(11, 2);
                var illu = payloadBytes.ParseTwoBytesLE(13);
                var batt = payloadBytes[8];

                // add values into dictionary to easy search by sensor-type
                var vals = new Dictionary <IHassComponent, object>
                {
                    { ComponentList.First(e => e.DeviceClass == "temperature"), temp },
                    { ComponentList.First(e => e.DeviceClass == "humidity"), humi },
                    { ComponentList.First(e => e.DeviceClass == "illuminance"), illu },
                    { ComponentList.First(e => e.DeviceClass == "battery"), batt }
                };

                // add values into json
                foreach (var sensor in ComponentList)
                {
                    payloadObj.Add(sensor.DeviceClassDescription.ValueName, JToken.FromObject(vals[sensor]));
                }

                // delete serviceData key, to avoid re-processing of the message
                payloadObj.Remove("servicedata");

                payload = payloadObj.ToString();

                // send message
                await MqttClient.PublishAsync(
                    $"{string.Format(ComponentList[0].StateTopic, WorkersConfiguration.ServiceName)}/{payloadObj.Value<string>("id").Replace(":", "")}",
                    payload, MqttConfiguration.MqttQosLevel, false);

                Logger.LogInformation($"WorkerABN03 send message: {payload} at {DateTimeOffset.Now}");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"WorkerABN03 error at {DateTimeOffset.Now}");
            }
        }
Пример #14
0
        private async void btnSend_Click(object sender, EventArgs e)
        {
            btnSend.Enabled      = false;
            btnSubscribe.Enabled = false;

            string topic  = txtPublishTopic.Text.Trim();
            string txtmsg = txtSendMsg.Text.Trim();

            if (string.IsNullOrWhiteSpace(txtmsg))
            {
                MessageBox.Show("发布内容不能为空");
                return;
            }
            //var msg = new MqttApplicationMessage(topic,Encoding.UTF8.GetBytes(txtmsg),MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.AtMostOnce,false);

            MqttApplicationMessage msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(txtmsg)
                                         .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce).WithRetainFlag(false).Build();

            await mqttClient.PublishAsync(msg);
        }
Пример #15
0
        private static async Task SendMessageAsync(string topic, string message, bool retain)
        {
            cumulus.LogDataMessage($"MQTT: publishing to topic '{topic}', message '{message}'");
            var mqttMsg = new MqttApplicationMessageBuilder()
                          .WithTopic(topic)
                          .WithPayload(message)
                          .WithRetainFlag(retain)
                          .Build();

            await mqttClient.PublishAsync(mqttMsg, CancellationToken.None);
        }
Пример #16
0
        /// <summary>
        /// 发布主题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Publish(string topic, string content)
        {
            if (string.IsNullOrEmpty(topic))
            {
                Status = "发布主题不能为空!";
                return;
            }
            var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(content), MqttQualityOfServiceLevel.AtMostOnce, false);

            mqttClient.PublishAsync(appMsg);
        }
Пример #17
0
        public void PublishUrl(string url)
        {
            var dataModel = new PublishedDataModel(url, DateTime.Now.ToString("yyyyMMddHHmmss"), false);
            var message   = new MqttApplicationMessageBuilder()
                            .WithTopic(Prop.Topic)
                            .WithPayload(JsonConvert.SerializeObject(dataModel))
                            .WithAtLeastOnceQoS()
                            .WithRetainFlag()
                            .Build();

            MqttClient.PublishAsync(message, CancellationToken.None);
        }
        /// <summary>
        /// Handler for Google Home SYNC intent.
        /// </summary>
        /// <param name="syncIntentReceivedEvent">The SYNC intent to handle.</param>
        private async void HandleGoogleHomeSyncIntent(SyncIntentReceivedEvent syncIntentReceivedEvent)
        {
            var delegateTopic   = $"{TopicRoot}/sync/lastRequest";
            var delegatePayload = syncIntentReceivedEvent.Time.ToString();

            await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                          .WithTopic(delegateTopic)
                                          .WithPayload(delegatePayload)
                                          .WithAtLeastOnceQoS()
                                          .Build())
            .ConfigureAwait(false);
        }
        /// <summary>
        /// Handler for Google Home QUERY intent.
        /// </summary>
        /// <param name="queryIntentReceivedEvent">The QUERY intent to handle.</param>
        private async void HandleGoogleHomeQueryIntent(QueryIntentReceivedEvent queryIntentReceivedEvent)
        {
            var delegateTopic   = $"{TopicRoot}/query/lastRequest";
            var delegatePayload = JsonConvert.SerializeObject(queryIntentReceivedEvent);

            await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                          .WithTopic(delegateTopic)
                                          .WithPayload(delegatePayload)
                                          .WithAtLeastOnceQoS()
                                          .Build())
            .ConfigureAwait(false);
        }
Пример #20
0
        /// <summary>
        /// Setup logging for the MqttClient.
        /// </summary>
        private void SetupMqttLogging()
        {
            // Log trace messages
            MqttNetGlobalLogger.LogMessagePublished += (sender, e) =>
            {
                switch (e.TraceMessage.Level)
                {
                case MqttNetLogLevel.Error:
                    _serviceLog.LogError(e.TraceMessage.Message, e.TraceMessage.Exception);
                    break;

                case MqttNetLogLevel.Warning:
                    _serviceLog.LogWarning(e.TraceMessage.Message);
                    break;

                case MqttNetLogLevel.Info:
                    _serviceLog.LogInformation(e.TraceMessage.Message);
                    break;

                case MqttNetLogLevel.Verbose:
                default:
                    _serviceLog.LogTrace(e.TraceMessage.Message);
                    break;
                }
            };

            // Log connect and disconnect events
            MqttClient.Connected += async(sender, e) =>
            {
                // Publish connected announcement, due to structure of these apps, it is always assumed the device is connected
                await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                              .WithTopic($"{TopicRoot}/connected")
                                              .WithPayload(((int)ConnectionStatus.ConnectedMqttAndDevice).ToString())
                                              .WithAtLeastOnceQoS()
                                              .WithRetainFlag()
                                              .Build());

                _serviceLog.LogInformation("MQTT Connection established");
            };

            MqttClient.ConnectingFailed += (sender, e) => _serviceLog.LogWarning("MQTT Connection failed, retrying...");
            MqttClient.Disconnected     += (sender, e) =>
            {
                if (!_stopping)
                {
                    _serviceLog.LogInformation("MQTT Connection closed unexpectedly, reconnecting...");
                }
                else
                {
                    _serviceLog.LogInformation("MQTT Connection closed");
                }
            };
        }
Пример #21
0
        public void Publish(string topic, string inputString)
        {
            if (string.IsNullOrEmpty(topic))
            {
                //Console.WriteLine("发布主题不能为空!");
                return;
            }

            var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);

            mqttClient.PublishAsync(appMsg);
            //Console.WriteLine("发送中...");
        }
Пример #22
0
 private async Task PublishAlarms(params Alarm[] oldAlarms)
 {
     var messages = Alarms
                    .Select(alarm => new MqttApplicationMessageBuilder()
                            .WithTopic($"{ApplicationPropertyPrefix}/alarms/{alarm.ApplicationId}/{alarm.Component}")
                            .WithPayload($"{alarm.Temperature}°C")
                            .Build())
                    .Union(oldAlarms.Select(alarm => new MqttApplicationMessageBuilder()
                                            .WithTopic($"{ApplicationPropertyPrefix}/alarms/{alarm.ApplicationId}/{alarm.Component}")
                                            .WithPayload("resolved")
                                            .Build()));
     await MqttClient.PublishAsync(messages);
 }
Пример #23
0
 private void PublishThermostatState(clsThermostat thermostat)
 {
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.current_operation), thermostat.ToOperationState(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.current_temperature), thermostat.TempText(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.current_humidity), thermostat.HumidityText(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.temperature_heat_state), thermostat.HeatSetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.temperature_cool_state), thermostat.CoolSetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.humidify_state), thermostat.HumidifySetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.dehumidify_state), thermostat.DehumidifySetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.mode_state), thermostat.ModeText().ToLower(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.fan_mode_state), thermostat.FanModeText().ToLower(), MqttQualityOfServiceLevel.AtMostOnce, true);
     MqttClient.PublishAsync(thermostat.ToTopic(Topic.hold_state), thermostat.HoldStatusText().ToLower(), MqttQualityOfServiceLevel.AtMostOnce, true);
 }
Пример #24
0
        public async override void PublishTopic(string topic, string payload)
        {
            var message = new MqttApplicationMessage()
            {
                Topic   = topic,
                Payload = Encoding.UTF8.GetBytes(payload)
            };
            await mqttClient.PublishAsync(message);

            if (IsShowInput)
            {
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}MQTT已发布主题{topic}");
            }
        }
Пример #25
0
        private async Task SendMsg(MqttClient mqttclient, Guid userid, string channelId)
        {
            var sendTopic = $"topic/createmeeting/{userid.ToString().ToLower()}";
            var sendMsg   = JsonConvert.SerializeObject(new ChannelTokenModel
            {
                Token     = "12345",
                ChannelId = channelId
            });

            var msg = new MqttApplicationMessageBuilder().WithTopic(sendTopic).WithPayload(sendMsg).WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce).WithRetainFlag(false).Build();


            mqttclient.PublishAsync(msg);
        }
Пример #26
0
        private void PublishZoneState(clsZone zone)
        {
            MqttClient.PublishAsync(zone.ToTopic(Topic.state), zone.ToState(), MqttQualityOfServiceLevel.AtMostOnce, true);
            MqttClient.PublishAsync(zone.ToTopic(Topic.basic_state), zone.ToBasicState(), MqttQualityOfServiceLevel.AtMostOnce, true);

            if (zone.IsTemperatureZone())
            {
                MqttClient.PublishAsync(zone.ToTopic(Topic.current_temperature), zone.TempText(), MqttQualityOfServiceLevel.AtMostOnce, true);
            }
            else if (zone.IsHumidityZone())
            {
                MqttClient.PublishAsync(zone.ToTopic(Topic.current_humidity), zone.TempText(), MqttQualityOfServiceLevel.AtMostOnce, true);
            }
        }
Пример #27
0
        /// <summary>
        /// Handles publishing updates to the harmony current activity to MQTT.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void Harmony_CurrentActivityUpdated(object sender, ActivityUpdatedEventArgs e)
        {
            var currentActivity = _harmonyConfig.Activity.FirstOrDefault(x => x.Id == e.Id.ToString())?.Label;

            _log.LogInformation("Harmony current activity updated: " + currentActivity);

            await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                          .WithTopic(TopicRoot + "/activity")
                                          .WithPayload(currentActivity)
                                          .WithAtLeastOnceQoS()
                                          .WithRetainFlag()
                                          .Build())
            .ConfigureAwait(false);
        }
Пример #28
0
        public void Publish(string topic, byte[] payload, MqttQosLevel qosLevel)
        {
            try
            {
                var message = new MqttApplicationMessage(topic, payload, (MqttQualityOfServiceLevel)qosLevel, false);
                _client.PublishAsync(message).Wait();

                _log.Verbose($"Published message '{topic}' [{Encoding.UTF8.GetString(payload)}].");
            }
            catch (Exception exception)
            {
                _log.Error(exception, $"Failed to publish message '{topic}' [{Encoding.UTF8.GetString(payload)}].");
            }
        }
Пример #29
0
        private void BtnPublish_Click(object sender, EventArgs e)
        {
            string topic = txtPubTopic.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("Publish topic was empty!");
                return;
            }

            string inputString = txtSendMessage.Text.Trim();
            var    appMsg      = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);

            mqttClient.PublishAsync(appMsg);
        }
Пример #30
0
        private void button_Release_Click(object sender, EventArgs e)
        {
            string topic = textBox_Release.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("发布主题不能为空!");
                return;
            }

            string inputString = richTextBox_Release.Text.Trim();
            var    appMsg      = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);

            mqttClient.PublishAsync(appMsg);
        }