SoraV2Utils/SoraV2Utils_Agent/ServiceIPC.cs

95 lines
2.5 KiB
C#

using EasyPipes;
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace SoraV2Utils_Agent
{
public struct DeviceStatus
{
public byte Battery;
public byte Charging;
public byte FullCharge;
public byte Online;
}
public interface IMouseData
{
byte[] GetDeviceStatus();
double GetBatteryRuntime();
void Exit();
}
public class ServiceIPC
{
public static ServiceIPC Instance;
public static DeviceStatus DeviceStatus;
public static double BatteryRuntime = 0;
public ServiceIPC()
{
ThreadPool.QueueUserWorkItem(state =>
{
while (true)
{
GetDeviceDataFromService();
Thread.Sleep(5000); // Periodically fetch data every 5 seconds
}
});
Instance = this;
}
public static void GetDeviceDataFromService()
{
var client = new Client("SoraV2UtilsDeviceData");
var service = client.GetServiceProxy<IMouseData>();
try
{
// Allocate memory and copy device status data
int size = Marshal.SizeOf(typeof(DeviceStatus));
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
byte[] statusData = service.GetDeviceStatus();
Marshal.Copy(statusData, 0, ptr, size);
// Marshal data into DeviceStatus struct
DeviceStatus = (DeviceStatus)Marshal.PtrToStructure(ptr, typeof(DeviceStatus));
}
finally
{
// Clean up allocated memory
Marshal.FreeHGlobal(ptr);
}
BatteryRuntime = service.GetBatteryRuntime();
}
catch (Exception ex)
{
//TODO: Log or handle exceptions properly
Console.WriteLine($"Error fetching device data: {ex.Message}");
}
}
public void Exit()
{
// Stop the Service
try
{
var client = new Client("SoraV2UtilsDeviceData");
var service = client.GetServiceProxy<IMouseData>();
service.Exit();
}
catch (TimeoutException)
{
}
// Exit the application
System.Environment.Exit(1);
}
}
}