Skip to content

Instantly share code, notes, and snippets.

@shroukkhan
Forked from adrenalinehit/mqtt-publisher.cs
Created August 3, 2017 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shroukkhan/78b39d6b230a01a00808a3182f67489e to your computer and use it in GitHub Desktop.
Save shroukkhan/78b39d6b230a01a00808a3182f67489e to your computer and use it in GitHub Desktop.
MQTT Publisher sample console application to demonstrate connecting to AWS IoT
using System;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using uPLibrary.Networking.M2Mqtt;
namespace MQTT.Sample
{
public class Program
{
/// <summary>
/// AWS IoT endpoint - replace with your own
/// </summary>
private const string IotEndpoint = "*******.iot.eu-west-1.amazonaws.com";
/// <summary>
/// TLS1.2 port used by AWS IoT
/// </summary>
private const int BrokerPort = 8883;
/// <summary>
/// this must match - partially - what the subscribed is subscribed too
/// nicksthings = the THING i created in AWS IoT
/// t1/t555 is just an arbitary topic that i'm publishing to. (It needs 2 parts for the rule I'm using to work)
/// </summary>
private const string Topic = "YOURTHING/t1/t555";
public static void Main(string[] args)
{
var publisher = new Program();
publisher.Publish();
}
/// <summary>
/// Configure client and publish a message
/// </summary>
public void Publish()
{
//convert to pfx using openssl - see confluence
//you'll need to add these two files to the project and copy them to the output (not included in source control deliberately!)
var clientCert = new X509Certificate2("YOURPFXFILE.pfx", "YOURPFXFILEPASSWORD");
var caCert = X509Certificate.CreateFromSignedFile("root.pem");
// create the client
var client = new MqttClient(IotEndpoint, BrokerPort, true, caCert, clientCert, MqttSslProtocols.TLSv1_2);
//message to publish - could be anything
var message = "Insert your message here";
//client naming has to be unique if there was more than one publisher
client.Connect("clientid1");
//publish to the topic
client.Publish(Topic, Encoding.UTF8.GetBytes(message));
//this was in for debug purposes but it's useful to see something in the console
if (client.IsConnected)
{
Console.WriteLine("SUCCESS!");
}
//wait so that we can see the outcome
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment