Skip to content

Commit

Permalink
Add example and link to documentation.
Browse files Browse the repository at this point in the history
  • Loading branch information
pglombardo authored Dec 27, 2023
1 parent 3504b2e commit 1941353
Showing 1 changed file with 26 additions and 112 deletions.
138 changes: 26 additions & 112 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ We'd appreciate any feedback you have. Happy MQTT adventures!

* **Easy-to-Install**: Available as a Nuget package.
* **Opensource**: No blackbox code. Only trusted, tested and reviewed opensource code.
* **Works with Any MQTT 5.0 Broker**: Built by HiveMQ _but not only for_ HiveMQ.
* **Easy to Use**: Smart defaults, excellent interfaces and intelligent automation makes implementing a breeze.
* **MQTT v5.0 compatible**: Backported versions 3.1.1 & 3.0 coming soon!
* **Extensive Event System**: Hook into all parts of the client down to the packet level with [built in events](https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/Events.md).
* **Globally Compatible**: Built to be a fully compliant client compatible with all reputable MQTT brokers.
* **Extensive Event System**: Hook into all parts of the client down to the packet level with [built in events](https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/events).
* **Globally Compatible**: Built to be a fully compliant MQTT 5.0 client compatible with all reputable MQTT brokers.
* **Actively Maintained**: Built by the MQTT professionals that built HiveMQ (and do this for a living).
* **Extensively Documented**: What good is it without excellent documentation?
* **Supported**: Contact us anytime in [this repository](https://github.com/hivemq/hivemq-mqtt-client-dotnet/issues), in the [community forum](https://community.hivemq.com) or [through support](https://www.hivemq.com/support/).
Expand Down Expand Up @@ -64,129 +64,43 @@ dotnet add package HiveMQtt

See the [HiveMQtt NuGet page](https://www.nuget.org/packages/HiveMQtt/) for more installation options.

## Quickstart
## Example

### Simple Connect
The following illustrates the client pattern to connect, subscribe and publish messages.

```c#
```csharp
using HiveMQtt.Client;

// Connect
var client = new HiveMQClient();
var connectResult = await client.ConnectAsync().ConfigureAwait(false);
```

#### With Options

```c#
var options = new HiveMQClientOptions();
options.Host = 'candy.x39.eu.hivemq.cloud';
options.Port = 8883;

using HiveMQtt.MQTT5.Types;

// Setup Client options and instantiate
var options = new HiveMQClientOptionsBuilder().
WithBroker('candy.x39.eu.hivemq.cloud').
WithPort(8883).
WithUseTLS(true).
Build();
var client = new HiveMQClient(options);
var connectResult = await client.ConnectAsync().ConfigureAwait(false);
```

### Basic Subscribe & Publish

```c#
using HiveMQtt.Client;

// Connect
var client = new HiveMQClient();
var connectResult = await client.ConnectAsync().ConfigureAwait(false);

// Message Handler
// Setup an application message handlers BEFORE subscribing to a topic
client.OnMessageReceived += (sender, args) =>
{
Console.WriteLine("Message Received: {}", args.PublishMessage.PayloadAsString)
};

// Subscribe
await client.SubscribeAsync("instrument/x9284/boston").ConfigureAwait(false);

await client.PublishAsync(
"core/dynamic_graph/entity/227489", // Topic to publish to
"{'2023': '👍'}" // Message to publish
).ConfigureAwait(false);
```

### Last Will and Testament

The Last Will and Testament support of MQTT can be used to notify subscribers that your client is offline.

For a more in-depth explanation, see [What is MQTT Last Will and Testament (LWT)? – MQTT Essentials: Part 9](https://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament/).

```C#
// Specify the Last Will and Testament specifics in HiveMQClientOptions
var options = new HiveMQClientOptions
{
LastWillAndTestament = new LastWillAndTestament("last/will", QualityOfService.AtLeastOnceDelivery, "last will message"),
};

// Optionally set extended properties on the Last Will and Testament message
options.LastWillAndTestament.WillDelayInterval = 1;
options.LastWillAndTestament.PayloadFormatIndicator = 1;
options.LastWillAndTestament.MessageExpiryInterval = 100;
options.LastWillAndTestament.ContentType = "application/text";
options.LastWillAndTestament.ResponseTopic = "response/topic";
options.LastWillAndTestament.CorrelationData = new byte[] { 1, 2, 3, 4, 5 };
options.LastWillAndTestament.UserProperties.Add("userPropertyKey", "userPropertyValue");

// ConnectAsync will transmit the Last Will and Testament configuration.
var client = new HiveMQClient(options);
connectResult = await client.ConnectAsync().ConfigureAwait(false);

// The Last Will and Testament message will be sent to the "last/will" topic if your clients get
// unexpectedly disconnected or alternatively, if your client disconnects with `DisconnectWithWillMessage`
var disconnectOptions = new DisconnectOptions { ReasonCode = DisconnectReasonCode.DisconnectWithWillMessage };
var disconnectResult = await client.DisconnectAsync(disconnectOptions).ConfigureAwait(false);
``````

Because the client above disconnected with `DisconnectReasonCode.DisconnectWithWillMessage`, subscribers to the `last/will` topic will receive the Last Will and Testament message as specified above.

### More

For more examples that you can easily copy/paste, see our [Examples](https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/Examples.md).
There is even an https://github.com/hivemq/hivemq-mqtt-client-dotnet/tree/main/Examples/HiveMQtt-CLI to demonstrate usage of the package.
## Configuration

### Logging

The HiveMQtt package uses [NLog](https://github.com/NLog/NLog) and can be configured with a configuration file (`NLog.config`). Having this file in the same directory of your executable will configure the HiveMQtt logger to output as configured:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
<target name="logfile" xsi:type="File" fileName="HiveMQtt.log" />
<target name="logconsole" xsi:type="Console" />
</targets>
// Connect to the MQTT broker
var connectResult = await client.ConnectAsync().ConfigureAwait(false);

<rules>
<!-- minlevel can be Debug, Info, Warn, Error and Fatal or Trace -->
<logger name="HiveMQtt.*" minlevel="Error" writeTo="logconsole" />
</rules>
</nlog>
// Configure the subscriptions we want and subscribe
var builder = new SubscribeOptionsBuilder();
builder.WithSubscription("topic1", QualityOfService.AtLeastOnceDelivery)
.WithSubscription("topic2", QualityOfService.ExactlyOnceDelivery);
var subscribeOptions = builder.Build();
var subscribeResult = await client.SubscribeAsync(subscribeOptions);

// Publish a message
var publishResult = await client.PublishAsync("topic1/example", "Hello Payload")
```

Setting `minlevel` to `Trace` will output all activity in the HiveMQtt package down to packet and event handling. Using this level will produce a lot of output such as the following:

```log
2023-10-04 16:56:54.9373|TRACE|HiveMQtt.Client.HiveMQClient|BeforeConnectEventLauncher
2023-10-04 16:56:55.0081|TRACE|HiveMQtt.Client.HiveMQClient|7: TrafficInflowProcessor Starting...Connecting
2023-10-04 16:56:55.0081|TRACE|HiveMQtt.Client.HiveMQClient|9: TrafficOutflowProcessor Starting...Connecting
2023-10-04 16:56:55.0081|TRACE|HiveMQtt.Client.HiveMQClient|--> ConnectPacket
2023-10-04 16:56:55.0128|TRACE|HiveMQtt.Client.HiveMQClient|OnConnectSentEventLauncher
2023-10-04 16:56:55.0374|TRACE|HiveMQtt.Client.HiveMQClient|<-- ConnAck
2023-10-04 16:56:55.0374|TRACE|HiveMQtt.Client.HiveMQClient|OnConnAckReceivedEventLauncher
2023-10-04 16:56:55.0379|TRACE|HiveMQtt.Client.HiveMQClient|AfterConnectEventLauncher
```
For a Quickstart, more examples and walkthroughs, see [the documentation](https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/quickstart).
## Other MQTT Clients

Expand Down

0 comments on commit 1941353

Please sign in to comment.