-
-
Notifications
You must be signed in to change notification settings - Fork 0
Outlet power logging
Ben Hutchison edited this page May 29, 2023
·
1 revision
The following small C# program lets you log the power levels of the Kasa smart outlet over time. This will allow you to determine the values to use when configuring the minimumActiveMilliwatts
and maximumIdleMilliwatts
properties in LaundryDuty's appsettings.json
file.
dotnet add package Kasa
using System.Text;
using Kasa;
using Timer = System.Threading.Timer;
using IKasaOutlet outlet = new KasaOutlet("washingmachine.outlets.aldaviva.com", new Options { MaxAttempts = 1 });
using FileStream tsvFile = File.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "washingmachine-power.tsv"), FileMode.Append, FileAccess.Write,
FileShare.Read);
using StreamWriter tsvWriter = new(tsvFile, new UTF8Encoding(false, true));
CancellationTokenSource cts = new();
DateTime start = DateTime.Now;
WriteTsvLine(string.Join('\t', "elapsed_sec", "current_mA", "voltage_mV", "power_mW"));
Timer timer = new(async _ => {
PowerUsage power = await outlet.EnergyMeter.GetInstantaneousPowerUsage();
WriteTsvLine(string.Join('\t', (DateTime.Now - start).TotalSeconds.ToString("N0"), power.Current.ToString("N0"), power.Voltage.ToString("N0"), power.Power.ToString("N0")));
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
Console.CancelKeyPress += (_, _) => cts.Cancel();
cts.Token.WaitHandle.WaitOne();
timer.Dispose();
void WriteTsvLine(string line) {
tsvWriter.WriteLine(line);
tsvWriter.Flush();
Console.WriteLine(line);
}
When you compile and run this program (with Visual Studio or dotnet run
, it prints a tab-separated listing of the outlet's energy meter state to the console and to a file on your desktop once per second.
elapsed_sec current_mA voltage_mV power_mW
0 0 122,559 403
1 0 122,559 0
2 0 122,559 0
3 0 122,559 0
4 0 122,559 0
5 9 122,559 0
6 9 122,482 0
7 9 122,482 0
8 9 122,482 0
9 9 122,482 0
10 9 122,482 475
11 9 122,482 475
12 0 122,482 475
13 0 122,482 475
14 0 122,536 475
15 0 122,536 475
16 0 122,536 475
17 0 122,536 475
18 0 122,536 475
19 0 122,536 0
20 0 122,536 0