Code Monkey home page Code Monkey logo

Comments (3)

SeppPenner avatar SeppPenner commented on September 27, 2024

I have tried the following code in https://dotnetfiddle.net/ with Newtonsoft.Json, v 13.0.3 (latest) and MQTTnet, v4.3.6 (latest) without any issues:

using System;
using Newtonsoft.Json;
using MQTTnet;
					
public class Program
{
    public static void Main()
    {
        var m = JsonConvert.SerializeObject("Hello");
		
        var message = new MqttApplicationMessageBuilder()
            .WithTopic("Hans")
            .WithPayload(m)
            .Build();
        Console.WriteLine(message);
    }
}

Just out of curiosity as I had this issue already sometimes:

  1. Try a clean and build.
  2. Close Visual Studio.
  3. Delete all bin and obj folders, maybe also the .vs folder.
  4. Build again and test.

Sometimes, Visual Studio does stupid shit with its caching and therefore errors that are never reproducable anymore occur.

from mqttnet.

sameert89 avatar sameert89 commented on September 27, 2024

I have tried doing that but still the same thing. After repeatedly trying with a script, I can see a lot of messages are just not being published even when the publish result object has IsSuccess True. Is there a bug somewhere in my approach? I have tried to follow the docs provided in the wiki.

from mqttnet.

LeGi0N09 avatar LeGi0N09 commented on September 27, 2024

The issue you're experiencing might be related to how the payload is being handled by the MQTT client. Specifically, there are a few potential areas to investigate:

  1. Serialization: Ensure the payload is correctly serialized into a format that the MQTT client expects.
  2. Encoding: Check if there's any encoding issue with the payload string.
  3. MQTT client configuration: Verify if there are any specific configurations required for the payload.

Here’s a modified version of your code with additional steps to handle these aspects:

public class Function1
{
    private readonly ILogger<Function1> _logger;

    public Function1(ILogger<Function1> logger)
    {
        _logger = logger;
    }

    [Function("Function1")]
    public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
    {
        const string HOST_URL = "xxx-xxx";
        const int PORT = 8883;
        const string TOPIC = "xxxxx";
        string username = "xxxxx";
        string randomName = Path.GetRandomFileName().Replace(".", string.Empty);

        IEnumerable<X509Certificate2> certList = new[]
        {
            new X509Certificate2("./certficate.pfx", "pass")
        };

        var factory = new MqttFactory();
        var client = factory.CreateMqttClient();

        var options = new MqttClientOptionsBuilder()
            .WithTcpServer(HOST_URL, PORT)
            .WithCredentials(username)
            .WithClientId(randomName)
            .WithCleanSession()
            .WithTlsOptions(o => o.WithClientCertificates(certList))
            .Build();

        // Serialize an object instead of a simple string
        var payloadObject = new { Message = "Hello" };
        var m = JsonConvert.SerializeObject(payloadObject);
        _logger.LogInformation(m); // This logs as expected

        try
        {
            await client.ConnectAsync(options, req.HttpContext.RequestAborted);
            var message = new MqttApplicationMessageBuilder()
                .WithTopic(TOPIC)
                .WithPayload(System.Text.Encoding.UTF8.GetBytes(m)) // Ensure the payload is correctly encoded
                .Build();

            await client.PublishAsync(message, req.HttpContext.RequestAborted);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to handle MQTT operation.");
            return new StatusCodeResult(StatusCodes.Status500InternalServerError);
        }
        finally
        {
            if (client.IsConnected)
            {
                await client.DisconnectAsync();
            }
        }

        _logger.LogInformation("C# HTTP trigger function processed a request.");
        return new OkObjectResult("Welcome to Azure Functions!");
    }
}

from mqttnet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.