I have a .Net/UWP application that I need to modify to send status via MQTT on AWS. I see plenty of examples in how to publish/subscribe using other languages, but for .Net the information that I've found seems to be outdated and no longer applicable.
In the .Net AWSSDK is there anything that is the equivalent of the AWSIotClient
class (from Java)? Is there some way to communicate with AWS from .Net?
CodePudding user response:
Had this same problem and never did find an official AWS published C# SDK for Iot Core, though you can communicate with AWS Iot Core using MQTTnet.
Here is a snippet on how to connect:
var pfxCert = new X509Certificate2(X509Certificate2.CreateFromPemFile(pemCert,pemPrivKey).Export(X509ContentType.Pfx));
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithTcpServer(endpoint, 8883)
.WithClientId(clientId)
.WithCleanSession()
.WithCommunicationTimeout(TimeSpan.FromSeconds(60))
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
IgnoreCertificateRevocationErrors = true,
IgnoreCertificateChainErrors = true,
AllowUntrustedCertificates = true,
Certificates = new List<X509Certificate>
{
pfxCert
}
})
.Build();
await mqttClient.ConnectAsync(options, CancellationToken.None);
To send a message:
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(jsonMessage)
.Build();
var result = await _mqttClient.PublishAsync(message, CancellationToken.None);