dotnet / dotnet/MQTTnet

Mqtt client with web API

Open
#1,913 0 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

### Describe your question
I have two questions regarding propper implementation of two simple (from description point of view) features.

1) Implement mechanism of publishing message on http request

As per documentation this [ref repo](https://github.com/rafiulgits/mqtt-client-dotnet-core) is propper way of implementing client in .net core.

I will inject it via provider as in repo

```C#
[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
private readonly IMqttClientService mqttClientService;

public SampleController(MqttClientServiceProvider provider)
{
mqttClientService = provider.MqttClientService;
}

[HttpPost]
async Task SendMessage(string topic, string message)
{
await mqttClientService.Publish(topic, message);

return Ok();
}
}
```

Publish method will look like this (I added semaphore because MqttClient is not thread safe to avoid sending too many requests at a time):

```C#
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);

public async Task Publish(string topic, string message)
{
await semaphoreSlim.WaitAsync();
try
{
await mqttClient.PublishStringAsync(topic, message);
}
finally
{
//Very important to release
semaphoreSlim.Release();
}
}
```

2) Handling state of client in the scenario above (when it is disconnected) [similar question to here](https://stackoverflow.com/questions/76781508/how-should-an-mqttnet-clients-lifecycle-be-managed). I'm mentioning since there are a lot of comments in issues stating that ManagedClient is not stable so I would like to stick with low level one.

### Which project is your question related to?
- Client

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.