Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mqtt client with web API #1913

Open
mikolajwalus opened this issue Jan 23, 2024 · 0 comments
Open

Mqtt client with web API #1913

mikolajwalus opened this issue Jan 23, 2024 · 0 comments
Labels
question It is a question regarding the project

Comments

@mikolajwalus
Copy link

mikolajwalus commented Jan 23, 2024

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 is propper way of implementing client in .net core.

I will inject it via provider as in repo

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

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

        [HttpPost]
        async Task<IActionResult> 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):

        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();
            }
        }
  1. Handling state of client in the scenario above (when it is disconnected) similar question to here. 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
@mikolajwalus mikolajwalus added the question It is a question regarding the project label Jan 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question It is a question regarding the project
Projects
None yet
Development

No branches or pull requests

1 participant