Innovenergy_trunk/csharp/App/SchneiderMeterDriver/SchneiderMeterDriver.cs

92 lines
3.1 KiB
C#
Raw Normal View History

2024-06-12 12:05:29 +00:00
using System.Reactive.Linq;
2024-06-04 10:23:19 +00:00
using InnovEnergy.Lib.Devices.IEM3kGridMeter;
using InnovEnergy.Lib.Protocols.DBus;
using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Utils;
using InnovEnergy.Lib.Victron.VeDBus;
2024-06-04 13:28:17 +00:00
namespace InnovEnergy.App.SchneiderDriver;
2024-06-04 10:23:19 +00:00
2024-06-04 13:28:17 +00:00
public static class SchneiderMeterDriver
2024-06-04 10:23:19 +00:00
{
2024-06-12 12:05:29 +00:00
2024-06-04 10:23:19 +00:00
public static Task<Exception> Run(String hostName, Bus dbusAddress)
{
return Run(hostName, ModbusTcpClient.DefaultPort, dbusAddress);
}
2024-06-04 10:23:19 +00:00
public static async Task<Exception> Run(String hostName, UInt16 port, Bus dbusAddress)
{
// var ep = new UnixDomainSocketEndPoint("/home/eef/graber_dbus.sock");
// var auth = AuthenticationMethod.ExternalAsRoot();
// dbusAddress = new Bus(ep, auth);
var schneider = new Iem3KGridMeterDevice(hostName, port, Config.ModbusNodeId);
var schneiderStatus = Observable
.Interval(Config.UpdatePeriod)
.Select(_ => schneider.Read())
.Where(reading => reading != null)
.Publish();
2024-06-04 10:23:19 +00:00
var poller = schneiderStatus.Connect();
2024-06-04 10:23:19 +00:00
var properties = Config.DefaultProperties;
2024-06-12 12:05:29 +00:00
var signals = Config
.Signals
.Select(signal => schneiderStatus
.Select(reading =>
{
var property = signal.ToVeProperty(reading);
if (property == null)
{
// Console.WriteLine($"Warning: Signal {signal} produced a null property.");
2024-06-12 12:05:29 +00:00
}
else
{
//Console.WriteLine($"Transformed Signal to Property: {property}");
2024-06-12 12:05:29 +00:00
}
return property;
})
.Where(property => property != null))
.Merge()
.Do(p =>
{
// Console.WriteLine($"Setting property: {p}");
properties.Set(p);
});
2024-06-12 12:05:29 +00:00
// TODO: remove when possible
2024-06-04 10:23:19 +00:00
// Apparently some VE services need to be periodically reminded that
// this service is /Connected
2024-06-12 12:05:29 +00:00
Console.WriteLine("Goes to subscribe");
schneiderStatus.Subscribe(_ => properties.Set("/Connected", 1));
2024-06-12 12:05:29 +00:00
Console.WriteLine("Subscribed successfully");
2024-06-04 10:23:19 +00:00
// Wait until status is read once to make sure all
// properties are set when we go onto the bus.
var dbus = schneiderStatus
.Skip(1)
.Take(1)
.SelectMany(_ => PublishPropertiesOnDBus(properties, dbusAddress));
2024-06-04 10:23:19 +00:00
return await signals
.MergeErrors(dbus)
.Finally(poller.Dispose)
.SelectErrors();
2024-06-04 10:23:19 +00:00
}
private static Task<Exception> PublishPropertiesOnDBus(VeProperties properties, Bus bus)
{
Console.WriteLine($"Connecting to DBus {bus}");
return properties.PublishOnDBus(bus, Config.BusName);
}
2024-06-07 08:36:15 +00:00
}