Пример #1
0
        public async Task <OutboundResponse> Handle(OutboundRequest request, CancellationToken cancellationToken)
        {
            // TODO handle response

            if (request.Payload != null)
            {
                await _mqttClient.PublishAsync(builder =>
                                               builder
                                               .WithTopic(request.Topic)
                                               .WithMessage(request.Message)
                                               .WithPayload(request.Payload)
                                               .WithCorrelationData(request.CorrelationData)
                                               .WithUserProperty("messageType", request.MessageType)
                                               .WithUserProperty("payloadType", request.PayloadType)
                                               .WithUserProperty("serialization", "json")
                                               .WithUserProperty("encoding", "utf8")
                                               , cancellationToken);
            }
            else
            {
                await _mqttClient.PublishAsync(builder =>
                                               builder
                                               .WithTopic(request.Topic)
                                               .WithMessage(request.Message)
                                               .WithUserProperty("messageType", request.MessageType)
                                               , cancellationToken);
            }

            return(new OutboundResponse()
            {
                Success = true
            });
        }
 public async Task PublishAsync(MqttApplicationMessage message)
 {
     if (clientMqtt != null)
     {
         await clientMqtt.PublishAsync(message);
     }
 }
Пример #3
0
        private async void TimerCallback(object stateInfo)
        {
            _timersMutex.WaitOne();

            try
            {
                var timerDetails = (TimerDetails)stateInfo;
                var topic        = $"mqtttimer/{timerDetails.Name}";

                _logger.LogInformation($"Timer callback for {timerDetails.Name} called.");
                _logger.LogInformation($"Publishing payload '{timerDetails.ResponsePayload}' to topic {topic}");

                var managedMqttApplicationMessage = new ManagedMqttApplicationMessageBuilder()
                                                    .WithApplicationMessage(new MqttApplicationMessageBuilder()
                                                                            .WithTopic(topic)
                                                                            .WithPayload(timerDetails.ResponsePayload)
                                                                            .WithAtLeastOnceQoS()
                                                                            .WithRetainFlag()
                                                                            .Build())
                                                    .Build();

                await _mqttClient.PublishAsync(managedMqttApplicationMessage);
            }
            finally
            {
                _timersMutex.ReleaseMutex();
            }
        }
Пример #4
0
 public async Task Handle(OutboundNotification notification, CancellationToken cancellationToken)
 {
     if (notification.Payload != null)
     {
         await _mqttClient.PublishAsync(builder =>
                                        builder
                                        .WithTopic(notification.Topic)
                                        .WithMessage(notification.Message)
                                        .WithPayload(notification.Payload)
                                        .WithUserProperty("messageType", notification.MessageType)
                                        .WithUserProperty("payloadType", notification.PayloadType)
                                        .WithUserProperty("serialization", "json")
                                        .WithUserProperty("encoding", "utf8")
                                        , cancellationToken);
     }
     else
     {
         await _mqttClient.PublishAsync(builder =>
                                        builder
                                        .WithTopic(notification.Topic)
                                        .WithMessage(notification.Message)
                                        .WithUserProperty("messageType", notification.MessageType)
                                        , cancellationToken);
     }
 }
Пример #5
0
        private async void PowerOnAsync()
        {
            airconPowerToolStripMenuItem.Checked = true;
            notifyIcon1.Icon = Properties.Resources.PowerOn;
#if DEBUG
            Console.WriteLine("Power On");
#else
            await mqttClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("cmnd/" + TB_DevID.Text + "/mode").WithPayload("cool").Build());
#endif
        }
Пример #6
0
        public async Task OtaUpdateDevice(string deviceFriendlyName)
        {
            var device = _stateService.FindDeviceById(deviceFriendlyName, out _);

            var msg = new MqttApplicationMessageBuilder()
                      .WithTopic($"{_settings.CurrentSettings.BaseTopic}/bridge/ota_update/update")
                      .WithPayload(device.FriendlyName)
                      .Build();

            await _client.PublishAsync(msg);
        }
Пример #7
0
 /// <summary>
 /// Publish Message.
 /// </summary>
 /// <param name="topic">Topic.</param>
 /// <param name="payload">Payload.</param>
 /// <param name="retainFlag">Retain flag.</param>
 /// <param name="qos">Quality of Service.</param>
 /// <returns>Task.</returns>
 public static async Task PublishAsync(string topic, string payload, bool retainFlag = true, int qos = 1) =>
 await client.PublishAsync(new MqttApplicationMessageBuilder()
                           .WithTopic(topic)
                           .WithPayload(payload)
                           .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos)
                           .WithRetainFlag(retainFlag)
                           .Build());
Пример #8
0
        async void LogEventRaised(object sender, LogEventArgs e)
        {
            if (mqttClient == null || mqttClient.IsConnected == false)
            {
                return;
            }
            string json = JsonConvert.SerializeObject(e);
            var    applicationMessage = new MqttApplicationMessageBuilder()
                                        .WithTopic("log/" + e.Assembly)
                                        .WithPayload(json)
                                        .WithAtLeastOnceQoS()
                                        .WithRetainFlag(false)
                                        .Build();

            await mqttClient.PublishAsync(applicationMessage);
        }
        public async void Receive(Message receivedMessage)
        {
            _logger.Debug($"IoT Edge Message Received from Broker: {JsonConvert.SerializeObject(receivedMessage)}");
            try
            {
                if (!receivedMessage.Properties.ContainsKey("source"))
                {
                    _logger.Debug("IoT Edge Message received from unknown source");
                    return;
                }

                if (!_moduleConfiguration.ExpectedSources.Contains(receivedMessage.Properties["source"]))
                {
                    _logger.Debug($"IoT Edge Message received from a non-expected source: {receivedMessage.Properties["source"]}");
                    return;
                }

                // Let's forward it along to Smart Connector.
                var messageString = Encoding.ASCII.GetString(receivedMessage.Content);
                _logger.Debug($"Message: {messageString}");
                await _managedMqttClient.PublishAsync(_moduleConfiguration.MqttValueSendTopic, messageString, MqttQualityOfServiceLevel.AtLeastOnce, true);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.ToString());
            }
        }
Пример #10
0
    private async Task PublishMessage(IManagedMqttClient mqttClient, string topic, string payload, bool retain,
                                      MqttQualityOfServiceLevel qos)
    {
        var message = new MqttApplicationMessageBuilder().WithTopic(topic)
                      .WithPayload(payload)
                      .WithRetainFlag(retain)
                      .WithQualityOfServiceLevel(qos)
                      .Build();

        _logger.LogDebug("MQTT sending to {Topic}: {Message}", message.Topic, message.ConvertPayloadToString());

        try
        {
            var publishResult = await mqttClient.PublishAsync(message, CancellationToken.None).ConfigureAwait(false);

            if (publishResult.ReasonCode != MqttClientPublishReasonCode.Success)
            {
                throw new MqttPublishException(publishResult.ReasonString);
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message, e);
            throw new MqttPublishException(e.Message, e);
        }
    }
        public async Task SendAsync(IMessage message)
        {
            if (disposedValue)
            {
                throw new InvalidOperationException("Client is disposed.");
            }
            await clientLock.WaitAsync();

            try
            {
                if (client == null)
                {
                    throw new InvalidOperationException($"{nameof(MqttClient)} has to be started to send messages.");
                }
                var mqttMessage = new MqttApplicationMessageBuilder()
                                  .WithTopic(message.Topic)
                                  .WithPayload(JsonConvert.SerializeObject(message))
                                  //.WithExactlyOnceQoS()     // Fails with exception and disconnect!
                                  .Build();
                await client.PublishAsync(mqttMessage);
            }
            finally
            {
                clientLock.Release();
            }
        }
        public void PublishMessage(RawMessage message)
        {
            string topic = message.Topic;

            Log.Debug("publish message topic = " + topic);

            if (string.IsNullOrEmpty(topic))
            {
                Log.Error("publish message is null");

                return;
            }

            var appMsg = new MqttApplicationMessage();

            appMsg.Payload = Encoding.UTF8.GetBytes(message.Payload);
            appMsg.Topic   = topic;
            appMsg.QualityOfServiceLevel = clientConf.Qos;
            appMsg.Retain = false;

            // 上行响应
            client.PublishAsync(appMsg).Wait();

            Log.Debug($"publish msg : publishing message is " + message.Payload);
        }
Пример #13
0
        // FIXME?(AFL): kinda ugly signature
        public void SendRequest(TRequest request, TimeSpan?requestTimeout, string destinationClientID = null, bool retained = false)
        {
            requestTimeout = requestTimeout ?? TimeSpan.FromSeconds(20);

            var wrappedRequest = _requestSerializer.SerializeMessage(request);

            wrappedRequest.Source      = _client.Options.ClientOptions.ClientId;;
            wrappedRequest.Destination = destinationClientID;

            var payload       = _requestSerializer.SerializeWrapper(wrappedRequest);
            var packedMessage = new MqttApplicationMessageBuilder()
                                .WithTopic(RequestTopic)
                                .WithPayload(payload)
                                .WithQualityOfServiceLevel(_qosLevel)
                                .WithRetainFlag(retained)
                                .Build();

            try
            {
                _client.PublishAsync(packedMessage, _cancellationToken.Token).Wait();
            }
            catch (Exception e)
            {
                Log.Error($"Failed to publish response message on topic \"{ResponseTopic}\". Exception: {e}");
                throw;
            }
        }
Пример #14
0
 public async void PublishMessage(string topic, string message)
 {
     MqttApplicationMessageBuilder messageBuilder = new MqttApplicationMessageBuilder()
                                                    .WithTopic(topic)
                                                    .WithPayload(message);
     await client.PublishAsync(messageBuilder.Build(), CancellationToken.None);
 }
Пример #15
0
        public void MQTTPublishMessage(string topic, byte[] payload)
        {
            topic = topic.Replace("//", "/");

            var message = new MqttApplicationMessageBuilder()
                          .WithTopic(topic)
                          .WithPayload(payload)
                          .WithExactlyOnceQoS()
                          .WithRetainFlag()
                          .Build();

            Debug.Log("newClient publishes message: " + topic);

            client.PublishAsync(message);
            currentlyProcessingMessages.Add(message.GetHashCode());
        }
Пример #16
0
 private async Task SendAsync(PacketContainer container, IRoutingInformation routingInfos)
 {
     await _client.PublishAsync(builder => builder
                                .WithPayload(_serializer.Serialize(container))
                                .WithTopic(routingInfos.OutgoingTopic)
                                .WithExactlyOnceQoS());
 }
Пример #17
0
        public async Task PublishMessage(TMessage message, bool retained = false)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var payload       = _serializer.Serialize(message);
            var packedMessage = new MqttApplicationMessageBuilder()
                                .WithTopic(Topic)
                                .WithPayload(payload)
                                .WithQualityOfServiceLevel(_qosLevel)
                                .WithRetainFlag(retained)
                                .Build();

            try
            {
                await _client.PublishAsync(packedMessage, _cancellationToken.Token);
            }
            catch (Exception e)
            {
                Log.Error($"Failed to publish message on topic \"{Topic}\". Exception: {e}");
                throw;
            }
        }
Пример #18
0
        public void Stop()
        {
            Policy
            .HandleResult <MqttClientPublishResult>(r => r.ReasonCode == MqttClientPublishReasonCode.UnspecifiedError)
            .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(2),
                          (exception, timespan) => _logger.LogWarning("Error sending offline message. Retrying..."))
            .Execute(() =>
            {
                var message = _mqttClient.PublishAsync(_lwtMessage);
                message.Wait();
                return(message.Result);
            });

            _mqttClient.StopAsync().Wait();
            _logger.LogDebug("Stopped client");
            _mqttClient.Dispose();
        }
 /// <summary>
 /// Publish a message on to the MQTT broker.
 /// </summary>
 /// <param name="message">The message to publish.</param>
 public async Task PublishAsync(MqttApplicationMessage message)
 {
     if (_managedMqttClient == null)
     {
         throw new MqttConnectionException("Connection not open, please use StartAsync first!");
     }
     await _managedMqttClient.PublishAsync(message).ConfigureAwait(false);
 }
Пример #20
0
        async void MQTTPublish()
        {
            try
            {
                string json = @"{
                  'Name': 'Bad Boys',
                  'ReleaseDate': '1995-4-7T00:00:00',
                  'Genres': [
                    'Action',
                    'Comedy'
                  ]
                }";

                string test = @"{
                  'updateId': 5,
                  'nodeId': 'ns=2;s=cnc362.cnc362.Cycle_Counter_Shift_SL',
                  'name':'Cycle_Counter_Shift_SL',
                  'plexus_Customer_No':'310507',
                  'pcn': 'Avilla',
                  'workcenter_Key': '61314',
                  'workcenter_Code': 'Honda Civic cnc 359 362',  
                  'cnc': '362',
                  'value': 0,
                  'transDate': '2020-06-29 00:00:00'
                }";

                Node node = new Node();
                Console.WriteLine("node.updateId {0}",node.updateId);
                Console.WriteLine("node.nodeId {0}", node.nodeId);
                Console.WriteLine("node.name {0}", node.name);
                // https://stackoverflow.com/questions/7574606/left-function-in-c-sharp/7574645

                node.value = partCounter;
                string json2 = JsonConvert.SerializeObject(node);
                Console.WriteLine("json2=> {0}", json2);


                var payload = Encoding.UTF8.GetBytes(json2);

//                var payload = Encoding.UTF8.GetBytes(partCounter);
                var message = new MqttApplicationMessageBuilder().WithTopic("presence").WithPayload(payload).WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce).WithRetainFlag().Build();

                if (managedMqttClientPublisher != null)
                {
                    await managedMqttClientPublisher.PublishAsync(message);
                    Console.WriteLine("Published Message=>{0}", message);
                }
                else
                {
                    throw new Exception("MQTTPublish => Not connected to MQTT server");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
Пример #21
0
        private async Task OnMessageReceived(MqttApplicationMessageReceivedEventArgs arg)
        {
            var messageTypeString = arg.ApplicationMessage
                                    .UserProperties?
                                    .FirstOrDefault(p => p.Name == "messageType")?
                                    .Value;

            var responseTypeString = arg.ApplicationMessage
                                     .UserProperties?
                                     .FirstOrDefault(p => p.Name == "responseType")?
                                     .Value;

            // Only if there is a responseType specifed do we do request/response processing
            // Otherwise we treat it as a notification.

            // Notification
            if (responseTypeString == null)
            {
                var    messageType     = MessageTypeMapper(messageTypeString);
                Type[] typeArgs        = { messageType };
                var    generic         = typeof(InboundNotification <>);
                var    constructedType = generic.MakeGenericType(typeArgs);
                var    notifyObject    = Activator.CreateInstance(constructedType);

                var inboundNotification = notifyObject as IInboundNotification;
                inboundNotification.RawMessage = arg.ApplicationMessage;
                inboundNotification.PropertyBag["messageType"] = messageTypeString;

                await _mediator.Publish(notifyObject);
            }
            // Request/Response
            else
            {
                var    messageType     = MessageTypeMapper(messageTypeString);
                Type[] typeArgs        = { messageType };
                var    generic         = typeof(InboundRequest <>);
                var    constructedType = generic.MakeGenericType(typeArgs);
                var    requestObject   = Activator.CreateInstance(constructedType);

                var inboundRequest = requestObject as IInboundRequest;
                inboundRequest.RawMessage = arg.ApplicationMessage;
                inboundRequest.PropertyBag["messageType"]  = messageTypeString;
                inboundRequest.PropertyBag["responseType"] = responseTypeString;
                inboundRequest.ResponseTopic   = arg.ApplicationMessage.ResponseTopic;
                inboundRequest.CorrelationData = arg.ApplicationMessage.CorrelationData;

                var response = await _mediator.Send(requestObject) as InboundResponse;

                arg.ProcessingFailed = !response.Success;
                await Task.Run(async() => await _mqttClient.PublishAsync(builder =>
                                                                         builder
                                                                         .WithTopic(response.Topic)
                                                                         .WithPayload(response.Payload)
                                                                         .WithCorrelationData(response.CorrelationData)
                                                                         .WithUserProperty("messageType", response.MessageType)
                                                                         .WithUserProperty("payloadType", response.PayloadType)));
            }
        }
        private void SendMessage(int siteId, string type, string valueName, string value)
        {
            var message = new MqttApplicationMessageBuilder()
                          .WithTopic($"solaredge/state/{siteId}/{type.ToLowerInvariant()}/{valueName.ToLowerInvariant()}")
                          .WithPayload(value)
                          .Build();

            _managedMqttClient.PublishAsync(message).Wait();
        }
Пример #23
0
 public async Task PublishAsync(string topic, string payload)
 {
     var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(topic)
                              .WithPayload(payload)
                              .Build();
     var manegedApplicationMessage = new ManagedMqttApplicationMessageBuilder().WithApplicationMessage(applicationMessage)
                                     .Build();
     await _mqttClient.PublishAsync(manegedApplicationMessage);
 }
Пример #24
0
        public async Task SendMessageAsync(string topic, string message)
        {
            var msg = new MqttApplicationMessageBuilder()
                      .WithTopic(topic)
                      .WithPayload(message)
                      .Build();

            await _mqttClient.PublishAsync(msg);
        }
Пример #25
0
        private async Task CountAsync()
        {
            await Semaphore.WaitAsync().ConfigureAwait(false);

            try
            {
                using var scope = _scopeFactory.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                if (executionCount >= 100)
                {
                    executionCount = 0;
                }
                var count = Interlocked.Increment(ref executionCount);
                _logger.LogInformation("[MQTT] Counter is working. Count: {Count}", count);
                var counters = dbContext.Counters.ToList();
                counters.Add(new Common.Counter
                {
                    NodeId          = _serviceSettings.NodeId,
                    Count           = count,
                    LocalRecordTime = DateTime.Now
                });
                if (_client.IsConnected)
                {
                    var message = new MqttApplicationMessageBuilder()
                                  .WithTopic("/count")
                                  .WithPayload(JsonSerializer.Serialize(counters.AsEnumerable()))
                                  .WithAtLeastOnceQoS()
                                  .Build();
                    await _client.PublishAsync(message, CancellationToken.None);

                    if (dbContext.Counters.Any())
                    {
                        _logger.LogTrace("[MQTT] succeeded. going to delete localDb records");
                        dbContext.Counters.RemoveRange(dbContext.Counters);
                        await dbContext.SaveChangesAsync();
                    }
                }
                else
                {
                    await dbContext.Counters.AddAsync(new Common.Counter
                    {
                        NodeId          = _serviceSettings.NodeId,
                        Count           = count,
                        LocalRecordTime = DateTime.Now
                    });

                    await dbContext.SaveChangesAsync();

                    _logger.LogWarning("[MQTT] failed. Recorded to localDb: {Count}", count);
                }
            }
            finally
            {
                Semaphore.Release();
            }
        }
Пример #26
0
 public static Task SendJsonAsync(this IManagedMqttClient mqttClient, string topic, JToken doc, CancellationToken token = default)
 {
     return(mqttClient.PublishAsync(new MqttApplicationMessage
     {
         Topic = topic,
         Retain = true,
         QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
         Payload = ConvertJson(doc)
     }, token));
 }
Пример #27
0
 public async Task Publish(string topic, string payload)
 {
     _logger.LogInformation($"Publishing Topic: {topic} Payload: {payload}");
     await _mqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                    .WithTopic(topic)
                                    .WithPayload(payload)
                                    .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
                                    .WithRetainFlag()
                                    .Build());
 }
 public async Task PublishAsync(string topic, string payload, bool retainFlag = false, int qos = 2)
 {
     _logger.LogInformation("she efe pami ni");
     await _client.PublishAsync(new MqttApplicationMessageBuilder()
                                .WithTopic (topic)
                                .WithPayload (payload)
                                .WithQualityOfServiceLevel ((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos)
                                .WithRetainFlag (retainFlag)
                                .Build());
 }
Пример #29
0
 private async Task PublishAsync(String topic, String value)
 {
     var message = new MqttApplicationMessageBuilder()
                   .WithTopic(topic)
                   .WithPayload(value)
                   .WithExactlyOnceQoS()
                   // .WithRetainFlag()
                   .Build();
     await MqttClient.PublishAsync(message);
 }
Пример #30
0
        private async Task SetLastSeen()
        {
            var msg = new MqttApplicationMessageBuilder()
                      .WithTopic($"{_settings.CurrentSettings.BaseTopic}/bridge/config/last_seen")
                      .WithPayload("epoch")
                      .Build();

            await _client.PublishAsync(msg);
        }