-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #27 from JonasMH/develop
Add readme, examples and more discoverydocs.
- Loading branch information
Showing
63 changed files
with
1,520 additions
and
194 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
# HomeAssistantDiscoveryNet | ||
|
||
This project contains two libraries that are both published to Nuget | ||
|
||
1. `HomeAssistantDiscoveryNet` Library, contains all HA Discovery Documents | ||
2. `ToMqttNet` a managed way to keep a MQTT connection in ASP.NET | ||
|
||
## HomeAssistantDiscoveryNet Library | ||
|
||
Contains the following (Home Assistant MQTT Discovery Documents)[https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery] as C\# classes: | ||
|
||
- AlarmControlPanel | ||
- BinarySensor | ||
- Button | ||
- Camera | ||
- Climate | ||
- Cover | ||
- DefaultLight | ||
- DeviceTracker | ||
- DeviceTrigger | ||
- Event | ||
- Fan | ||
- Humidifier | ||
- Image | ||
- JsonLight | ||
- LawnMower | ||
- Lock | ||
- Number | ||
- Scene | ||
- Select | ||
- Sensor | ||
- Siren | ||
- Switch | ||
- TagScanner | ||
- TemplateLight | ||
- Text | ||
- Update | ||
- Vacuum | ||
- Valve | ||
- WaterHeater | ||
|
||
This makes it easy to create discovery documents from C\# without having to worry about mistyping property names etc. | ||
|
||
It also including de(serilization) using `System.Text.Json` source generators (AoT Compatible) | ||
|
||
### How to serialize discovery docs | ||
|
||
```csharp | ||
var cfg = new MqttBinarySensorDiscoveryConfig | ||
{ | ||
Name = $"Recommend Charging", | ||
ValueTemplate = "{{ 'ON' if value_json.recommend else 'OFF' }}", | ||
StateTopic = $"some-node/status/recommend-charging", | ||
UniqueId = $"some-node-recommend-charging", | ||
}; | ||
|
||
var json = cfg.ToJson(); | ||
``` | ||
|
||
Results in | ||
|
||
```json | ||
{ | ||
"component": "binary_sensor", | ||
"state_topic": "some-node/status/recommend-charging", | ||
"value_template": "{{ 'ON' if value_json.recommend else 'OFF' }}", | ||
"name": "Recommend Charging", | ||
"unique_id": "some-node-recommend-charging" | ||
} | ||
``` | ||
|
||
### How to deserialize discovery docs | ||
|
||
```csharp | ||
var parser = new MqttDiscoveryConfigParser(NullLoggerFactory.Instance, []); | ||
var topic = "some-node/binary/some_sensor"; | ||
var message = "{\"component\": \"binary_sensor\", \"state_topic\": \"some-node/status/recommend-charging\", \"value_template\": \"{{ 'ON' if value_json.recommend else 'OFF' }}\", \"name\": \"Recommend Charging\", \"unique_id\": \"some-node-recommend-charging\"}"; | ||
|
||
var result = parser.Parse(topic, message); | ||
|
||
Assert.IsType<MqttBinarySensorDiscoveryConfig>(result); | ||
``` | ||
|
||
## ToMqttNet Library | ||
|
||
This sets up a managed connection to a MQTT broker with | ||
|
||
- Makes use of [MQTTnet](https://github.com/dotnet/MQTTnet) for the connection | ||
- Dependency injection | ||
- `System.Diagnostics.Metrics` Based metrics | ||
- AoT compatible | ||
- Home Assistant Discovery integration | ||
|
||
### How to set up the ToMqttNet Library | ||
|
||
In `Program.cs`/`Startup.cs` | ||
|
||
```csharp | ||
var builder = WebApplication.CreateSlimBuilder(args); | ||
|
||
builder.Services.AddMqttConnection() | ||
.Configure<IOptions<MqttOptions>>((options, mqttConfI) => | ||
{ | ||
var mqttConf = mqttConfI.Value; | ||
options.NodeId = "myintegration"; | ||
options.ClientOptions.ChannelOptions = new MqttClientTcpOptions | ||
{ | ||
Server = mqttConf.Server, | ||
Port = mqttConf.Port, | ||
}; | ||
}); | ||
|
||
// ... | ||
``` | ||
|
||
### How to use the ToMqttNet Library | ||
|
||
```csharp | ||
// Remember to register this service in ASP.NET (Or call the .Execute) | ||
public class CounterMqttBackgroundService(MqttConnectionService mqtt) : BackgroundService | ||
{ | ||
private readonly MqttConnectionService _mqtt = mqtt; | ||
|
||
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | ||
{ | ||
var discoveryDoc = new MqttSensorDiscoveryConfig() | ||
{ | ||
UniqueId = "myintegration_mycounter", | ||
Name = "My Counter", | ||
ValueTemplate = "{{ value_json.value }}", | ||
StateTopic = _mqtt.MqttOptions.NodeId + "/status/counter", // myintegration/status/counter | ||
}; | ||
|
||
await _mqtt.PublishDiscoveryDocument(discoveryDoc); | ||
|
||
var counter = 0L; | ||
while (!stoppingToken.IsCancellationRequested) | ||
{ | ||
await _mqtt.PublishAsync(new MqttApplicationMessageBuilder() | ||
.WithTopic(_mqtt.MqttOptions.NodeId + "/status/counter") | ||
.WithPayload(JsonSerializer.Serialize(new {value = counter})) | ||
.Build()); | ||
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); | ||
counter++; | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Examples / usages of HomeAssistantDiscoveryNet and ToMqttNet | ||
|
||
- [JonasMH/Dantherm2Mqtt](https://github.com/JonasMH/Dantherm2Mqtt) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...s/MqttAlarmControlPanelDiscoveryConfig.cs → ...s/MqttAlarmControlPanelDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...eTypes/MqttBinarySensorDiscoveryConfig.cs → ...tities/MqttBinarySensorDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 5 additions & 5 deletions
10
.../DeviceTypes/MqttButtonDiscoveryConfig.cs → ...Net/Entities/MqttButtonDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
.../DeviceTypes/MqttCameraDiscoveryConfig.cs → ...Net/Entities/MqttCameraDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...DeviceTypes/MqttClimateDiscoveryConfig.cs → ...et/Entities/MqttClimateDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...t/DeviceTypes/MqttCoverDiscoveryConfig.cs → ...yNet/Entities/MqttCoverDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...eTypes/MqttDefaultLightDiscoveryConfig.cs → ...tities/MqttDefaultLightDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...Types/MqttDeviceTrackerDiscoveryConfig.cs → ...ities/MqttDeviceTrackerDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...Types/MqttDeviceTriggerDiscoveryConfig.cs → ...ities/MqttDeviceTriggerDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...t/DeviceTypes/MqttEventDiscoveryConfig.cs → ...yNet/Entities/MqttEventDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...Net/DeviceTypes/MqttFanDiscoveryConfig.cs → ...eryNet/Entities/MqttFanDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...iceTypes/MqttHumidifierDiscoveryConfig.cs → ...Entities/MqttHumidifierDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
src/HomeAssistantDiscoveryNet/Entities/MqttImageDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
using System.Text.Json.Serialization; | ||
|
||
namespace HomeAssistantDiscoveryNet; | ||
|
||
/// <summary> | ||
/// The mqtt image platform allows you to integrate the content of an image file sent through MQTT into Home Assistant as an image. The image platform is a simplified version of the camera platform that only accepts images. Every time a message under the image_topic in the configuration is received, the image displayed in Home Assistant will also be updated. Messages received on image_topic should contain the full contents of an image file, for example, a JPEG image, without any additional encoding or metadata. | ||
/// </summary> | ||
public class MqttImageDiscoveryConfig : MqttDiscoveryConfig | ||
{ | ||
public override string Component => "image"; | ||
|
||
///<summary> | ||
/// The content type of and image data message received on image_topic. This option cannot be used with the url_topic because the content type is derived when downloading the image. | ||
/// , default: image/jpeg | ||
///</summary> | ||
[JsonPropertyName("content_type")] | ||
public string? ContentType { get; set; } | ||
|
||
///<summary> | ||
/// Flag which defines if the entity should be enabled when first added. | ||
/// , default: true | ||
///</summary> | ||
[JsonPropertyName("enabled_by_default")] | ||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] | ||
public bool? EnabledByDefault { get; set; } | ||
|
||
///<summary> | ||
/// The encoding of the payloads received. Set to "" to disable decoding of incoming payload. Use image_encoding to enable Base64 decoding on image_topic. | ||
/// , default: utf-8 | ||
///</summary> | ||
[JsonPropertyName("encoding")] | ||
public string? Encoding { get; set; } | ||
|
||
///<summary> | ||
/// The category of the entity. | ||
/// , default: None | ||
///</summary> | ||
[JsonPropertyName("entity_category")] | ||
public string? EntityCategory { get; set; } | ||
|
||
///<summary> | ||
/// The encoding of the image payloads received. Set to "b64" to enable base64 decoding of image payload. If not set, the image payload must be raw binary data. | ||
/// , default: None | ||
///</summary> | ||
[JsonPropertyName("image_encoding")] | ||
public string? ImageEncoding { get; set; } | ||
|
||
///<summary> | ||
/// The MQTT topic to subscribe to receive the image payload of the image to be downloaded. Ensure the content_type type option is set to the corresponding content type. This option cannot be used together with the url_topic option. But at least one of these option is required. | ||
///</summary> | ||
[JsonPropertyName("image_topic")] | ||
public string? ImageTopic { get; set; } | ||
|
||
///<summary> | ||
/// Defines a template to extract the JSON dictionary from messages received on the json_attributes_topic. | ||
///</summary> | ||
[JsonPropertyName("json_attributes_template")] | ||
public string? JsonAttributesTemplate { get; set; } | ||
|
||
///<summary> | ||
/// The MQTT topic subscribed to receive a JSON dictionary payload and then set as sensor attributes. Implies force_update of the current sensor state when a message is received on this topic. | ||
///</summary> | ||
[JsonPropertyName("json_attributes_topic")] | ||
public string? JsonAttributesTopic { get; set; } | ||
|
||
///<summary> | ||
/// Used instead of name for automatic generation of entity_id | ||
///</summary> | ||
[JsonPropertyName("object_id")] | ||
public string? ObjectId { get; set; } | ||
|
||
///<summary> | ||
/// Defines a template to extract the image URL from a message received at url_topic. | ||
///</summary> | ||
[JsonPropertyName("url_template")] | ||
public string? UrlTemplate { get; set; } | ||
|
||
///<summary> | ||
/// The MQTT topic to subscribe to receive an image URL. A url_template option can extract the URL from the message. The content_type will be derived from the image when downloaded. This option cannot be used together with the image_topic option, but at least one of these options is required. | ||
///</summary> | ||
[JsonPropertyName("url_topic")] | ||
public string? UrlTopic { get; set; } | ||
} | ||
|
||
|
2 changes: 1 addition & 1 deletion
2
...viceTypes/MqttJsonLightDiscoveryConfig.cs → .../Entities/MqttJsonLightDiscoveryConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.