Skip to content

Instantly share code, notes, and snippets.

@adrenalinehit
Last active February 10, 2020 07:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adrenalinehit/ccfeba90264a02fb629f to your computer and use it in GitHub Desktop.
Save adrenalinehit/ccfeba90264a02fb629f to your computer and use it in GitHub Desktop.
MQTT subscriber example connecting to AWS IoT
using System.Security.Cryptography.X509Certificates;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace MQTT.SubscriberTest
{
public class Program
{
/// <summary>
/// Replace this with your endpoint - it's shown in the AWS IoT console next to the REST endpoint - they're the same.
/// </summary>
private const string IotEndpoint = "**********.iot.eu-west-1.amazonaws.com";
/// <summary>
/// This is the default TLS1.2 port that AWS IoT uses
/// </summary>
private const int BrokerPort = 8883;
/// <summary>
/// Just build it and run it up from the bin folder before you publish a message using the publisher
/// </summary>
/// <param name="args">expects Nowt</param>
public static void Main(string[] args)
{
var subscriber = new Program();
subscriber.Subscribe();
}
/// <summary>
/// Set up the client and listen for inbound messages
/// </summary>
public void Subscribe()
{
//convert to pfx using openssl
//you'll need to add these two files to the project and copy them to the output
var clientCert = new X509Certificate2("YOURPFXFILE.pfx", "YOURPFXFILEPASSWORD");
//this is the AWS caroot.pem file that you get as part of the download
var caCert = X509Certificate.CreateFromSignedFile("root.pem"); // this doesn't have to be a new X509 type...
var client = new MqttClient(IotEndpoint, BrokerPort, true, caCert, clientCert, MqttSslProtocols.TLSv1_2 /*this is what AWS IoT uses*/);
//event handler for inbound messages
client.MqttMsgPublishReceived += ClientMqttMsgPublishReceived;
//client id here is totally arbitary, but I'm pretty sure you can't have more than one client named the same.
client.Connect("listener");
// '#' is the wildcard to subscribe to anything under the 'root' topic
// the QOS level here - I only partially understand why it has to be this level - it didn't seem to work at anything else.
client.Subscribe(new[] { "YOURTHING/#" }, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
while (true)
{
//listen good!
}
}
public static void ClientMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Console.WriteLine("We received a message...");
Console.WriteLine(Encoding.UTF8.GetChars(e.Message));
}
}
}
@hopewise
Copy link

I have tried to follow instructions, I get error at line 39 above:

An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll

Additional information: The system cannot find the file specified.

In my case, its "{id}-certificate.pem" that I've downloaded for the certificate after attaching the thing and policy to it..
Although the "{id}-certificate.pem" file is in the same folder of the exe file, I get the error above

Can you please help?

@SolidStateLEDLighting
Copy link

SolidStateLEDLighting commented Jun 3, 2017

I just got this code working with AWS IOT. 2 Things that gave me problems.

  1. Had to use a Linux machine to convert the Cert and PrivKey to a pfx file with openssl.
  2. The wildcard subscription topic of "YOURTHING/#" didn't work. "#" alone did work. "topicname" also works. (I did substitute my thing name in for YOURTHING - No go)

Note: Changed line 39 to:
caCert = new X509Certificate("YourCertFilePath/Filename"); (not sure if this was part of my original problem or not)

Suggestion. Test your certs and keys with Mqttfx tool first to confirm your IOT Thing is set up correctly.
Also - My project was a standard Windows app - not a command line project.

@gevorgter
Copy link

Just for those who still looking for answer. You MUST make a policy that allows your client to connect
The easiest one is:
{
"Effect": "Allow",
"Action": [
"iot:Publish",
"iot:Subscribe",
"iot:Receive",
"iot:Connect"
],
"Resource": "*"
}
]

@TejaswiniiB
Copy link

Hi @adrenalinehit , wild cards are not working for me with this library as you told . If I subscribe and publish to topic of same string ,it's working. But if I subscribe to YOURTHING/# , and if I publish to YOURTHING/top , I am not receiving any msg. I tested the same with aws python script, where it was working - so the certs generated are not a problem.

Thanks !

@prize-max
Copy link

I get errors at line 47.

client.Connect("listener");

Message: Exception connecting to the broker.
InnerException: The remote certificate is invalid according to the validation procedure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment