Skip to content

Commit

Permalink
Merge pull request #2 from JonasMH/develop
Browse files Browse the repository at this point in the history
Include null properties + button
  • Loading branch information
JonasMH authored Feb 6, 2022
2 parents 4ed6be9 + 6e465fa commit 8380b27
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 13 deletions.
24 changes: 24 additions & 0 deletions src/ToMqttNet/DeviceTypes/MqttBinarySensorDiscoveryConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,38 @@

namespace ToMqttNet
{
/// <summary>
/// The mqtt binary sensor platform uses an MQTT message received to set the binary sensor’s state to on or off.
/// </summary>
public class MqttBinarySensorDiscoveryConfig : MqttDiscoveryConfig<MqttSelectDiscoveryConfig>
{
public override string Component => "binary_sensor";

[JsonProperty("state_topic")]
public string? StateTopic { get; set; }

/// <summary>
/// Defines a template that returns a string to be compared to <c>payload_on</c>/<c>payload_off</c> or an empty string, in which case the MQTT message will be removed. Available variables: entity_id. Remove this option when ‘payload_on’ and ‘payload_off’ are sufficient to match your payloads (i.e no pre-processing of original message is required).
/// </summary>
[JsonProperty("value_template")]
public string? ValueTemplate { get; set; }

/// <summary>
/// The string that represents the off state. It will be compared to the message in the state_topic (see value_template for details)
/// </summary>
[JsonProperty("payload_off")]
public string? PayloadOff { get; set; }

/// <summary>
/// The string that represents the on state. It will be compared to the message in the state_topic (see value_template for details)
/// </summary>
[JsonProperty("payload_on")]
public string? PayloadOn { get; set; }

/// <summary>
/// Sets the <see href="https://www.home-assistant.io/integrations/binary_sensor/#device-class">class of the device</see>, changing the device state and icon that is displayed on the frontend.
/// </summary>
[JsonProperty("device_class")]
public string? DeviceClass { get; set; }
}
}
31 changes: 31 additions & 0 deletions src/ToMqttNet/DeviceTypes/MqttButtonDiscoveryConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Newtonsoft.Json;

namespace ToMqttNet
{
/// <summary>
/// The mqtt button platform lets you send an MQTT message when the button is pressed in the frontend or the button press service is called. This can be used to expose some service of a remote device, for example reboot.
/// </summary>
public class MqttButtonDiscoveryConfig : MqttDiscoveryConfig<MqttButtonDiscoveryConfig>
{
public override string Component => "button";

/// <summary>
/// The MQTT topic to publish commands to trigger the button.
/// </summary>
[JsonProperty("command_topic")]
public string? CommandTopic { get; set; }

/// <summary>
/// Defines a template to generate the payload to send to command_topic.
/// </summary>
[JsonProperty("command_template")]
public string? CommandTemplate { get; set; }

/// <summary>
/// The payload To send to trigger the button.
/// </summary>
[JsonProperty("payload_press")]
public string? PayloadPress { get; set; }

}
}
3 changes: 3 additions & 0 deletions src/ToMqttNet/DeviceTypes/MqttSelectDiscoveryConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace ToMqttNet
{
/// <summary>
/// The mqtt Select platform allows you to integrate devices that might expose configuration options through MQTT into Home Assistant as a Select. Every time a message under the topic in the configuration is received, the select entity will be updated in Home Assistant and vice-versa, keeping the device and Home Assistant in sync.
/// </summary>
public class MqttSelectDiscoveryConfig : MqttDiscoveryConfig<MqttSelectDiscoveryConfig>
{
public override string Component => "select";
Expand Down
3 changes: 3 additions & 0 deletions src/ToMqttNet/DeviceTypes/MqttSensorDiscoveryConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

namespace ToMqttNet
{
/// <summary>
/// This mqtt sensor platform uses the MQTT message payload as the sensor value. If messages in this state_topic are published with RETAIN flag, the sensor will receive an instant update with last known value. Otherwise, the initial state will be undefined.
/// </summary>
public class MqttSensorDiscoveryConfig : MqttDiscoveryConfig<MqttSensorDiscoveryConfig>
{
public override string Component => "sensor";
Expand Down
27 changes: 26 additions & 1 deletion src/ToMqttNet/DeviceTypes/MqttSwitchDiscoveryConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,54 @@

namespace ToMqttNet
{
/// <summary>
/// The mqtt switch platform lets you control your MQTT enabled switches.
/// </summary>
public class MqttSwitchDiscoveryConfig : MqttDiscoveryConfig<MqttSwitchDiscoveryConfig>
{
public override string Component => "switch";

/// <summary>
/// The MQTT topic to publish commands to change the switch state.
/// </summary>
[JsonProperty("command_topic")]
public string? CommandTopic { get; set; }

/// <summary>
/// The payload that represents on state. If specified, will be used for both comparing to the value in the state_topic (see value_template and state_on for details) and sending as on command to the command_topic.
/// </summary>
[JsonProperty("payload_on")]
public object? PayloadOn { get; set; }

/// <summary>
/// The payload that represents off state. If specified, will be used for both comparing to the value in the state_topic (see value_template and state_off for details) and sending as off command to the command_topic.
/// </summary>
[JsonProperty("payload_off")]
public object? PayloadOff { get; set; }


/// <summary>
/// The MQTT topic subscribed to receive state updates.
/// </summary>
[JsonProperty("state_topic")]
public string? StateTopic { get; set; }

/// <summary>
/// The payload that represents the on state. Used when value that represents on state in the state_topic is different from value that should be sent to the command_topic to turn the device on.
/// Default: payload_on if defined, else ON
/// </summary>
[JsonProperty("state_on")]
public object? StateOn { get; set; }

/// <summary>
/// The payload that represents the off state. Used when value that represents off state in the state_topic is different from value that should be sent to the command_topic to turn the device off.
/// Default: payload_off if defined, else OFF
/// </summary>
[JsonProperty("state_off")]
public object? StateOff { get; set; }

/// <summary>
/// Defines a template to extract device’s state from the state_topic. To determine the switches’s state result of this template will be compared to state_on and state_off.
/// </summary>
[JsonProperty("value_template")]
public string? ValueTemplate { get; set; }
}
Expand Down
19 changes: 11 additions & 8 deletions src/ToMqttNet/MqttConnectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;

Expand All @@ -10,6 +11,7 @@ namespace ToMqttNet
public class MqttConnectionService : BackgroundService, IMqttConnectionService
{
private readonly ILogger<MqttConnectionService> _logger;

public MqttConnectionOptions MqttOptions { get; }
private IManagedMqttClient? _mqttClient;

Expand All @@ -34,6 +36,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
new MqttApplicationMessageBuilder()
.WithPayload("0")
.WithTopic($"{MqttOptions.NodeId}/connected")
.WithRetainFlag()
.Build()
)
.Build()
Expand All @@ -43,9 +46,16 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
_mqttClient = new MqttFactory()
.CreateManagedMqttClient();

_mqttClient.UseConnectedHandler((evnt) =>
_mqttClient.UseConnectedHandler(async (evnt) =>
{
_logger.LogInformation("Connected to mqtt: {reason}", evnt.ConnectResult.ReasonString);

await _mqttClient.PublishAsync(
new MqttApplicationMessageBuilder()
.WithPayload("2")
.WithTopic($"{MqttOptions.NodeId}/connected")
.WithRetainFlag()
.Build());
});

_mqttClient.UseDisconnectedHandler((evnt) =>
Expand All @@ -60,15 +70,8 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
});

await _mqttClient.StartAsync(options);
await SubscribeAsync(new MqttTopicFilterBuilder().WithTopic($"{MqttOptions.NodeId}/#").Build());
await _mqttClient.PublishAsync(
new MqttApplicationMessageBuilder()
.WithPayload("2")
.WithTopic($"{MqttOptions.NodeId}/connected")
.Build());
}


public Task PublishAsync(params MqttApplicationMessage[] applicationMessages)
{
return _mqttClient!.PublishAsync(applicationMessages);
Expand Down
1 change: 0 additions & 1 deletion src/ToMqttNet/MqttConnectionServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ public static class MqttDiscoveryConfigExtensions
{
NamingStrategy = new CamelCaseNamingStrategy(),
},
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.None
};
public static string ToJson<T>(this T config) where T : MqttDiscoveryConfig<T>
Expand Down
2 changes: 1 addition & 1 deletion src/ToMqttNet/ToMqttNet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<Version>0.1.1</Version>
<Version>0.1.2</Version>
<Authors>JonasMH</Authors>
<PackageDescription>ASP.NET Hosted MQTT Connection and models to make it easier to work with Home Assistant MQTT Discovery</PackageDescription>
<RepositoryUrl>https://github.com/JonasMH/ToMqttNet</RepositoryUrl>
Expand Down
21 changes: 19 additions & 2 deletions test/ToMqttNet.Test.Unit/MqttDiscoveryConfigTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,27 @@ public void ToJson_CorrectTopic()
};

// Act
var result = sut.ToJson();
var result = (JObject)JsonConvert.DeserializeObject(sut.ToJson())!;

// Assert
Assert.Equal("stub", result["component"]!.ToString());
}

[Fact]
public void ToJson_ShouldIncludeNull()
{
// Arrange
var sut = new MqttStubDiscoveryConfig()
{

};

// Act
var result = (JObject)JsonConvert.DeserializeObject(sut.ToJson())!;

// Assert
Assert.Equal("{\"component\":\"stub\"}", result);
Assert.IsType<JValue>(result["device"]);
Assert.Null(((JValue)result["device"]).Value);
}

[Fact]
Expand Down

0 comments on commit 8380b27

Please sign in to comment.