mirror of
https://github.com/ckaczor/HomeMonitor.git
synced 2026-01-14 01:25:38 -05:00
Initial framework of the power service
This commit is contained in:
81
Power/Service/PowerReader.cs
Normal file
81
Power/Service/PowerReader.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using ChrisKaczor.HomeMonitor.Power.Service.Models;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using RestSharp;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public class PowerReader : IHostedService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
private HubConnection _hubConnection;
|
||||
private Timer _readTimer;
|
||||
|
||||
public PowerReader(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_readTimer = new Timer(OnTimer, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
|
||||
|
||||
if (!string.IsNullOrEmpty(_configuration["Hub:Power"]))
|
||||
_hubConnection = new HubConnectionBuilder().WithUrl(_configuration["Hub:Power"]).Build();
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnTimer(object state)
|
||||
{
|
||||
var client = new RestClient(_configuration["Power:Host"]);
|
||||
|
||||
var request = new RestRequest("current-sample", Method.GET);
|
||||
request.AddHeader("Authorization", _configuration["Power:AuthorizationHeader"]);
|
||||
|
||||
var response = client.Execute(request);
|
||||
|
||||
var sample = JsonSerializer.Deserialize<PowerSample>(response.Content);
|
||||
|
||||
Console.WriteLine(sample.Channels[2].Type + " " + sample.Channels[2].RealPower);
|
||||
Console.WriteLine(sample.Channels[3].Type + " " + sample.Channels[3].RealPower);
|
||||
|
||||
if (_hubConnection == null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
if (_hubConnection.State == HubConnectionState.Disconnected)
|
||||
_hubConnection.StartAsync().Wait();
|
||||
|
||||
_hubConnection.InvokeAsync("SendLatestSample", response.Content).Wait();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WriteLog($"Hub exception: {exception}");
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_readTimer.Dispose();
|
||||
|
||||
_hubConnection?.StopAsync(cancellationToken).Wait(cancellationToken);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static void WriteLog(string message)
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user