Cannot send data If I disconnect afterwards

I am trying to write a service to forward data to cumulocity.

When a sensor reads data, it sends it to our server. Then the server forwards that data to my service. I parse it and use Smart REST templates to send it to cumulocity.

I looked at the guides and copied the code there for some test. For example a device creation message looks like this.


public async Task ClientTest([FromBody] JObject sensorjson)
    {
        var cDetails = new ConnectionDetailsBuilder()
           .WithClientId("clientId")
           .WithHost("mqtt.cumulocity.com")
           .WithCredentials("Credentials")
           .WithCleanSession(true)
           .(WithProtocol(TransportType.Tcp).Build();

        MqttClient client = new MqttClient(cDetails);

        await client.EstablishConnectionAsync();

        string topic = "s/us";
        string payload = $"100,TestDevice,Test";
        var message = new MqttMessageRequestBuilder()
            .WithTopicName(topic)
            .WithQoS(QoS.AT_LEAST_ONCE)
            .WithMessageContent(payload)
            .Build();

        await client.PublishAsync(message);

        await client.Disconnect();
}

When the code is like this, no device is created in my cumulocity tenant.

When I comment out “await client.Disconnect();” it creates the device.

What is the reason behind this?

In my real code if I don’t disconnect at some point memory usage cannot be maintained. If I disconnect my messages doesn’t go to the broker.

What should I do?

Hi,

why don’t you sent the data directly to Cumulocity?

Cheers
Michael

Hello,

Thanks for your reply and apologies for late reply.
The thing is devices are custom made and their output need some tweaking before they are sent to Cumulocity. I have no way of changing the output on device level. They are working fine on our platform but I need to pass the data to Cumulocity.

I worked some more on the problem and now I am not using Disconnect. Instead I create a client for each device and keep them alive while the program runs. When new data comes I find the corresponding client and send data with it.

But with this new questions arise.

Is “ConnectionFailed” event of Cumulocity.SDK.MQTT called only when the client tries to connect and fail or also when an existing connection drops.For example if I write


private void Client_ConnectionFailed(object sender, ProcessFailedEventArgs e)
        {
            MqttClient client = sender as MqttClient;

            client.EstablishConnectionAsync();
         }

Would this guarantee that my client is always connected?

Hi Omer,

I have to apologize that I never came back to you until now. I totally lost track of this issue. At the moment I involved our R&D team to double check if the code you put here will work. I hope I can give you an update soon.

best regards
Michael