Comments (3)
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:
- Try a
clean and build
. - Close Visual Studio.
- Delete all
bin
andobj
folders, maybe also the.vs
folder. - Build again and test.
Sometimes, Visual Studio does stupid shit with its caching and therefore errors that are never reproducable anymore occur.
from mqttnet.
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.
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:
- Serialization: Ensure the payload is correctly serialized into a format that the MQTT client expects.
- Encoding: Check if there's any encoding issue with the payload string.
- 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)
- nuget version of MQTTnet.Extensions.TopicTemplate is not up to date HOT 2
- Dose MQTTnet support Native AOT? HOT 1
- Reopen: nuget version of MQTTnet.Extensions.TopicTemplate is not up to date HOT 5
- When using InjectApplicationMessage the client does not receive any message when the topic starts with `$` HOT 5
- How to reconnect properly HOT 2
- sendmessage and mqtt service return function_clause
- Server subscriber sessions hash set can contain sessions with no subscriptions
- how to unsubscibe all topics HOT 1
- Enhancements for the MqttPacketIdentifierProvider HOT 2
- Can support save session to disk or database HOT 1
- Timing of ConnectAsync HOT 1
- Example of WebSocket broker from wiki does not work HOT 3
- MqttNet Connection not established after the Mqttnet Client is Disposed. in MQTTNet Version 4.3.3.952
- MqttClientFactory not fount in MQTTnet.4.3.6.1152 HOT 2
- How to start a MQTT Broker with WebSocket support in .NET Framework 4.6.1? HOT 1
- MQTTClient Thread-safety: Publishing HOT 4
- MQTTClient Thread-safety: Publishing
- Received packet 'PubAck: [PacketIdentifier=6538] [ReasonCode=Success]' at an unexpected time. HOT 4
- ReuseAddress option on Client Socket (as well).
- Certificate Authentication using PFX in .NET472 To Azure HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mqttnet.