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:
- Publisher.Connect is returning code value of 5
- Publisher.Publish is returning msgID value of 1
- 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;
}