示例#1
0
        private static async Task OnReceivedConfigWriteRequest(IMqttClient clientMQTT, LargePayloadReader reader, string moduleID, string topicBase, Connection clientFAST, MqttApplicationMessageReceivedEventArgs arg)
        {
            var msg = arg.ApplicationMessage;

            await arg.AcknowledgeAsync(CancellationToken.None);

            if (msg.Topic.EndsWith("/info"))
            {
                reader.SetInfo(msg.Payload);
                string payload = Encoding.UTF8.GetString(msg.Payload);
                Console.WriteLine($"Got Info msg! ClientID: {arg.ClientId}; Topic: {msg.Topic}; QOS: {msg.QualityOfServiceLevel}; Payload: {payload}");
            }
            else
            {
                int bucket = GetBucketNumberFromTopicName(msg.Topic);
                reader.SetBucket(bucket, msg.Payload);

                Console.WriteLine($"Got Data msg! ClientID: {arg.ClientId}; Topic: {msg.Topic}; Bucket: {bucket}; QOS: {msg.QualityOfServiceLevel}; Payload.Len: {msg.Payload.Length}");
            }

            string?content = reader.Content();

            if (content != null)
            {
                try {
                    var       nv    = new NamedValue("config", content);
                    DataValue value = await clientFAST.CallMethod(moduleID, "SetConfigString", nv);

                    Console.WriteLine("Stored new config!");
                }
                catch (Exception exp) {
                    Exception e = exp.GetBaseException() ?? exp;
                    Console.Error.WriteLine($"Failed to set new config: {e.Message}");

                    byte[] payload = StdJson.ObjectToBytes(new {
                        Hash  = reader.ContentHash,
                        Error = e.Message,
                        Time  = Timestamp.Now.ToString()
                    }, indented: true);

                    var msgInfo = new MqttApplicationMessage()
                    {
                        QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                        Retain = true,
                        Topic  = $"{topicBase}/error",
                        PayloadFormatIndicator = MqttPayloadFormatIndicator.CharacterData,
                        Payload = payload,
                    };

                    await clientMQTT.PublishAsync(msgInfo);
                }
            }
        }