Ejemplo n.º 1
0
        private async Task HandleMqttApplicationMessageAsync(MqttApplicationMessage applicationMessage)
        {
            string topic = applicationMessage.Topic;

            if (topic.StartsWith(ApplicationCommandPrefix))
            {
                if (topic == $"{ApplicationCommandPrefix}/shutdown")
                {
                    string shutdownToken = applicationMessage.ConvertPayloadToString();
                    if (shutdownToken == "very-secret")
                    {
                        ShutdownFromRemote.SetResult(true);
                    }
                    else
                    {
                        Console.WriteLine($"{topic}: refused");
                    }
                }
                else if (topic == $"{ApplicationCommandPrefix}/rebirth")
                {
                    await PublishBirth();
                }
            }
            else if (topic == $"{ApplicationPropertyPrefix}/temperature-threshold/set")
            {
                string payloadAsString = applicationMessage.ConvertPayloadToString();
                double temperature     = payloadAsString.ToDouble();
                Console.WriteLine($"{topic}: updated temperature threshold from {TemperatureThreshold}°C to {temperature}°C");
                TemperatureThreshold = temperature;
                await PublishCpuThreshold();
            }
            else
            {
                var match = Regex.Match(topic, "^([^/]+)/property/([^/]+)/temperature");
                if (match.Success)
                {
                    string remoteApplicationId = match.Groups[1].Value;
                    string component           = match.Groups[2].Value;
                    string payloadAsString     = applicationMessage.ConvertPayloadToString();
                    string temperatureAsString = Regex.Replace(payloadAsString, "[^0-9\\.]", "");
                    double temperature         = temperatureAsString.ToDouble();
                    await TemperatureReceived(remoteApplicationId, component, temperature);
                }
                else
                {
                    Console.WriteLine($"{topic} unhandled");
                }
            }
        }
Ejemplo n.º 2
0
        void ProcessLogInfo(MqttApplicationMessage applicationMessage)
        {
            string json  = applicationMessage.ConvertPayloadToString();
            var    model = JsonConvert.DeserializeObject <LogInfoModel>(json);

            if (model.Priority == Priorities.LOG_WARNING)
            {
                if (!logWarningsSendTime.TryGetValue(model.Text, out DateTime lastSended))
                {
                    lastSended = model.Time.ToLocalTime();
                    logWarningsSendTime.Add(model.Text, lastSended);
                }
                else
                {
                    if (DateTime.Now.Subtract(lastSended).TotalMinutes < 30)
                    {
                        return;
                    }
                    else
                    {
                        logWarningsSendTime[model.Text] = model.Time.ToLocalTime();
                    }
                }
            }
            telegramBotService.SendMessage($"{model.Text} {model.Data}");
        }
Ejemplo n.º 3
0
        public async Task Handle(string[] topicLevels, MqttApplicationMessage message, CancellationToken token = default)
        {
            Match mtch       = _thermostatRegex.Match(topicLevels[0]);
            int   controller = int.Parse(mtch.Groups["controller"].Value);
            int   thermostat = int.Parse(mtch.Groups["thermostat"].Value);

            int obj = UponorObjects.Thermostat(UponorThermostats.RoomSetpoint, controller, thermostat);

            string convertPayloadToString = message.ConvertPayloadToString();
            float  newSetpoint            = float.Parse(convertPayloadToString, _parsingCulture);

            _logger.LogInformation("Setting c{Controller} t{Thermostat} setpoint to {Value}", controller, thermostat, newSetpoint);

            await _client.SetValue(obj, UponorProperties.Value, newSetpoint, token);

            // Perform new read, wait until the value is applied
            using CancellationTokenSource cts          = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            using CancellationTokenSource timeoutToken = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, token);

            (_, UponorResponseContainer responseContainer) = await _client.WaitUntil(obj, UponorProperties.Value,
                                                                                     testContainer =>
            {
                if (!testContainer.TryGetValue(obj, UponorProperties.Value, out float appliedFloat))
                {
                    return(false);
                }

                return(Math.Abs(appliedFloat - newSetpoint) < 0.5f);
            }, timeoutToken.Token);

            _featureManager.Process(responseContainer);
            await _hassMqttManager.FlushAll(token);
        }
Ejemplo n.º 4
0
        private TimerDetails GetTimerDetails(MqttApplicationMessage message)
        {
            var topic   = message.Topic;
            var payload = message.ConvertPayloadToString();

            _logger.LogInformation($"Recevied message with Topic '{topic}', Payload '{payload}'");

            if (string.IsNullOrWhiteSpace(topic))
            {
                _logger.LogWarning("Ignoring message with empty topic");
                return(null);
            }

            var topicParts = topic.Split('/');

            if (topicParts.Length != 3)
            {
                _logger.LogWarning("Ignoring message with unrecognised topic format.");
                return(null);
            }

            var payloadJObject = JObject.Parse(payload);

            Enum.TryParse <CommandType>(topicParts[2], ignoreCase: true, out var command);
            return(new TimerDetails
            {
                Name = topicParts[1],
                Command = command,
                UnixTriggerTimeSeconds = (long)payloadJObject["triggerTimeSeconds"],
                ResponsePayload = payloadJObject["responsePayload"].ToString()
            });
        }
Ejemplo n.º 5
0
        private Task HandleMessageReceived(MqttApplicationMessage message)
        {
            Logger.LogTrace("Message received");
            Match match = CommandTopicRegex.Match(message.Topic);

            if (match.Success)
            {
                string waterControllerId = match.Groups[WATER_CONTROLLER_ID_REGEX_GROUP].Value;
                string command           = match.Groups[COMMAND_NAME_REGEX_GROUP].Value;
                string payload           = message.ConvertPayloadToString();
                if (!WaterSystem.TryGet(waterControllerId, out IWaterController waterController))
                {
                    Logger.LogWarning($"Water controller: '{waterControllerId}' not found");
                    return(Task.CompletedTask);
                }
                switch (command)
                {
                case FLOW_TOPIC:
                    break;

                default:
                    Logger.LogWarning($"Unknown command topic '{command}'");
                    return(SendCommandResponseAsync(waterControllerId, COMMAND_UNKNOWN_PAYLOAD));
                }
                switch (payload)
                {
                case ON_PAYLOAD:
                    if (!waterController.IsOn)
                    {
                        waterController.TurnOn();
                    }
                    else
                    {
                        Logger.LogTrace($"Water controller: '{waterControllerId}' is already on");
                    }
                    return(SendCommandResponseAsync(waterControllerId, COMMAND_FLOW_ON_PAYLOAD));

                case OFF_PAYLOAD:
                    if (waterController.IsOn)
                    {
                        waterController.TurnOff();
                    }
                    else
                    {
                        Logger.LogTrace($"Water controller: '{waterControllerId}' is already off");
                    }
                    return(SendCommandResponseAsync(waterControllerId, COMMAND_FLOW_OFF_PAYLOAD));

                default:
                    Logger.LogWarning($"Unknown payload '{payload}'");
                    return(Task.CompletedTask);
                }
            }
            else
            {
                Logger.LogTrace("Topic does not match expectation");
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 6
0
        void ProcessCycleStatistics(MqttApplicationMessage applicationMessage)
        {
            string json = applicationMessage.ConvertPayloadToString();

            try {
                var model = JsonConvert.DeserializeObject <BoilerInfoModel>(json);
                model.Sensors.Add(new Sensor()
                {
                    SensorId = Sensor.SensorIdForBoilerRequired,
                    Last     = model.BoilerRequired,
                    Time     = model.CycleStart,
                    Average  = model.BoilerRequired
                });
                model.Sensors.Add(new Sensor()
                {
                    SensorId = Sensor.SensorIdForBoilerState,
                    Last     = model.IsBoilerOn ? 0.4 : 0,
                    Time     = model.CycleStart,
                    Average  = model.IsBoilerOn ? 0.4 : 0
                });
                model.ReciveTime = DateTime.UtcNow;
                readerWriterLockSlim.EnterWriteLock();
                try {
                    boilerInfoModel = model;
                    SaveValidValues(model);
                    if (boilerInfoModel.ReciveTime.Subtract(lastFullModelRecieved).TotalMinutes >= 10)
                    {
                        if (infoModelsHistory.Count >= QueueCapacity)
                        {
                            infoModelsHistory.Dequeue();
                        }
                        SubstituteEmptyValues(model);
                        infoModelsHistory.Enqueue(model);
                        lastFullModelRecieved = boilerInfoModel.ReciveTime;
                    }
                    if (voltageModelsHistory.Count >= QueueCapacity * 2)
                    {
                        voltageModelsHistory.Dequeue();
                    }
                    model = new BoilerInfoModel()
                    {
                        ReciveTime = DateTime.UtcNow
                    };
                    var sensor = boilerInfoModel.Sensors.First(s => s.SensorId == 103);
                    model.Sensors = new List <Sensor>()
                    {
                        (Sensor)sensor.Clone()
                    };
                    if (voltageModelsHistory.Count == 0 || Math.Abs(voltageModelsHistory.Peek().Sensors[0].Last - sensor.Last) > 0.005 || sensor.Time.Subtract(voltageModelsHistory.Peek().Sensors[0].Time).TotalSeconds > 5)
                    {
                        voltageModelsHistory.Enqueue(model);
                    }
                } finally {
                    readerWriterLockSlim.ExitWriteLock();
                }
            } catch { }
        }
Ejemplo n.º 7
0
        private async Task ProcessMessageAsync(MqttDevice device, MqttApplicationMessage applicationMessage)
        {
            string value;
            bool   matched;

            // topic path
            if (string.IsNullOrEmpty(device.TopicPath))
            {
                var messageValue = applicationMessage.ConvertPayloadToString();
                matched = messageValue.Equals(device.TopicValue, StringComparison.InvariantCultureIgnoreCase);
                value   = device.Value;

                Log.Verbose("[{where}] Processed message: got {messageValue} - expected {value} - matched: {matched}", nameof(MQTTServer), messageValue, value, matched);
            }
            // read the value from the payload, using the path
            else
            {
                var json       = applicationMessage.ConvertPayloadToString();
                var jsonObject = JObject.Parse(json);
                value = device.TopicPath == "." ? json : (string)jsonObject.SelectToken(device.TopicPath);

                if (!string.IsNullOrEmpty(device.AlternateTopicPath) && string.IsNullOrEmpty(value))
                {
                    value = device.AlternateTopicPath == "." ? json : (string)jsonObject.SelectToken(device.AlternateTopicPath);
                }

                matched = true;

                Log.Verbose("[{where}] Processed message: got {value}", nameof(MQTTServer), value);
            }

            if (matched)
            {
                Log.Information("[{where}] Updating #{deviceID} - {service} / {var} - {value}", nameof(MQTTServer), device.DeviceID, device.Service, device.Variable, value);
                await luupWrapper.UpdateVariablesAsync(device.DeviceID, device.Service, device.Variable, value);
            }
        }
Ejemplo n.º 8
0
        public void integrate_with_serilog_test_remote_mqtt_broker()
        {
            var topic             = "hojmorhovetvomojhoroduktokradmourukousiahnenatvojuslobodu";
            var publisherOptions  = new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io").Build();
            var subscriberOptions = new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io").Build();
            var factory           = new MqttFactory();
            var subscriberClient  = factory.CreateMqttClient();

            subscriberClient.ConnectAsync(subscriberOptions, System.Threading.CancellationToken.None).Wait();

            subscriberClient.SubscribeAsync(new MQTTnet.Client.Subscribing.MqttClientSubscribeOptions()
            {
                TopicFilters = new List <MqttTopicFilter>()
                {
                    new MqttTopicFilter()
                    {
                        Topic = topic
                    }
                }
            },
                                            System.Threading.CancellationToken.None).Wait();


            MqttApplicationMessage appMessage = null;

            subscriberClient.UseApplicationMessageReceivedHandler((m) => appMessage = m.ApplicationMessage);

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MQTT(publisherOptions, topic)
                         .CreateLogger();

            Log.Fatal("this is fatal");

            while (appMessage == null)
            {
                System.Threading.Thread.Sleep(10);
            }

            var payload = LogMqttMessagePayload.GetPayload(appMessage.ConvertPayloadToString());

            Assert.AreEqual("this is fatal", payload.MessageTemplate);
            Assert.AreEqual("Fatal", payload.Level);
        }
Ejemplo n.º 9
0
        static async Task ExecuteTestAsync(string name, MqttClientOptions options)
        {
            try
            {
                Write("Testing '" + name + "'... ", ConsoleColor.Gray);
                var factory = new MqttFactory();
                //factory.UseWebSocket4Net();
                var client = factory.CreateMqttClient();
                var topic  = Guid.NewGuid().ToString();

                MqttApplicationMessage receivedMessage = null;
                client.ApplicationMessageReceivedAsync += e =>
                {
                    receivedMessage = e.ApplicationMessage;
                    return(PlatformAbstractionLayer.CompletedTask);
                };

                await client.ConnectAsync(options);

                await client.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce);

                await client.PublishStringAsync(topic, "Hello_World", MqttQualityOfServiceLevel.AtLeastOnce);

                SpinWait.SpinUntil(() => receivedMessage != null, 5000);

                if (receivedMessage?.Topic != topic || receivedMessage?.ConvertPayloadToString() != "Hello_World")
                {
                    throw new Exception("Message invalid.");
                }

                await client.UnsubscribeAsync(topic);

                await client.DisconnectAsync();

                Write("[OK]\n", ConsoleColor.Green);
            }
            catch (Exception e)
            {
                Write("[FAILED] " + e.Message + "\n", ConsoleColor.Red);
            }
        }
Ejemplo n.º 10
0
 public HildebrandState(MqttApplicationMessage message)
 {
     Topic = message.Topic;
     Json  = message.ConvertPayloadToString();
 }
Ejemplo n.º 11
0
        public async Task ExecuteAsync_PublishMeasurementData_CorrectlyPublished()
        {
            MqttApplicationMessage publishedMessage = null;
            var sensorDevice = new SensorDevice()
            {
                Id = "Device1",
                SensorDeviceTypeId = "DeviceType1"
            };

            var sensorDeviceType = new SensorDeviceType()
            {
                Id      = "DeviceType1",
                Sensors = new List <Sensor>()
                {
                    new Sensor()
                    {
                        Id = "Sensor1",
                    }
                }
            };

            //Arrange
            var config = new CollectorConfiguration
            {
                CollectorEnabled     = true,
                BluetoothAdapterName = "test",
                ScanIntervalSeconds  = 0,
                SensorDevices        = new List <SensorDevice>()
                {
                    sensorDevice
                },
                SensorDeviceTypes = new List <SensorDeviceType>()
                {
                    sensorDeviceType
                }
            };

            var measurementData = new MeasurementData()
            {
                SensorDeviceId = sensorDevice.Id, SensorId = sensorDeviceType.Sensors[0].Id, Timestamp = DateTime.Now, Value = "123"
            };
            var measurementList = new List <MeasurementData>()
            {
                measurementData
            };

            _mqttClientMock.Setup(m => m.IsConnected).Returns(true);
            _mqttClientMock.Setup(m => m.PublishAsync(It.IsAny <MqttApplicationMessage>(), CancellationToken.None)).Callback((MqttApplicationMessage message, CancellationToken ct) => { publishedMessage = message; });
            _configMock.Setup(c => c.Value).Returns(config);
            _deviceScannerMock.Setup(d => d.GetDeviceDataAsync(config.SensorDevices)).ReturnsAsync(measurementList);

            //Act
            var btGwService = _serviceProvider.GetService <CollectorService>();
            var cts         = new CancellationTokenSource();

#pragma warning disable CS4014
            // Run as fire & forget
            Task.Run(() => btGwService.StartAsync(cts.Token).ConfigureAwait(false));
#pragma warning restore CS4014

            await Task.Delay(100);

            cts.Cancel();

            var expectedMessage = $"{Constant.TopicMeasurement}/{sensorDevice.Location}/{sensorDevice.Id}/{measurementData.SensorId}";
            Assert.AreEqual(expectedMessage, publishedMessage.Topic, "Published topic was incorrect");
            Assert.AreEqual(measurementData.Value, publishedMessage.ConvertPayloadToString(), "Published payload was incorrect");
        }
Ejemplo n.º 12
0
 private async Task SendMessage(IManagedMqttClient client, MqttApplicationMessage message)
 {
     Logger.LogInformation("< [{topic}] {payload}", message.Topic, message.ConvertPayloadToString());
     await client.PublishAsync(message);
 }
Ejemplo n.º 13
0
 String ReplaceKeywords(SettingsHandler h, MqttApplicationMessage message, string input)
 {
     return(input.Replace("%topic%", message.Topic)
            .Replace("%payload%", message.ConvertPayloadToString()));
 }
Ejemplo n.º 14
0
        private async Task SendHubEventAsync(string clientId, MqttApplicationMessage message)
        {
            using (var eventMessage = new Message(message.Payload))
            {
                eventMessage.Properties.Add("clientId", clientId);
                eventMessage.Properties.Add("topic", message.Topic);

                Console.WriteLine("\t{0}> Sending message: Data: [{2}]", DateTime.Now.ToLocalTime(), message.ConvertPayloadToString());
                await DeviceClient.SendEventAsync(eventMessage).ConfigureAwait(false);
            }
        }
Ejemplo n.º 15
0
 private async Task HandleMessageReceived(MqttApplicationMessage applicationMessage)
 {
     await ParseMessage(applicationMessage.Topic, applicationMessage.ConvertPayloadToString());
 }