-
-
Notifications
You must be signed in to change notification settings - Fork 80
Mqtt extension to create an update entities in HA #658
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
a651058
Initial commit of MQTT entity management framework. (#656)
skotl 228e3fd
Added Update and Remove methods and resolved some of the comments for…
eugeneniemand 30f3184
Changing names to be less generic
eugeneniemand 4fc6954
Moved to src/extensions, renamed folder and fixed warning
eugeneniemand d6e15d0
Added example app and fixed IOptions for mqtt config
eugeneniemand 577d93c
Fix CI Build error
eugeneniemand a1fd37f
Add support for nuget and default host (#660)
helto4real c95a4bb
Added Discovery prefix
eugeneniemand 211efdd
Merge branch 'mqtt_extensions' of github.com:net-daemon/netdaemon int…
eugeneniemand 15a917d
MQTT connect and publish can throw exceptions as well as return error…
skotl 72b109b
1. Add XML comments
skotl 455efc7
Resolving PR comments
eugeneniemand 7889701
Merged Skotl's code and fixed hard coded retain flag
eugeneniemand 753a43b
Removing throw and fixed warning. Added comment for Delay
eugeneniemand f5da8c1
address PR comments
skotl 812ac17
Internalising...
skotl 5265d62
Merge branch 'dev' into mqtt_extensions
helto4real File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,10 @@ | ||
| { | ||
| "profiles": { | ||
| "DebugHost": { | ||
| "commandName": "Project", | ||
| "environmentVariables": { | ||
| "DOTNET_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or 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,63 @@ | ||
| #region | ||
|
|
||
| using System; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Logging; | ||
| using NetDaemon.AppModel; | ||
| using NetDaemon.Extensions.MqttEntityManager; | ||
| using NetDaemon.HassModel; | ||
|
|
||
| #endregion | ||
|
|
||
| namespace DebugHost.apps.Extensions; | ||
|
|
||
| [NetDaemonApp] | ||
| [Focus] | ||
| public class MqttEntityManagerApp : IAsyncInitializable | ||
| { | ||
| private readonly IHaContext _ha; | ||
| private readonly ILogger<MqttEntityManagerApp> _logger; | ||
| private readonly IMqttEntityManager _manager; | ||
|
|
||
| public MqttEntityManagerApp(IHaContext ha, ILogger<MqttEntityManagerApp> logger, IMqttEntityManager manager) | ||
| { | ||
| _ha = ha; | ||
| _logger = logger; | ||
| _manager = manager; | ||
| } | ||
|
|
||
| [SuppressMessage("Naming", "CA1727:Use PascalCase for named placeholders", Justification = "<Pending>")] | ||
| [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "We need to log unexpected errors")] | ||
| public async Task InitializeAsync(CancellationToken cancellationToken) | ||
| { | ||
| try | ||
| { | ||
| _logger.LogInformation("Creating Entity {domain}.{entityId}", "binary_sensor", "manager_test"); | ||
| await _manager.CreateAsync("binary_sensor", "manager_test", "motion", "Manager Test").ConfigureAwait(false); | ||
| // Using Delay to give Mqtt and HA enough time to process events. | ||
| // Only needed for the example as we immediately read the entity and it may not yet exist | ||
| await Task.Delay(250, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| var entity = _ha.Entity("binary_sensor.manager_test"); | ||
| _logger.LogInformation("Entity {domain}.{entityId} State: {state}", "binary_sensor", "manager_test", entity.State); | ||
|
|
||
| await _manager.UpdateAsync("binary_sensor", "manager_test", "ON", JsonSerializer.Serialize(new { attribute1 = "attr1" })) | ||
| .ConfigureAwait(false); | ||
| await Task.Delay(250, cancellationToken).ConfigureAwait(false); | ||
| _logger.LogInformation("Entity {domain}.{entityId} State: {state} Attributes: {attributes}", | ||
| "binary_sensor", "manager_test", entity.State, entity.Attributes); | ||
|
|
||
| await _manager.RemoveAsync("binary_sensor", "manager_test").ConfigureAwait(false); | ||
| await Task.Delay(250, cancellationToken).ConfigureAwait(false); | ||
| var removed = _ha.Entity("binary_sensor.manager_test").State == null; | ||
| _logger.LogInformation("Removed Entity: {removed}", removed); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| _logger.LogError(e, e.Message); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -16,5 +16,8 @@ | |
| "NetDaemon": { | ||
| "Admin": true, | ||
| "ApplicationConfigurationFolder": "./apps" | ||
| }, | ||
| "Mqtt": { | ||
| "Host": "localhost" | ||
| } | ||
| } | ||
31 changes: 31 additions & 0 deletions
31
src/Extensions/NetDaemon.Extensions.MqttEntityManager/DependencyInjectionSetup.cs
This file contains hidden or 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,31 @@ | ||
| #region | ||
|
|
||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
| using MQTTnet; | ||
|
|
||
| #endregion | ||
|
|
||
| namespace NetDaemon.Extensions.MqttEntityManager; | ||
|
|
||
| /// <summary> | ||
| /// DI setup for Mqtt Entity Manager | ||
| /// </summary> | ||
| public static class DependencyInjectionSetup | ||
| { | ||
| /// <summary> | ||
| /// Add support for managing entities via MQTT | ||
| /// </summary> | ||
| /// <param name="hostBuilder"></param> | ||
| /// <returns></returns> | ||
| public static IHostBuilder UseNetDaemonMqttEntityManagement(this IHostBuilder hostBuilder) | ||
| { | ||
| return hostBuilder.ConfigureServices((context, services) => | ||
| { | ||
| services.AddSingleton<IMqttFactory, MqttFactory>(); | ||
| services.AddSingleton<IMqttEntityManager, MqttEntityManager>(); | ||
| services.AddTransient<IMessageSender, MessageSender>(); | ||
| services.Configure<MqttConfiguration>(context.Configuration.GetSection("Mqtt")); | ||
| }); | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
src/Extensions/NetDaemon.Extensions.MqttEntityManager/Exceptions/MqttConnectionException.cs
This file contains hidden or 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,22 @@ | ||
| namespace NetDaemon.Extensions.MqttEntityManager.Exceptions; | ||
|
|
||
| /// <summary> | ||
| /// MQTT connection failed | ||
| /// </summary> | ||
| public class MqttConnectionException : Exception | ||
| { | ||
| /// <summary> | ||
| /// MQTT connection failed | ||
| /// </summary> | ||
| /// <param name="msg"></param> | ||
| public MqttConnectionException(string msg) : base(msg) | ||
| {} | ||
|
|
||
| /// <summary> | ||
| /// MQTT connection failed | ||
| /// </summary> | ||
| /// <param name="msg"></param> | ||
| /// <param name="innerException"></param> | ||
| public MqttConnectionException(string msg, Exception innerException) : base(msg, innerException) | ||
| {} | ||
| } |
22 changes: 22 additions & 0 deletions
22
src/Extensions/NetDaemon.Extensions.MqttEntityManager/Exceptions/MqttPublishException.cs
This file contains hidden or 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,22 @@ | ||
| namespace NetDaemon.Extensions.MqttEntityManager.Exceptions; | ||
|
|
||
| /// <summary> | ||
| /// Failed to publish a message to MQTT | ||
| /// </summary> | ||
| public class MqttPublishException : Exception | ||
| { | ||
| /// <summary> | ||
| /// Failed to publish a message to MQTT | ||
| /// </summary> | ||
| /// <param name="msg"></param> | ||
| public MqttPublishException(string msg) : base(msg) | ||
| {} | ||
|
|
||
| /// <summary> | ||
| /// Failed to publish a message to MQTT | ||
| /// </summary> | ||
| /// <param name="msg"></param> | ||
| /// <param name="innerException"></param> | ||
| public MqttPublishException(string msg, Exception innerException) : base(msg, innerException) | ||
| {} | ||
| } |
16 changes: 16 additions & 0 deletions
16
src/Extensions/NetDaemon.Extensions.MqttEntityManager/IMessageSender.cs
This file contains hidden or 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,16 @@ | ||
| namespace NetDaemon.Extensions.MqttEntityManager; | ||
|
|
||
| /// <summary> | ||
| /// Interface to send messages to MQTT | ||
| /// </summary> | ||
| internal interface IMessageSender | ||
| { | ||
| /// <summary> | ||
| /// Send a message for the given payload to the MQTT topic | ||
| /// </summary> | ||
| /// <param name="topic"></param> | ||
| /// <param name="payload"></param> | ||
| /// <param name="retain"></param> | ||
| /// <returns></returns> | ||
| Task SendMessageAsync(string topic, string payload, bool retain = false); | ||
| } |
24 changes: 24 additions & 0 deletions
24
src/Extensions/NetDaemon.Extensions.MqttEntityManager/IMqttEntityManager.cs
This file contains hidden or 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,24 @@ | ||
| namespace NetDaemon.Extensions.MqttEntityManager; | ||
|
|
||
| /// <summary> | ||
| /// Interface for managing entities via MQTT | ||
| /// </summary> | ||
| public interface IMqttEntityManager | ||
| { | ||
| /// <summary> | ||
| /// Create an entity in Home Assistant via MQTT | ||
| /// </summary> | ||
| Task CreateAsync(string domain, string entityId, string deviceClass, string name, bool persist = true); | ||
|
|
||
|
|
||
| /// <summary> | ||
| /// Remove an entity from Home Assistant | ||
| /// </summary> | ||
| Task RemoveAsync(string domain, string entityId); | ||
|
|
||
|
|
||
| /// <summary> | ||
| /// Update state and, optionally, attributes of an HA entity via MQTT | ||
| /// </summary> | ||
| Task UpdateAsync(string domain, string entityId, string state, string? attributes = null); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.