Compare commits
4 Commits
aac8f3c820
...
a9957bc695
| Author | SHA1 | Date | |
|---|---|---|---|
| a9957bc695 | |||
| 2311647885 | |||
| d432db9985 | |||
| 73c7dfb8e5 |
54
analog_system_monitor_arduino/Command_Summary.txt
Normal file
54
analog_system_monitor_arduino/Command_Summary.txt
Normal 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
|
||||||
@@ -1,370 +1,227 @@
|
|||||||
// ------------------------------------------------------
|
|
||||||
// ESP32 8‑Channel PWM + WiFiManager + OSC (messages + bundles)
|
|
||||||
// + Slew + Multi‑Point Calibration + OSC Packet Queue + Watchdog Sweep
|
|
||||||
// ------------------------------------------------------
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <WiFi.h>
|
#include <WiFi.h>
|
||||||
#include <WiFiManager.h>
|
|
||||||
#include <WiFiUdp.h>
|
#include <WiFiUdp.h>
|
||||||
#include <OSCMessage.h>
|
#include <WiFiManager.h>
|
||||||
#include <OSCBundle.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;
|
const uint8_t NUM_CHANNELS = 8;
|
||||||
|
|
||||||
uint8_t pwmPins[NUM_CHANNELS] = {26, 25, 33, 32, 27, 25, 22, 21};
|
uint8_t pwmPins[NUM_CHANNELS] = {
|
||||||
|
26, // D0
|
||||||
const uint32_t pwmFrequency = 10000;
|
22, // D1
|
||||||
const uint8_t pwmResolutionBits = 10;
|
21, // D2
|
||||||
const uint32_t pwmMax = (1 << pwmResolutionBits) - 1;
|
17, // D3
|
||||||
|
16, // D4
|
||||||
// Slew rate: time to change 1% duty (ms)
|
5, // D5
|
||||||
unsigned long slewPerPercent = 50;
|
18, // D6
|
||||||
|
19 // D7
|
||||||
// OSC UDP port
|
// 23 (D8) remains as a spare
|
||||||
const uint16_t oscPort = 9000;
|
|
||||||
|
|
||||||
// Per‑channel OSC addresses (configurable)
|
|
||||||
const char* oscAddresses[NUM_CHANNELS] = {
|
|
||||||
"/cpu",
|
|
||||||
"/cputemp",
|
|
||||||
"/memory",
|
|
||||||
"/gpu3d",
|
|
||||||
"/gputemp",
|
|
||||||
"/vram",
|
|
||||||
"/netup",
|
|
||||||
"/netdown"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// -------------------------------
|
const uint32_t pwmFrequency = 25000; // 25 kHz
|
||||||
// Multi‑point Calibration Tables
|
const uint8_t pwmResolution = 10; // 10-bit resolution (0–1023)
|
||||||
// -------------------------------
|
|
||||||
|
|
||||||
|
// -------------------------------
|
||||||
|
// Calibration tables
|
||||||
|
// -------------------------------
|
||||||
float logicalPoints[5] = {0, 25, 50, 75, 100};
|
float logicalPoints[5] = {0, 25, 50, 75, 100};
|
||||||
|
|
||||||
float calibratedPoints[NUM_CHANNELS][5] = {
|
float calibratedPoints[NUM_CHANNELS][5] = {
|
||||||
{0, 25, 50, 75, 99}, // CH0
|
{0, 25, 50, 75, 99},
|
||||||
{0, 24, 49, 74, 98}, // CH1
|
{0, 24, 49, 74, 98},
|
||||||
{0, 26, 51, 76, 99}, // CH2
|
{0, 26, 51, 76, 99},
|
||||||
{0, 25, 50, 75, 97}, // CH3
|
{0, 25, 50, 75, 97},
|
||||||
{0, 25, 50, 75, 99}, // CH4
|
{0, 25, 50, 75, 99},
|
||||||
{0, 24, 50, 74, 98}, // CH5
|
{0, 24, 50, 74, 98},
|
||||||
{0, 25, 49, 75, 97}, // CH6
|
{0, 25, 49, 75, 97},
|
||||||
{0, 26, 50, 76, 99} // CH7
|
{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 0–100
|
unsigned long slewStartTime = 0;
|
||||||
float targetDuty[NUM_CHANNELS] = {0}; // logical 0–100
|
const unsigned long slewDuration = 1000; // 1 second smooth transition
|
||||||
|
|
||||||
unsigned long lastSlewUpdate = 0;
|
|
||||||
|
|
||||||
WiFiUDP Udp;
|
|
||||||
|
|
||||||
// -------------------------------
|
// -------------------------------
|
||||||
// OSC Packet Queue
|
// Watchdog (UDP-based)
|
||||||
// -------------------------------
|
// -------------------------------
|
||||||
|
unsigned long lastPacketTime = 0;
|
||||||
#define OSC_QUEUE_SIZE 16
|
const unsigned long watchdogTimeout = 5000; // 5 seconds
|
||||||
#define OSC_MAX_PACKET 512
|
unsigned long lastFadeTime = 0;
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------
|
// -------------------------------
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------
|
|
||||||
// Multi‑point calibration function
|
|
||||||
// -------------------------------
|
|
||||||
|
|
||||||
float applyCalibration(uint8_t ch, float logicalDuty) {
|
float applyCalibration(uint8_t ch, float logicalDuty) {
|
||||||
if (logicalDuty <= 0) return calibratedPoints[ch][0];
|
if (logicalDuty <= 0.0f) return calibratedPoints[ch][0];
|
||||||
if (logicalDuty >= 100) return calibratedPoints[ch][4];
|
if (logicalDuty >= 100.0f) return calibratedPoints[ch][4];
|
||||||
|
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
if (logicalDuty >= logicalPoints[i] && logicalDuty <= logicalPoints[i+1]) {
|
if (logicalDuty >= logicalPoints[i] && logicalDuty <= logicalPoints[i+1]) {
|
||||||
|
|
||||||
float x0 = logicalPoints[i];
|
float x0 = logicalPoints[i];
|
||||||
float x1 = logicalPoints[i+1];
|
float x1 = logicalPoints[i+1];
|
||||||
float y0 = calibratedPoints[ch][i];
|
float y0 = calibratedPoints[ch][i];
|
||||||
float y1 = calibratedPoints[ch][i+1];
|
float y1 = calibratedPoints[ch][i+1];
|
||||||
|
|
||||||
float t = (logicalDuty - x0) / (x1 - x0);
|
float t = (logicalDuty - x0) / (x1 - x0);
|
||||||
|
return y0 + t * (y1 - y0);
|
||||||
return y0 + t * (y1 - y0); // linear interpolation
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return calibratedPoints[ch][4];
|
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
|
// Setup
|
||||||
// -------------------------------
|
// -------------------------------
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
delay(500);
|
delay(300);
|
||||||
|
|
||||||
Serial.println("ESP32 8‑channel 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;
|
// LEDC PWM init (ESP32 Core 3.x API)
|
||||||
wifiManager.setHostname("ESP32-PWM-OSC");
|
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
|
||||||
if (!wifiManager.autoConnect("ESP32-PWM-OSC")) {
|
bool ok = ledcAttach(pwmPins[ch], pwmFrequency, pwmResolution);
|
||||||
Serial.println("Failed to connect, restarting...");
|
if (!ok) {
|
||||||
delay(3000);
|
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();
|
ESP.restart();
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.print("Connected. IP: ");
|
Serial.println("WiFi connected!");
|
||||||
|
Serial.print("IP: ");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
|
|
||||||
Udp.begin(oscPort);
|
// UDP init
|
||||||
Serial.print("Listening for OSC on port ");
|
udp.begin(listenPort);
|
||||||
Serial.println(oscPort);
|
Serial.print("Listening on UDP port ");
|
||||||
|
Serial.println(listenPort);
|
||||||
|
|
||||||
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
|
lastPacketTime = millis();
|
||||||
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.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------
|
// -------------------------------
|
||||||
// Loop
|
// Loop
|
||||||
// -------------------------------
|
// -------------------------------
|
||||||
|
|
||||||
void 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();
|
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
|
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
|
||||||
enqueueOscPacket();
|
float newDuty = slewStartDuty[ch] + (targetDuty[ch] - slewStartDuty[ch]) * progress;
|
||||||
|
currentDuty[ch] = newDuty;
|
||||||
|
|
||||||
// Process queued OSC packets
|
float calibratedDuty = applyCalibration(ch, newDuty);
|
||||||
processOscQueue();
|
int duty = (int)((calibratedDuty / 100.0f) * ((1 << pwmResolution) - 1));
|
||||||
|
|
||||||
// Watchdog + sweep mode handling
|
ledcWrite(pwmPins[ch], duty);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CONSTANT-RATE SLEWING (all channels)
|
// -------- Watchdog fade-to-zero (UDP-based) --------
|
||||||
if (now - lastSlewUpdate >= slewPerPercent) {
|
if (millis() - lastPacketTime > watchdogTimeout) {
|
||||||
lastSlewUpdate = now;
|
|
||||||
|
const unsigned long fadeInterval = 1;
|
||||||
|
|
||||||
|
if (millis() - lastFadeTime >= fadeInterval) {
|
||||||
|
lastFadeTime = millis();
|
||||||
|
|
||||||
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
|
for (int ch = 0; ch < NUM_CHANNELS; ch++) {
|
||||||
|
|
||||||
if (currentDuty[ch] < targetDuty[ch]) {
|
if (currentDuty[ch] > 0.0f) {
|
||||||
currentDuty[ch] += 1.0f;
|
|
||||||
if (currentDuty[ch] > targetDuty[ch])
|
const float fadeFactor = 0.999f;
|
||||||
currentDuty[ch] = targetDuty[ch];
|
currentDuty[ch] *= fadeFactor;
|
||||||
}
|
|
||||||
else if (currentDuty[ch] > targetDuty[ch]) {
|
if (currentDuty[ch] < 0.01f)
|
||||||
currentDuty[ch] -= 1.0f;
|
currentDuty[ch] = 0.0f;
|
||||||
if (currentDuty[ch] < targetDuty[ch])
|
|
||||||
currentDuty[ch] = targetDuty[ch];
|
|
||||||
}
|
|
||||||
|
|
||||||
float calibratedDuty = applyCalibration(ch, currentDuty[ch]);
|
float calibratedDuty = applyCalibration(ch, currentDuty[ch]);
|
||||||
uint32_t pwmValue = (uint32_t)((calibratedDuty / 100.0f) * pwmMax);
|
int duty = (int)((calibratedDuty / 100.0f) * ((1 << pwmResolution) - 1));
|
||||||
ledcWrite(pwmPins[ch], pwmValue);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
delay(5);
|
ledcWrite(pwmPins[ch], duty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 { }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace analog_system_monitor
|
|
||||||
{
|
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
[STAThread]
|
[STAThread]
|
||||||
@@ -12,4 +10,3 @@ namespace analog_system_monitor
|
|||||||
Application.Run(new TrayApp());
|
Application.Run(new TrayApp());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,338 +1,222 @@
|
|||||||
|
#nullable enable
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Net.Sockets;
|
using System.Globalization;
|
||||||
using System.Text;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using LibreHardwareMonitor.Hardware;
|
using LibreHardwareMonitor.Hardware;
|
||||||
|
|
||||||
public class Telemetry
|
public class Telemetry : IDisposable
|
||||||
{
|
{
|
||||||
private Config config;
|
private const int UpdateRateDefaultMs = 1000;
|
||||||
private string oscIp = "127.0.0.1";
|
public int UpdateRateMs => UpdateRateDefaultMs;
|
||||||
private int oscPort = 9000;
|
|
||||||
|
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[] cpuLoadSensors = Array.Empty<ISensor>();
|
||||||
private ISensor? cpuTempSensor;
|
private ISensor? cpuTempSensor;
|
||||||
private ISensor? gpuVramUsedSensor;
|
|
||||||
private ISensor? gpuVramTotalSensor;
|
|
||||||
private ISensor? gpu3DLoadSensor;
|
private ISensor? gpu3DLoadSensor;
|
||||||
private ISensor? gpuTempSensor;
|
private ISensor? gpuTempSensor;
|
||||||
|
private ISensor? gpuVramUsedSensor;
|
||||||
|
private ISensor? gpuVramTotalSensor;
|
||||||
|
|
||||||
private Computer computer = new Computer();
|
private ISensor? memUsedSensor;
|
||||||
private UdpClient udp = new UdpClient();
|
private ISensor? memAvailSensor;
|
||||||
|
|
||||||
// ---------------- INITIALIZATION ----------------
|
private static readonly CultureInfo CI = CultureInfo.InvariantCulture;
|
||||||
|
|
||||||
public void Initialize()
|
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;
|
|
||||||
computer.IsCpuEnabled = true;
|
computer.IsCpuEnabled = true;
|
||||||
computer.IsGpuEnabled = true;
|
computer.IsGpuEnabled = true;
|
||||||
|
computer.IsMemoryEnabled = true;
|
||||||
|
|
||||||
computer.Open();
|
computer.Open();
|
||||||
|
CacheHardwareAndSensors();
|
||||||
DetectSensors();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int UpdateRateMs => config.UpdateRateMs;
|
private void CacheHardwareAndSensors()
|
||||||
|
|
||||||
private void ParseArgs(string[] args)
|
|
||||||
{
|
{
|
||||||
foreach (var arg in args)
|
foreach (var hw in computer.Hardware)
|
||||||
{
|
{
|
||||||
if (arg.StartsWith("--ip="))
|
hw.Update();
|
||||||
oscIp = arg.Substring("--ip=".Length);
|
|
||||||
|
|
||||||
if (arg.StartsWith("--port=") &&
|
switch (hw.HardwareType)
|
||||||
int.TryParse(arg.Substring("--port=".Length), out int p))
|
{
|
||||||
oscPort = p;
|
case HardwareType.Cpu:
|
||||||
|
cpuHw = hw;
|
||||||
|
CacheCpuSensors(hw);
|
||||||
|
break;
|
||||||
|
|
||||||
if (arg.StartsWith("--rate=") &&
|
case HardwareType.GpuNvidia:
|
||||||
int.TryParse(arg.Substring("--rate=".Length), out int r))
|
case HardwareType.GpuAmd:
|
||||||
config.UpdateRateMs = r;
|
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>();
|
||||||
|
|
||||||
// ---------------- MAIN UPDATE LOOP ----------------
|
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()
|
public void UpdateAndSend()
|
||||||
{
|
{
|
||||||
int memPercent = GetMemoryUsagePercent();
|
cpuHw?.Update();
|
||||||
int cpuPercent = GetCpuLoadPercent();
|
gpuHw?.Update();
|
||||||
int vramPercent = GetGpuVramPercent();
|
memHw?.Update();
|
||||||
int gpu3DPercent = GetGpu3DLoad();
|
|
||||||
int cpuTempPercent = GetCpuTemperaturePercent();
|
|
||||||
int gpuTempPercent = GetGpuTemperaturePercent();
|
|
||||||
|
|
||||||
SendOscBundle(
|
float cpu = GetCpuLoadPercent();
|
||||||
cpuPercent / 100f,
|
float cpuTemp = GetCpuTemperaturePercent();
|
||||||
cpuTempPercent / 100f,
|
float mem = GetMemoryUsagePercent();
|
||||||
memPercent / 100f,
|
float gpu3d = GetGpu3DLoad();
|
||||||
gpu3DPercent / 100f,
|
float gpuTemp = GetGpuTemperaturePercent();
|
||||||
gpuTempPercent / 100f,
|
float vram = GetGpuVramPercent();
|
||||||
vramPercent / 100f
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------- SENSOR DETECTION ----------------
|
// Prepare 8 floats (future‑proof)
|
||||||
|
float[] packet =
|
||||||
private void DetectSensors()
|
|
||||||
{
|
{
|
||||||
var cpuLoadList = new List<ISensor>();
|
cpu,
|
||||||
|
cpuTemp,
|
||||||
|
mem,
|
||||||
|
gpu3d,
|
||||||
|
gpuTemp,
|
||||||
|
vram,
|
||||||
|
0f, // reserved for future use
|
||||||
|
0f // reserved for future use
|
||||||
|
};
|
||||||
|
|
||||||
ISensor? bestCpuTemp = null;
|
udp.SendFloats(packet);
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hw.HardwareType == HardwareType.GpuNvidia ||
|
private float GetCpuLoadPercent()
|
||||||
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()
|
|
||||||
{
|
{
|
||||||
if (cpuLoadSensors.Length == 0) return 0;
|
if (cpuLoadSensors.Length == 0) return 0;
|
||||||
|
|
||||||
float total = 0;
|
float total = 0;
|
||||||
int count = 0;
|
int count = 0;
|
||||||
|
|
||||||
foreach (var sensor in cpuLoadSensors)
|
foreach (var s in cpuLoadSensors)
|
||||||
{
|
{
|
||||||
sensor.Hardware.Update();
|
total += s.Value ?? 0;
|
||||||
total += sensor.Value ?? 0;
|
|
||||||
count++;
|
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)
|
float t = cpuTempSensor?.Value ?? 0;
|
||||||
return 0;
|
return Math.Clamp(t, 0, 100);
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int GetGpu3DLoad()
|
private float GetGpu3DLoad()
|
||||||
{
|
{
|
||||||
if (gpu3DLoadSensor == null) return 0;
|
return gpu3DLoadSensor?.Value ?? 0;
|
||||||
|
|
||||||
gpu3DLoadSensor.Hardware.Update();
|
|
||||||
return (int)Math.Round(gpu3DLoadSensor.Value ?? 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int GetCpuTemperaturePercent()
|
private float GetGpuTemperaturePercent()
|
||||||
{
|
{
|
||||||
if (cpuTempSensor == null) return 0;
|
float t = gpuTempSensor?.Value ?? 0;
|
||||||
|
return Math.Clamp(t, 0, 100);
|
||||||
cpuTempSensor.Hardware.Update();
|
|
||||||
float temp = cpuTempSensor.Value ?? 0;
|
|
||||||
|
|
||||||
return (int)Math.Round(Math.Clamp(temp, 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();
|
if (total <= 0) return 0;
|
||||||
float temp = gpuTempSensor.Value ?? 0;
|
return (used / total) * 100f;
|
||||||
|
|
||||||
return (int)Math.Round(Math.Clamp(temp, 0, 100));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------- OSC ----------------
|
private float GetMemoryUsagePercent()
|
||||||
|
|
||||||
private void SendOscBundle(
|
|
||||||
float cpu, float cpuTemp, float mem,
|
|
||||||
float gpu3d, float gpuTemp, float vram)
|
|
||||||
{
|
{
|
||||||
var messages = new List<byte[]>();
|
float used = memUsedSensor?.Value ?? 0;
|
||||||
|
float avail = memAvailSensor?.Value ?? 0;
|
||||||
|
|
||||||
messages.Add(BuildOscFloatMessage("/cpu", cpu));
|
float total = used + avail;
|
||||||
messages.Add(BuildOscFloatMessage("/cputemp", cpuTemp));
|
if (total <= 0) return 0;
|
||||||
messages.Add(BuildOscFloatMessage("/memory", mem));
|
|
||||||
messages.Add(BuildOscFloatMessage("/gpu3d", gpu3d));
|
|
||||||
messages.Add(BuildOscFloatMessage("/gputemp", gpuTemp));
|
|
||||||
messages.Add(BuildOscFloatMessage("/vram", vram));
|
|
||||||
|
|
||||||
byte[] bundle = BuildOscBundle(messages);
|
return (used / total) * 100f;
|
||||||
udp.Send(bundle, bundle.Length, oscIp, oscPort);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private byte[] BuildOscBundle(List<byte[]> messages)
|
public void Dispose()
|
||||||
{
|
{
|
||||||
List<byte[]> parts = new List<byte[]>();
|
udp.Dispose();
|
||||||
|
computer.Close();
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,86 +1,40 @@
|
|||||||
|
#nullable enable
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
using System.Reflection;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace analog_system_monitor
|
|
||||||
{
|
|
||||||
public class TrayApp : ApplicationContext
|
public class TrayApp : ApplicationContext
|
||||||
{
|
{
|
||||||
private NotifyIcon trayIcon;
|
private NotifyIcon trayIcon;
|
||||||
private Thread workerThread;
|
private Telemetry telemetry;
|
||||||
private bool running = true;
|
|
||||||
|
|
||||||
public TrayApp()
|
public TrayApp()
|
||||||
{
|
{
|
||||||
trayIcon = new NotifyIcon()
|
telemetry = new Telemetry();
|
||||||
{
|
|
||||||
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.Initialize();
|
telemetry.Initialize();
|
||||||
|
|
||||||
while (running)
|
trayIcon = new NotifyIcon()
|
||||||
{
|
{
|
||||||
telemetry.UpdateAndSend();
|
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath),
|
||||||
Thread.Sleep(telemetry.UpdateRateMs);
|
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;
|
telemetry.Dispose();
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
workerThread?.Join(500);
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
|
|
||||||
trayIcon.Visible = false;
|
trayIcon.Visible = false;
|
||||||
trayIcon.Dispose();
|
|
||||||
|
|
||||||
Application.Exit();
|
Application.Exit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|||||||
64
analog_system_monitor_dotnet/UdpSender.cs
Normal file
64
analog_system_monitor_dotnet/UdpSender.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,14 +4,23 @@
|
|||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<TargetFramework>net10.0-windows</TargetFramework>
|
<TargetFramework>net10.0-windows</TargetFramework>
|
||||||
<UseWindowsForms>true</UseWindowsForms>
|
<UseWindowsForms>true</UseWindowsForms>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
<!-- Single-file EXE -->
|
||||||
<PublishSingleFile>true</PublishSingleFile>
|
<PublishSingleFile>true</PublishSingleFile>
|
||||||
<SelfContained>true</SelfContained>
|
<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>
|
<DebugSymbols>false</DebugSymbols>
|
||||||
|
|
||||||
<ApplicationIcon>telemetry_icon.ico</ApplicationIcon>
|
<ApplicationIcon>telemetry_icon.ico</ApplicationIcon>
|
||||||
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
35
analog_system_monitor_dotnet/app.manifest
Normal file
35
analog_system_monitor_dotnet/app.manifest
Normal 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>
|
||||||
53
analog_system_monitor_dotnet/build-release.ps1
Normal file
53
analog_system_monitor_dotnet/build-release.ps1
Normal 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
|
||||||
@@ -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 "============================================"
|
|
||||||
Reference in New Issue
Block a user