wip notify infrastructure

notify
sleevezipper 4 years ago
parent 3255e94620
commit 93072d4dcd

@ -1,16 +1,19 @@
using System;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using hass_workstation_service.Communication.InterProcesCommunication.Models;
using hass_workstation_service.Communication.Util;
using hass_workstation_service.Data;
using hass_workstation_service.Domain.Notify;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Adapter;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using Serilog;
using static hass_workstation_service.Domain.Notify.Notifier;
namespace hass_workstation_service.Communication
{
@ -20,6 +23,7 @@ namespace hass_workstation_service.Communication
private readonly IMqttClient _mqttClient;
private readonly ILogger<MqttPublisher> _logger;
private readonly IConfigurationService _configurationService;
private readonly Notifier _notifier;
private string _mqttClientMessage { get; set; }
public DateTime LastConfigAnnounce { get; private set; }
public DeviceConfigModel DeviceConfigModel { get; private set; }
@ -41,12 +45,14 @@ namespace hass_workstation_service.Communication
public MqttPublisher(
ILogger<MqttPublisher> logger,
DeviceConfigModel deviceConfigModel,
IConfigurationService configurationService)
IConfigurationService configurationService,
Notifier notifier)
{
this._logger = logger;
this.DeviceConfigModel = deviceConfigModel;
this._configurationService = configurationService;
this._notifier = notifier;
var options = _configurationService.GetMqttClientOptionsAsync().Result;
_configurationService.MqqtConfigChangedHandler = this.ReplaceMqttClient;
@ -63,11 +69,20 @@ namespace hass_workstation_service.Communication
{
this._mqttClientMessage = "Not configured";
}
this._mqttClient.UseConnectedHandler(e => {
this._mqttClient.UseConnectedHandler(e =>
{
this._mqttClientMessage = "All good";
// subscribe to the default notify topic
this._mqttClient.SubscribeAsync(
new MqttTopicFilterBuilder()
.WithTopic($"homeassistant/sensor/{this.DeviceConfigModel.Name}/notify")
.Build());
});
this._mqttClient.UseApplicationMessageReceivedHandler(e => this.HandleMessageReceived(e.ApplicationMessage));
// configure what happens on disconnect
this._mqttClient.UseDisconnectedHandler(async e =>
{
@ -135,12 +150,35 @@ namespace hass_workstation_service.Communication
this._mqttClientMessage = ex.ResultCode.ToString();
Log.Logger.Error("Could not connect to broker: " + ex.ResultCode.ToString());
}
}
public MqqtClientStatus GetStatus()
{
return new MqqtClientStatus() { IsConnected = _mqttClient.IsConnected, Message = _mqttClientMessage };
}
private void HandleMessageReceived(MqttApplicationMessage applicationMessage)
{
NotificationModel notification;
try
{
notification = JsonSerializer.Deserialize<NotificationModel>(Encoding.UTF8.GetString(applicationMessage?.Payload));
}
catch (Exception)
{
notification = new NotificationModel("Error", $"Invalid message: {Encoding.UTF8.GetString(applicationMessage?.Payload)}");
}
this._notifier.GenerateToast(notification);
Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
Console.WriteLine($"+ Topic = {applicationMessage.Topic}");
Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(applicationMessage?.Payload)}");
Console.WriteLine($"+ QoS = {applicationMessage.QualityOfServiceLevel}");
Console.WriteLine($"+ Retain = {applicationMessage.Retain}");
Console.WriteLine();
}
}
}

@ -0,0 +1,60 @@
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
namespace hass_workstation_service.Domain.Notify
{
public class Notifier
{
public void GenerateToast(NotificationModel notificationModel)
{
var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
var textNodes = template.GetElementsByTagName("text");
textNodes[0].AppendChild(template.CreateTextNode(notificationModel.Title));
textNodes[2].AppendChild(template.CreateTextNode(notificationModel.Content));
if (File.Exists(notificationModel.ImagePath))
{
XmlNodeList toastImageElements = template.GetElementsByTagName("image");
((XmlElement)toastImageElements[0]).SetAttribute("src", notificationModel.ImagePath);
}
IXmlNode toastNode = template.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("duration", "long");
var notifier = ToastNotificationManager.CreateToastNotifier("Home Assistant");
var notification = new ToastNotification(template);
notifier.Show(notification);
}
public class NotificationModel
{
public string Title { get; private set; }
public string Content { get; private set; }
public string ImagePath { get; private set; }
[JsonConstructor]
public NotificationModel(string title, string content)
{
Title = title;
Content = content;
this.ImagePath = Path.Combine(Environment.CurrentDirectory, @"hass-workstation-logo.ico");
}
public NotificationModel(string title, string content, string imagePath)
{
Title = title;
Content = content;
ImagePath = imagePath;
}
}
}
}

@ -19,6 +19,7 @@ using Microsoft.Win32;
using JKang.IpcServiceFramework.Hosting;
using hass_workstation_service.Communication.NamedPipe;
using hass_workstation_service.Communication.InterProcesCommunication;
using hass_workstation_service.Domain.Notify;
namespace hass_workstation_service
{
@ -88,6 +89,7 @@ namespace hass_workstation_service
services.AddSingleton<IConfigurationService, ConfigurationService>();
services.AddSingleton<MqttPublisher>();
services.AddHostedService<Worker>();
services.AddSingleton<Notifier>();
}).ConfigureIpcHost(builder =>
{
// configure IPC endpoints

@ -5,6 +5,7 @@ using System.Threading;
using System.Threading.Tasks;
using hass_workstation_service.Communication;
using hass_workstation_service.Data;
using hass_workstation_service.Domain.Notify;
using hass_workstation_service.Domain.Sensors;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

@ -44,6 +44,7 @@
<PackageReference Include="JKang.IpcServiceFramework.Hosting.NamedPipe" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageReference Include="Microsoft.Windows.SDK.Contracts" Version="10.0.19041.1" />
<PackageReference Include="MQTTnet" Version="3.0.13" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.5.1.20201229" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />

Loading…
Cancel
Save