0

I have configured a Google Cloud IoT project and successfully published the "Hello, World" message from google cloud IoT console Topics page. I am able to view the received message also.

Now, while trying to run the below code on Visual Studio C# using Hivemq M2Mqtt nuget package, the message is not getting published. I observed the following:

  1. Publisher.Connect is returning code value of 5
  2. Publisher.Publish is returning msgID value of 1
  3. publisher.MqttMsgPublished event is not fired

What mistake I am making ?

Thanks.

    public static int ConvertToSeconds(DateTime date)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan diff = date.ToUniversalTime() - origin;
        return Convert.ToInt32(diff.TotalSeconds);
    }

    private bool createClients()
    {
        try
        {
            publisher = new MqttClient("mqtt.googleapis.com", 8883, true,
                new System.Security.Cryptography.X509Certificates.X509Certificate(Properties.Resources.roots),
                null, MqttSslProtocols.TLSv1_2);
            publisher.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
            string Gu_id = "projects/testproject-279402/locations/asia-east1/registries/My_Registry/devices/My_Device";
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Properties.Resources.rsa_private);
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                (securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);
            var header = new System.IdentityModel.Tokens.Jwt.JwtHeader(credentials);

            var validfrom = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(30));
            var validTo = DateTime.UtcNow.Add(TimeSpan.FromMinutes(600));
            var payload = new System.IdentityModel.Tokens.Jwt.JwtPayload {
                {"aud", "googleapis.com/projects/testproject-279402/topics/Temperature"},
                {"iat", ConvertToSeconds(validfrom)},
                {"exp", ConvertToSeconds(validTo) }
            };
            var secToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(header, payload);
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);
            byte code = publisher.Connect(Gu_id, null, tokenString,
                                       false, // will retain flag
                                        MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, // will QoS
                                       true, // will flag
                                       "/will_topic", // will topic
                                       "will_message", // will message
                                       true,
                                       60);
            publisher.MqttMsgPublished += publisher_MqttMsgPublished;

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return false;
        }
        return true;
    }

    private bool publish(ref string ers)
    {
        try
        {
            ushort msgId = publisher.Publish("/projects/testproject-279402/topics/Temperature",
                              Encoding.UTF8.GetBytes("123"),
                              MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE,
                              false); // retained
        }
        catch (Exception ex)
        {
            ers = "Exception occurred in publish.";
            return false;
        }
        ers = "";
        return true;
    }
Abhijit
  • 1
  • 1

1 Answers1

0

The "aud" key in the JWT should just be the project ID, not the full Pub/Sub topic. I don't know if it's smart enough to read just what it needs, but try that first.

Also, if I'm reading this right, it looks like you're trying to publish directly to the Pub/Sub topic? You should be publishing to the MQTT topic (/devices/[device_id]/events) not the Pub/Sub topic if you're using IoT Core. If you're trying to MQTT publish straight to Pub/Sub, that's somethign else...but it sounds like you're still wanting to use IoT Core?

Gabe Weiss
  • 3,134
  • 1
  • 12
  • 15
  • Caveat, I'm not familiar with the Hivemq package, and haven't done what you're doing exactly, but IoT Core likely doesn't understand what/where you're publishing given what I see in the code there. – Gabe Weiss Jun 09 '20 at 06:42