Compare commits

...

4 Commits

11 changed files with 565 additions and 753 deletions

View File

@@ -0,0 +1,54 @@
COMMAND BEHAVIOR SUMMARY
========================
PING
----
Format:
PING
Response:
Analog_System_Monitor_<version>
Purpose:
- Confirms the device is alive
- Allows PC-side auto-discovery
- Returns firmware version
SETALL
------
Format:
SETALL: v0,v1,v2,v3,v4,v5,v6,v7
Rules:
- Exactly 8 comma-separated values
- Each value must be numeric
- Each value must be between 0 and 100
- No extra values allowed
- No missing values allowed
- No trailing commas or extra characters
Success Response:
OK
Error Response:
ERROR
Purpose:
- Updates all 8 channels in one atomic operation
- Applies calibration to each channel
- Resets watchdog timer
UNKNOWN / MALFORMED COMMANDS
----------------------------
Format:
Anything not matching PING or a valid SETALL command
Response:
ERROR
Purpose:
- Keeps protocol strict and predictable
- Prevents accidental meter movement
- Simplifies debugging

View File

@@ -1,370 +1,227 @@
// ------------------------------------------------------
// ESP32 8Channel PWM + WiFiManager + OSC (messages + bundles)
// + Slew + MultiPoint Calibration + OSC Packet Queue + Watchdog Sweep
// ------------------------------------------------------
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiManager.h>
#include <WiFiUdp.h>
#include <OSCMessage.h>
#include <OSCBundle.h>
#include <WiFiManager.h>
// -------------------------------
// User Configuration
// Firmware version
// -------------------------------
const char* FIRMWARE_VERSION = "V2.4_UDP_LEDC_WM_SLEW";
// -------------------------------
// UDP
// -------------------------------
WiFiUDP udp;
const int listenPort = 12345; // Must match PC config.json
// -------------------------------
// PWM setup (LEDC, ESP32 Core 3.x)
// -------------------------------
const uint8_t NUM_CHANNELS = 8;
uint8_t pwmPins[NUM_CHANNELS] = {26, 25, 33, 32, 27, 25, 22, 21};
const uint32_t pwmFrequency = 10000;
const uint8_t pwmResolutionBits = 10;
const uint32_t pwmMax = (1 << pwmResolutionBits) - 1;
// Slew rate: time to change 1% duty (ms)
unsigned long slewPerPercent = 50;
// OSC UDP port
const uint16_t oscPort = 9000;
// Perchannel OSC addresses (configurable)
const char* oscAddresses[NUM_CHANNELS] = {
"/cpu",
"/cputemp",
"/memory",
"/gpu3d",
"/gputemp",
"/vram",
"/netup",
"/netdown"
uint8_t pwmPins[NUM_CHANNELS] = {
26, // D0
22, // D1
21, // D2
17, // D3
16, // D4
5, // D5
18, // D6
19 // D7
// 23 (D8) remains as a spare
};
// -------------------------------
// Multipoint Calibration Tables
// -------------------------------
const uint32_t pwmFrequency = 25000; // 25 kHz
const uint8_t pwmResolution = 10; // 10-bit resolution (01023)
// -------------------------------
// Calibration tables
// -------------------------------
float logicalPoints[5] = {0, 25, 50, 75, 100};
float calibratedPoints[NUM_CHANNELS][5] = {
{0, 25, 50, 75, 99}, // CH0
{0, 24, 49, 74, 98}, // CH1
{0, 26, 51, 76, 99}, // CH2
{0, 25, 50, 75, 97}, // CH3
{0, 25, 50, 75, 99}, // CH4
{0, 24, 50, 74, 98}, // CH5
{0, 25, 49, 75, 97}, // CH6
{0, 26, 50, 76, 99} // CH7
{0, 25, 50, 75, 99},
{0, 24, 49, 74, 98},
{0, 26, 51, 76, 99},
{0, 25, 50, 75, 97},
{0, 25, 50, 75, 99},
{0, 24, 50, 74, 98},
{0, 25, 49, 75, 97},
{0, 26, 50, 76, 99}
};
// -------------------------------
// Internal Variables
// Duty tracking + Slew system
// -------------------------------
float currentDuty[NUM_CHANNELS] = {0.0f};
float targetDuty[NUM_CHANNELS] = {0.0f};
float slewStartDuty[NUM_CHANNELS] = {0.0f};
float currentDuty[NUM_CHANNELS] = {0}; // logical 0100
float targetDuty[NUM_CHANNELS] = {0}; // logical 0100
unsigned long lastSlewUpdate = 0;
WiFiUDP Udp;
unsigned long slewStartTime = 0;
const unsigned long slewDuration = 1000; // 1 second smooth transition
// -------------------------------
// OSC Packet Queue
// Watchdog (UDP-based)
// -------------------------------
#define OSC_QUEUE_SIZE 16
#define OSC_MAX_PACKET 512
struct OscPacket {
int len;
uint8_t data[OSC_MAX_PACKET];
};
OscPacket oscQueue[OSC_QUEUE_SIZE];
volatile int oscHead = 0;
volatile int oscTail = 0;
void enqueueOscPacket() {
int packetSize = Udp.parsePacket();
if (packetSize <= 0) return;
int nextHead = (oscHead + 1) % OSC_QUEUE_SIZE;
if (nextHead == oscTail) {
// Queue full → drop packet
return;
}
OscPacket &pkt = oscQueue[oscHead];
pkt.len = Udp.read(pkt.data, OSC_MAX_PACKET);
oscHead = nextHead;
}
bool dequeueOscPacket(OscPacket &pkt) {
if (oscTail == oscHead) return false;
pkt = oscQueue[oscTail];
oscTail = (oscTail + 1) % OSC_QUEUE_SIZE;
return true;
}
unsigned long lastPacketTime = 0;
const unsigned long watchdogTimeout = 5000; // 5 seconds
unsigned long lastFadeTime = 0;
// -------------------------------
// Watchdog + Sweep (smooth using slewPerPercent)
// Calibration interpolation
// -------------------------------
unsigned long lastOscTime = 0;
unsigned long watchdogTimeoutMs = 5000; // configurable
unsigned long lastSweepStep = 0;
int sweepValue = 0;
int sweepDirection = 1; // +1 or -1
bool inSweepMode = false;
void updateWatchdogAndSweep() {
unsigned long now = millis();
// Enter sweep mode if no OSC for watchdogTimeoutMs
if (!inSweepMode && (now - lastOscTime > watchdogTimeoutMs)) {
inSweepMode = true;
Serial.println("Watchdog: No OSC, entering sweep mode.");
sweepValue = 0;
sweepDirection = 1;
lastSweepStep = now;
}
// Exit sweep mode immediately when OSC resumes
if (inSweepMode && (now - lastOscTime <= watchdogTimeoutMs)) {
inSweepMode = false;
Serial.println("Watchdog: OSC resumed, exiting sweep mode.");
}
// Smooth sweep using the same slew timing as boot-up
if (inSweepMode && (now - lastSweepStep >= slewPerPercent)) {
lastSweepStep = now;
sweepValue += sweepDirection;
if (sweepValue >= 100) {
sweepValue = 100;
sweepDirection = -1;
} else if (sweepValue <= 0) {
sweepValue = 0;
sweepDirection = 1;
}
// Set all channels to the sweep target
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
targetDuty[ch] = sweepValue;
}
}
}
// -------------------------------
// Multipoint calibration function
// -------------------------------
float applyCalibration(uint8_t ch, float logicalDuty) {
if (logicalDuty <= 0) return calibratedPoints[ch][0];
if (logicalDuty >= 100) return calibratedPoints[ch][4];
if (logicalDuty <= 0.0f) return calibratedPoints[ch][0];
if (logicalDuty >= 100.0f) return calibratedPoints[ch][4];
for (int i = 0; i < 4; i++) {
if (logicalDuty >= logicalPoints[i] && logicalDuty <= logicalPoints[i+1]) {
float x0 = logicalPoints[i];
float x1 = logicalPoints[i+1];
float y0 = calibratedPoints[ch][i];
float y1 = calibratedPoints[ch][i+1];
float t = (logicalDuty - x0) / (x1 - x0);
return y0 + t * (y1 - y0); // linear interpolation
return y0 + t * (y1 - y0);
}
}
return calibratedPoints[ch][4];
}
// -------------------------------
// OSC routing (single message)
// -------------------------------
void routeOscMessage(OSCMessage &msg) {
// Any valid OSC message resets watchdog and exits sweep mode
lastOscTime = millis();
for (uint8_t ch = 0; ch < NUM_CHANNELS; ch++) {
if (msg.fullMatch(oscAddresses[ch])) {
float v = 0.0f;
if (msg.isFloat(0)) {
v = msg.getFloat(0);
} else if (msg.isInt(0)) {
v = (float)msg.getInt(0);
} else {
return;
}
if (v < 0.0f) v = 0.0f;
if (v > 1.0f) v = 1.0f;
targetDuty[ch] = v * 100.0f;
Serial.print("OSC CH");
Serial.print(ch);
Serial.print(" -> ");
Serial.println(targetDuty[ch]);
}
}
}
// -------------------------------
// Process OSC queue (messages + bundles)
// -------------------------------
void processOscQueue() {
OscPacket pkt;
while (dequeueOscPacket(pkt)) {
OSCBundle bundle;
OSCMessage msg;
for (int i = 0; i < pkt.len; i++) {
bundle.fill(pkt.data[i]);
msg.fill(pkt.data[i]);
}
if (!bundle.hasError()) {
for (int i = 0; i < bundle.size(); i++) {
OSCMessage *m = bundle.getOSCMessage(i);
if (m) routeOscMessage(*m);
}
}
else if (!msg.hasError()) {
routeOscMessage(msg);
}
}
}
// -------------------------------
// Setup
// -------------------------------
void setup() {
Serial.begin(115200);
delay(500);
delay(300);
Serial.println("ESP32 8channel PWM + WiFiManager + OSC + Queue + Watchdog starting...");
Serial.println("Booting Analog System Monitor (UDP + LEDC + WiFiManager + Slew)");
Serial.print("Firmware: ");
Serial.println(FIRMWARE_VERSION);
WiFiManager wifiManager;
wifiManager.setHostname("ESP32-PWM-OSC");
if (!wifiManager.autoConnect("ESP32-PWM-OSC")) {
Serial.println("Failed to connect, restarting...");
delay(3000);
// LEDC PWM init (ESP32 Core 3.x API)
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
bool ok = ledcAttach(pwmPins[ch], pwmFrequency, pwmResolution);
if (!ok) {
Serial.print("LEDC attach failed on pin ");
Serial.println(pwmPins[ch]);
}
ledcWrite(pwmPins[ch], 0); // duty = 0%
}
// -------------------------------
// WiFi Manager (Captive Portal)
// -------------------------------
WiFiManager wm;
wm.setHostname("AnalogMonitor");
wm.setTimeout(180); // 3 minutes before giving up
Serial.println("Starting WiFiManager...");
bool res = wm.autoConnect("AnalogMonitor-Setup");
if (!res) {
Serial.println("WiFi failed or timed out. Rebooting...");
delay(2000);
ESP.restart();
}
Serial.print("Connected. IP: ");
Serial.println("WiFi connected!");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
Udp.begin(oscPort);
Serial.print("Listening for OSC on port ");
Serial.println(oscPort);
// UDP init
udp.begin(listenPort);
Serial.print("Listening on UDP port ");
Serial.println(listenPort);
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
ledcAttach(pwmPins[ch], pwmFrequency, pwmResolutionBits);
ledcWrite(pwmPins[ch], 0);
}
delay(100);
// BOOT-UP SWEEP (all channels together, using slewPerPercent)
for (int d = 0; d <= 100; d++) {
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
float calibratedDuty = applyCalibration(ch, d);
uint32_t pwmValue = (uint32_t)((calibratedDuty / 100.0f) * pwmMax);
ledcWrite(pwmPins[ch], pwmValue);
}
delay(slewPerPercent);
}
for (int d = 100; d >= 0; d--) {
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
float calibratedDuty = applyCalibration(ch, d);
uint32_t pwmValue = (uint32_t)((calibratedDuty / 100.0f) * pwmMax);
ledcWrite(pwmPins[ch], pwmValue);
}
delay(slewPerPercent);
}
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
currentDuty[ch] = 0;
targetDuty[ch] = 0;
ledcWrite(pwmPins[ch], 0);
}
lastOscTime = millis(); // start in normal mode
Serial.println("Ready. OSC + Serial + Queue + Watchdog active.");
lastPacketTime = millis();
}
// -------------------------------
// Loop
// -------------------------------
void loop() {
// -------- UDP parsing --------
int packetSize = udp.parsePacket();
if (packetSize > 0) {
char buf[256];
int len = udp.read(buf, sizeof(buf) - 1);
buf[len] = '\0';
float values[NUM_CHANNELS] = {0};
int idx = 0;
char* token = strtok(buf, ",");
while (token != nullptr && idx < NUM_CHANNELS) {
values[idx] = atof(token);
idx++;
token = strtok(nullptr, ",");
}
if (idx == NUM_CHANNELS) {
// Start a new slew toward the target
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
targetDuty[ch] = values[ch];
slewStartDuty[ch] = currentDuty[ch];
}
slewStartTime = millis();
lastPacketTime = millis();
// Debug output
Serial.println("Received UDP packet:");
for (int i = 0; i < NUM_CHANNELS; i++) {
Serial.print(" CH");
Serial.print(i);
Serial.print(": ");
Serial.println(values[i]);
}
Serial.println();
}
}
// -------- Slew-rate limiting (smooth 1-second transitions) --------
unsigned long now = millis();
float progress = (float)(now - slewStartTime) / (float)slewDuration;
if (progress > 1.0f) progress = 1.0f;
// Grab any incoming OSC packets into the queue
enqueueOscPacket();
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
float newDuty = slewStartDuty[ch] + (targetDuty[ch] - slewStartDuty[ch]) * progress;
currentDuty[ch] = newDuty;
// Process queued OSC packets
processOscQueue();
float calibratedDuty = applyCalibration(ch, newDuty);
int duty = (int)((calibratedDuty / 100.0f) * ((1 << pwmResolution) - 1));
// Watchdog + sweep mode handling
updateWatchdogAndSweep();
// SERIAL INPUT HANDLING (X=YY)
if (Serial.available()) {
String s = Serial.readStringUntil('\n');
s.trim();
int eq = s.indexOf('=');
if (eq > 0) {
int ch = s.substring(0, eq).toInt();
int val = s.substring(eq + 1).toInt();
if (ch >= 0 && ch < NUM_CHANNELS && val >= 0 && val <= 100) {
targetDuty[ch] = val;
Serial.print("SER CH");
Serial.print(ch);
Serial.print(" -> ");
Serial.println(val);
}
}
ledcWrite(pwmPins[ch], duty);
}
// CONSTANT-RATE SLEWING (all channels)
if (now - lastSlewUpdate >= slewPerPercent) {
lastSlewUpdate = now;
// -------- Watchdog fade-to-zero (UDP-based) --------
if (millis() - lastPacketTime > watchdogTimeout) {
const unsigned long fadeInterval = 1;
if (millis() - lastFadeTime >= fadeInterval) {
lastFadeTime = millis();
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
if (currentDuty[ch] < targetDuty[ch]) {
currentDuty[ch] += 1.0f;
if (currentDuty[ch] > targetDuty[ch])
currentDuty[ch] = targetDuty[ch];
}
else if (currentDuty[ch] > targetDuty[ch]) {
currentDuty[ch] -= 1.0f;
if (currentDuty[ch] < targetDuty[ch])
currentDuty[ch] = targetDuty[ch];
}
if (currentDuty[ch] > 0.0f) {
const float fadeFactor = 0.999f;
currentDuty[ch] *= fadeFactor;
if (currentDuty[ch] < 0.01f)
currentDuty[ch] = 0.0f;
float calibratedDuty = applyCalibration(ch, currentDuty[ch]);
uint32_t pwmValue = (uint32_t)((calibratedDuty / 100.0f) * pwmMax);
ledcWrite(pwmPins[ch], pwmValue);
}
}
int duty = (int)((calibratedDuty / 100.0f) * ((1 << pwmResolution) - 1));
delay(5);
ledcWrite(pwmPins[ch], duty);
}
}
}
}
}

View File

@@ -1,44 +0,0 @@
using System;
using System.IO;
using System.Text.Json;
public class Config
{
public string OscIp { get; set; } = "127.0.0.1";
public int OscPort { get; set; } = 9000;
public int UpdateRateMs { get; set; } = 1000;
private static string ConfigPath =>
Path.Combine(AppContext.BaseDirectory, "config.json");
public static Config Load()
{
try
{
if (File.Exists(ConfigPath))
{
string json = File.ReadAllText(ConfigPath);
return JsonSerializer.Deserialize<Config>(json) ?? new Config();
}
}
catch { }
// If loading fails, create a default config
var cfg = new Config();
cfg.Save();
return cfg;
}
public void Save()
{
try
{
string json = JsonSerializer.Serialize(this, new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(ConfigPath, json);
}
catch { }
}
}

View File

@@ -1,15 +1,12 @@
using System;
using System.Windows.Forms;
namespace analog_system_monitor
internal static class Program
{
internal static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new TrayApp());
}
}
}

View File

@@ -1,338 +1,222 @@
#nullable enable
using System;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using LibreHardwareMonitor.Hardware;
public class Telemetry
public class Telemetry : IDisposable
{
private Config config;
private string oscIp = "127.0.0.1";
private int oscPort = 9000;
private const int UpdateRateDefaultMs = 1000;
public int UpdateRateMs => UpdateRateDefaultMs;
private readonly UdpSender udp = new UdpSender();
private readonly Computer computer = new Computer();
private IHardware? cpuHw;
private IHardware? gpuHw;
private IHardware? memHw;
private ISensor[] cpuLoadSensors = Array.Empty<ISensor>();
private ISensor? cpuTempSensor;
private ISensor? gpuVramUsedSensor;
private ISensor? gpuVramTotalSensor;
private ISensor? gpu3DLoadSensor;
private ISensor? gpuTempSensor;
private ISensor? gpuVramUsedSensor;
private ISensor? gpuVramTotalSensor;
private Computer computer = new Computer();
private UdpClient udp = new UdpClient();
private ISensor? memUsedSensor;
private ISensor? memAvailSensor;
// ---------------- INITIALIZATION ----------------
private static readonly CultureInfo CI = CultureInfo.InvariantCulture;
public void Initialize()
{
config = Config.Load();
// Load defaults from config
oscIp = config.OscIp;
oscPort = config.OscPort;
// Override with command-line args if provided
ParseArgs(Environment.GetCommandLineArgs());
// Save updated config (optional)
config.OscIp = oscIp;
config.OscPort = oscPort;
config.Save();
computer.IsMemoryEnabled = true;
public void Initialize()
{
computer.IsCpuEnabled = true;
computer.IsGpuEnabled = true;
computer.IsMemoryEnabled = true;
computer.Open();
DetectSensors();
}
public int UpdateRateMs => config.UpdateRateMs;
private void ParseArgs(string[] args)
{
foreach (var arg in args)
{
if (arg.StartsWith("--ip="))
oscIp = arg.Substring("--ip=".Length);
if (arg.StartsWith("--port=") &&
int.TryParse(arg.Substring("--port=".Length), out int p))
oscPort = p;
if (arg.StartsWith("--rate=") &&
int.TryParse(arg.Substring("--rate=".Length), out int r))
config.UpdateRateMs = r;
CacheHardwareAndSensors();
}
}
private void CacheHardwareAndSensors()
{
foreach (var hw in computer.Hardware)
{
hw.Update();
// ---------------- MAIN UPDATE LOOP ----------------
switch (hw.HardwareType)
{
case HardwareType.Cpu:
cpuHw = hw;
CacheCpuSensors(hw);
break;
case HardwareType.GpuNvidia:
case HardwareType.GpuAmd:
case HardwareType.GpuIntel:
gpuHw = hw;
CacheGpuSensors(hw);
break;
case HardwareType.Memory:
memHw = hw;
CacheMemorySensors(hw);
break;
}
}
}
private void CacheCpuSensors(IHardware hw)
{
var loads = new System.Collections.Generic.List<ISensor>();
foreach (var s in hw.Sensors)
{
if (s.SensorType == SensorType.Load &&
s.Name.Contains("CPU Core"))
loads.Add(s);
if (s.SensorType == SensorType.Temperature)
{
if (s.Name == "Core (Tctl/Tdie)")
cpuTempSensor = s;
else if (cpuTempSensor == null)
cpuTempSensor = s;
}
}
cpuLoadSensors = loads.ToArray();
}
private void CacheGpuSensors(IHardware hw)
{
foreach (var s in hw.Sensors)
{
if (s.SensorType == SensorType.Load)
{
if (s.Name == "D3D 3D")
gpu3DLoadSensor = s;
else if (gpu3DLoadSensor == null && s.Name == "GPU Core")
gpu3DLoadSensor = s;
}
if (s.SensorType == SensorType.Temperature)
{
if (s.Name == "GPU Core")
gpuTempSensor = s;
else if (gpuTempSensor == null)
gpuTempSensor = s;
}
if (s.SensorType == SensorType.SmallData)
{
if (s.Name == "GPU Memory Used")
gpuVramUsedSensor = s;
if (s.Name == "GPU Memory Total")
gpuVramTotalSensor = s;
}
}
}
private void CacheMemorySensors(IHardware hw)
{
foreach (var s in hw.Sensors)
{
if (s.SensorType == SensorType.Data && s.Name == "Memory Used")
memUsedSensor = s;
if (s.SensorType == SensorType.Data && s.Name == "Memory Available")
memAvailSensor = s;
}
}
public void UpdateAndSend()
{
int memPercent = GetMemoryUsagePercent();
int cpuPercent = GetCpuLoadPercent();
int vramPercent = GetGpuVramPercent();
int gpu3DPercent = GetGpu3DLoad();
int cpuTempPercent = GetCpuTemperaturePercent();
int gpuTempPercent = GetGpuTemperaturePercent();
cpuHw?.Update();
gpuHw?.Update();
memHw?.Update();
SendOscBundle(
cpuPercent / 100f,
cpuTempPercent / 100f,
memPercent / 100f,
gpu3DPercent / 100f,
gpuTempPercent / 100f,
vramPercent / 100f
);
}
float cpu = GetCpuLoadPercent();
float cpuTemp = GetCpuTemperaturePercent();
float mem = GetMemoryUsagePercent();
float gpu3d = GetGpu3DLoad();
float gpuTemp = GetGpuTemperaturePercent();
float vram = GetGpuVramPercent();
// ---------------- SENSOR DETECTION ----------------
private void DetectSensors()
// Prepare 8 floats (futureproof)
float[] packet =
{
var cpuLoadList = new List<ISensor>();
cpu,
cpuTemp,
mem,
gpu3d,
gpuTemp,
vram,
0f, // reserved for future use
0f // reserved for future use
};
ISensor? bestCpuTemp = null;
ISensor? bestGpuTemp = null;
ISensor? bestGpu3D = null;
ISensor? bestVramUsed = null;
ISensor? bestVramTotal = null;
foreach (var hw in computer.Hardware)
{
hw.Update();
if (hw.HardwareType == HardwareType.Cpu)
{
foreach (var sensor in hw.Sensors)
{
if (sensor.SensorType == SensorType.Load &&
sensor.Name.Contains("CPU Core"))
cpuLoadList.Add(sensor);
if (sensor.SensorType == SensorType.Temperature)
{
if (sensor.Name == "Core (Tctl/Tdie)")
bestCpuTemp = sensor;
else if (bestCpuTemp == null)
bestCpuTemp = sensor;
}
}
udp.SendFloats(packet);
}
if (hw.HardwareType == HardwareType.GpuNvidia ||
hw.HardwareType == HardwareType.GpuAmd ||
hw.HardwareType == HardwareType.GpuIntel)
{
foreach (var sensor in hw.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
if (sensor.Name == "GPU Core")
bestGpuTemp = sensor;
else if (bestGpuTemp == null)
bestGpuTemp = sensor;
}
if (sensor.SensorType == SensorType.Load)
{
if (sensor.Name == "D3D 3D")
bestGpu3D = sensor;
else if (bestGpu3D == null && sensor.Name == "GPU Core")
bestGpu3D = sensor;
}
if (sensor.SensorType == SensorType.SmallData)
{
if (sensor.Name == "GPU Memory Used")
bestVramUsed = sensor;
if (sensor.Name == "GPU Memory Total")
bestVramTotal = sensor;
}
}
}
}
cpuLoadSensors = cpuLoadList.ToArray();
cpuTempSensor = bestCpuTemp;
gpuTempSensor = bestGpuTemp;
gpu3DLoadSensor = bestGpu3D;
gpuVramUsedSensor = bestVramUsed;
gpuVramTotalSensor = bestVramTotal;
}
// ---------------- METRICS ----------------
private int GetMemoryUsagePercent()
{
float used = 0;
float available = 0;
foreach (var hw in computer.Hardware)
{
if (hw.HardwareType == HardwareType.Memory)
{
hw.Update();
foreach (var sensor in hw.Sensors)
{
if (sensor.SensorType == SensorType.Data && sensor.Name == "Memory Used")
used = sensor.Value ?? 0;
if (sensor.SensorType == SensorType.Data && sensor.Name == "Memory Available")
available = sensor.Value ?? 0;
}
}
}
float total = used + available;
if (total <= 0) return 0;
return (int)Math.Round((used / total) * 100);
}
private int GetCpuLoadPercent()
private float GetCpuLoadPercent()
{
if (cpuLoadSensors.Length == 0) return 0;
float total = 0;
int count = 0;
foreach (var sensor in cpuLoadSensors)
foreach (var s in cpuLoadSensors)
{
sensor.Hardware.Update();
total += sensor.Value ?? 0;
total += s.Value ?? 0;
count++;
}
return count == 0 ? 0 : (int)Math.Round(total / count);
return count == 0 ? 0 : total / count;
}
private int GetGpuVramPercent()
private float GetCpuTemperaturePercent()
{
if (gpuVramUsedSensor == null || gpuVramTotalSensor == null)
return 0;
gpuVramUsedSensor.Hardware.Update();
float usedMB = gpuVramUsedSensor.Value ?? 0;
float totalMB = gpuVramTotalSensor.Value ?? 0;
if (totalMB <= 0) return 0;
return (int)Math.Round((usedMB / totalMB) * 100);
float t = cpuTempSensor?.Value ?? 0;
return Math.Clamp(t, 0, 100);
}
private int GetGpu3DLoad()
private float GetGpu3DLoad()
{
if (gpu3DLoadSensor == null) return 0;
gpu3DLoadSensor.Hardware.Update();
return (int)Math.Round(gpu3DLoadSensor.Value ?? 0);
return gpu3DLoadSensor?.Value ?? 0;
}
private int GetCpuTemperaturePercent()
private float GetGpuTemperaturePercent()
{
if (cpuTempSensor == null) return 0;
cpuTempSensor.Hardware.Update();
float temp = cpuTempSensor.Value ?? 0;
return (int)Math.Round(Math.Clamp(temp, 0, 100));
float t = gpuTempSensor?.Value ?? 0;
return Math.Clamp(t, 0, 100);
}
private int GetGpuTemperaturePercent()
private float GetGpuVramPercent()
{
if (gpuTempSensor == null) return 0;
float used = gpuVramUsedSensor?.Value ?? 0;
float total = gpuVramTotalSensor?.Value ?? 0;
gpuTempSensor.Hardware.Update();
float temp = gpuTempSensor.Value ?? 0;
return (int)Math.Round(Math.Clamp(temp, 0, 100));
if (total <= 0) return 0;
return (used / total) * 100f;
}
// ---------------- OSC ----------------
private void SendOscBundle(
float cpu, float cpuTemp, float mem,
float gpu3d, float gpuTemp, float vram)
private float GetMemoryUsagePercent()
{
var messages = new List<byte[]>();
float used = memUsedSensor?.Value ?? 0;
float avail = memAvailSensor?.Value ?? 0;
messages.Add(BuildOscFloatMessage("/cpu", cpu));
messages.Add(BuildOscFloatMessage("/cputemp", cpuTemp));
messages.Add(BuildOscFloatMessage("/memory", mem));
messages.Add(BuildOscFloatMessage("/gpu3d", gpu3d));
messages.Add(BuildOscFloatMessage("/gputemp", gpuTemp));
messages.Add(BuildOscFloatMessage("/vram", vram));
float total = used + avail;
if (total <= 0) return 0;
byte[] bundle = BuildOscBundle(messages);
udp.Send(bundle, bundle.Length, oscIp, oscPort);
return (used / total) * 100f;
}
private byte[] BuildOscBundle(List<byte[]> messages)
public void Dispose()
{
List<byte[]> parts = new List<byte[]>();
parts.Add(PadOscString("#bundle"));
byte[] timetag = new byte[8];
timetag[7] = 1;
parts.Add(timetag);
foreach (var msg in messages)
{
byte[] len = BitConverter.GetBytes(msg.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(len);
parts.Add(len);
parts.Add(msg);
}
int total = 0;
foreach (var p in parts)
total += p.Length;
byte[] bundle = new byte[total];
int offset = 0;
foreach (var p in parts)
{
Buffer.BlockCopy(p, 0, bundle, offset, p.Length);
offset += p.Length;
}
return bundle;
}
private byte[] BuildOscFloatMessage(string address, float value)
{
byte[] addr = PadOscString(address);
byte[] types = PadOscString(",f");
byte[] floatBytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
Array.Reverse(floatBytes);
byte[] packet = new byte[addr.Length + types.Length + floatBytes.Length];
Buffer.BlockCopy(addr, 0, packet, 0, addr.Length);
Buffer.BlockCopy(types, 0, packet, addr.Length, types.Length);
Buffer.BlockCopy(floatBytes, 0, packet, addr.Length + types.Length, floatBytes.Length);
return packet;
}
private byte[] PadOscString(string s)
{
byte[] raw = Encoding.ASCII.GetBytes(s);
int paddedLength = ((raw.Length + 1 + 3) / 4) * 4;
byte[] padded = new byte[paddedLength];
Buffer.BlockCopy(raw, 0, padded, 0, raw.Length);
return padded;
udp.Dispose();
computer.Close();
}
}

View File

@@ -1,86 +1,40 @@
#nullable enable
using System;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
namespace analog_system_monitor
public class TrayApp : ApplicationContext
{
public class TrayApp : ApplicationContext
{
private NotifyIcon trayIcon;
private Thread workerThread;
private bool running = true;
private Telemetry telemetry;
public TrayApp()
{
trayIcon = new NotifyIcon()
{
Icon = LoadEmbeddedIcon(),
Text = "Analog System Monitor",
Visible = true,
ContextMenuStrip = BuildMenu()
};
workerThread = new Thread(WorkerLoop)
{
IsBackground = true
};
workerThread.Start();
}
private Icon LoadEmbeddedIcon()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "analog_system_monitor.telemetry_icon.ico";
using var stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
MessageBox.Show("Embedded icon not found: " + resourceName);
return SystemIcons.Application;
}
return new Icon(stream);
}
private ContextMenuStrip BuildMenu()
{
var menu = new ContextMenuStrip();
var exitItem = new ToolStripMenuItem("Exit");
exitItem.Click += (s, e) => ExitApp();
menu.Items.Add(exitItem);
return menu;
}
private void WorkerLoop()
{
var telemetry = new Telemetry();
telemetry = new Telemetry();
telemetry.Initialize();
while (running)
trayIcon = new NotifyIcon()
{
telemetry.UpdateAndSend();
Thread.Sleep(telemetry.UpdateRateMs);
}
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath),
Visible = true,
Text = "Telemetry Running (UDP)"
};
var menu = new ContextMenuStrip();
menu.Items.Add("Exit", null, OnExit);
trayIcon.ContextMenuStrip = menu;
var timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += (s, e) => telemetry.UpdateAndSend();
timer.Start();
}
private void ExitApp()
private void OnExit(object? sender, EventArgs e)
{
running = false;
try
{
workerThread?.Join(500);
}
catch { }
telemetry.Dispose();
trayIcon.Visible = false;
trayIcon.Dispose();
Application.Exit();
}
}
}

View File

@@ -0,0 +1,64 @@
#nullable enable
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.Json;
public class UdpSender : IDisposable
{
private readonly UdpClient client = new UdpClient();
private IPEndPoint endpoint;
private const string DefaultIp = "192.168.1.50";
private const int DefaultPort = 12345;
public UdpSender()
{
string exeDir = AppContext.BaseDirectory;
string cfgPath = Path.Combine(exeDir, "config.json");
// Create default config if missing
if (!File.Exists(cfgPath))
{
var defaultCfg = new UdpConfig
{
esp32_ip = DefaultIp,
esp32_port = DefaultPort
};
string json = JsonSerializer.Serialize(
defaultCfg,
new JsonSerializerOptions { WriteIndented = true }
);
File.WriteAllText(cfgPath, json);
}
// Load config
var jsonText = File.ReadAllText(cfgPath);
var cfg = JsonSerializer.Deserialize<UdpConfig>(jsonText)
?? throw new Exception("Invalid config.json");
endpoint = new IPEndPoint(IPAddress.Parse(cfg.esp32_ip), cfg.esp32_port);
}
public void SendFloats(float[] values)
{
string packet = string.Join(",", values);
byte[] data = System.Text.Encoding.ASCII.GetBytes(packet);
client.Send(data, data.Length, endpoint);
}
public void Dispose()
{
client.Dispose();
}
private class UdpConfig
{
public string esp32_ip { get; set; } = DefaultIp;
public int esp32_port { get; set; } = DefaultPort;
}
}

View File

@@ -4,14 +4,23 @@
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- Single-file EXE -->
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<DebugType>None</DebugType>
<!-- No trimming (LHM + reflection will break) -->
<PublishTrimmed>false</PublishTrimmed>
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
<InvariantGlobalization>true</InvariantGlobalization>
<!-- Keep debugging symbols optional -->
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
<ApplicationIcon>telemetry_icon.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="*"
name="AnalogSystemMonitor"
type="win32"
/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<!-- Force the EXE to always run as administrator -->
<requestedExecutionLevel
level="requireAdministrator"
uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>

View File

@@ -0,0 +1,53 @@
# ============================================
# Build Release Single-File EXE for Analog System Monitor
# Output directory: ./release/
# ============================================
Write-Host "=== Analog System Monitor Release Build ===" -ForegroundColor Cyan
# Ensure script runs from project directory
$project = "analog_system_monitor.csproj"
if (!(Test-Path $project)) {
Write-Host "Error: Telemetry.csproj not found in this directory." -ForegroundColor Red
exit 1
}
# Clean previous builds
Write-Host "Cleaning previous build artifacts..."
dotnet clean -c Release
# Publish using settings from the .csproj
Write-Host "Publishing Release build..."
dotnet publish -c Release
# Determine publish folder
$publishDir = Join-Path "bin" "Release\net10.0-windows\win-x64\publish"
if (!(Test-Path $publishDir)) {
Write-Host "Error: Publish directory not found." -ForegroundColor Red
exit 1
}
# Custom output directory
$releaseDir = Join-Path (Get-Location) "release"
# Create directory if missing
if (!(Test-Path $releaseDir)) {
Write-Host "Creating release directory..."
New-Item -ItemType Directory -Path $releaseDir | Out-Null
}
# Copy all published files to ./release/
Write-Host "Copying published files to ./release/ ..."
Copy-Item -Path "$publishDir\*" -Destination $releaseDir -Recurse -Force
Write-Host "Build completed successfully!" -ForegroundColor Green
Write-Host "Release output: $releaseDir"
# List produced files
Write-Host "`nRelease files:"
Get-ChildItem $releaseDir | Format-Table Name, Length
# Open folder in Explorer
Write-Host "`nOpening release folder..."
Start-Process explorer.exe $releaseDir

View File

@@ -1,51 +0,0 @@
# ============================================
# Analog System Monitor Release Script
# Creates a clean, single-file Windows build
# ============================================
param(
[string]$Version = "1.0.0"
)
$ErrorActionPreference = "Stop"
Write-Host "=== Analog System Monitor Release Script ==="
Write-Host "Version: $Version"
Write-Host ""
# Paths
$project = "analog_system_monitor.csproj"
$releaseDir = "release\$Version"
# Clean old release
if (Test-Path $releaseDir) {
Write-Host "Cleaning old release directory..."
Remove-Item -Recurse -Force $releaseDir
}
# Ensure release directory exists
New-Item -ItemType Directory -Force -Path $releaseDir | Out-Null
Write-Host "Restoring packages..."
dotnet restore $project
Write-Host "Cleaning project..."
dotnet clean $project -c Release
Write-Host "Publishing single-file executable..."
dotnet publish $project `
-c Release `
-r win-x64 `
--self-contained true `
/p:PublishSingleFile=true `
/p:IncludeNativeLibrariesForSelfExtract=true `
/p:DebugType=None `
/p:DebugSymbols=false `
/p:Version=$Version `
-o "$releaseDir"
Write-Host ""
Write-Host "============================================"
Write-Host " Release build completed successfully"
Write-Host " Output folder: $releaseDir"
Write-Host "============================================"