Files
AltImuAnalyze.Unity/Assets/Accelerometer.cs
T
2025-05-13 00:32:28 +03:00

123 lines
3.5 KiB
C#

using Antilatency.DeviceNetwork;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine;
public class Accelerometer : MonoBehaviour
{
public static System.Guid TaskID {
get {
byte[] data = new byte[] { 48, 125, 192, 166, 207, 227, 237, 68, 185, 150, 95, 150, 153, 131, 146, 226 };
var handle = GCHandle.Alloc(data, GCHandleType.Pinned);
System.Guid result = (System.Guid)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(System.Guid));
handle.Free();
return result;
}
}
public event Action<Accelerometer, Vector3> OnNewSample;
public event Action<Accelerometer> OnStarted;
public event Action<Accelerometer> OnStopped;
Antilatency.DeviceNetwork.INetwork _network;
ISynchronousConnection _connection;
uint _updateId = 0;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
using var lib = Antilatency.DeviceNetwork.Library.load();
using var filter = lib.createFilter();
filter.addUsbDevice(Antilatency.DeviceNetwork.Constants.AllUsbDevices);
_network = lib.createNetwork(filter);
Debug.Log("Network created");
}
void OnTaskStarted() {
if(OnStarted != null) {
OnStarted.Invoke(this);
}
}
void OnTaskFinished() {
if (OnStopped != null) {
OnStopped.Invoke(this);
}
}
void Reconnect() {
if (_connection != null) {
return;
}
var updateId = _network.getUpdateId();
if (updateId != _updateId) {
_updateId = updateId;
var nodes = _network.getNodes();
foreach (var node in nodes) {
if(_network.nodeIsTaskSupported(node, TaskID)){
_connection = _network.nodeStartTask2(node, TaskID);
OnTaskStarted();
}
}
}
}
void OnAccelerometer(Vector3 value) {
if(OnNewSample != null) {
OnNewSample.Invoke(this, value);
}
}
void OnAccelerometerPacket(Antilatency.DeviceNetwork.Interop.Packet packet, int gRange) {
float scale = (float)gRange / 0x8000;
var sample = Marshal.PtrToStructure<AntilatencyMath.short3>(packet.data);
OnAccelerometer(new Vector3(sample.x * scale, sample.y * scale, sample.z * scale));
}
// Update is called once per frame
void Update()
{
Reconnect();
if (_connection == null) {
return;
}
Antilatency.InterfaceContract.Bool taskFinished = false;
var packets = _connection.getAvailablePackets(out taskFinished);
if (taskFinished) {
Antilatency.Utils.SafeDispose(ref _connection);
OnTaskFinished();
return;
}
foreach (var packet in packets) {
if (packet.id == 3) {
OnAccelerometerPacket(packet, 2);
} else if (packet.id == 4) {
OnAccelerometerPacket(packet, 4);
} else if (packet.id == 5) {
OnAccelerometerPacket(packet, 8);
} else if (packet.id == 6) {
OnAccelerometerPacket(packet, 16);
}
}
}
private void OnDestroy() {
Antilatency.Utils.SafeDispose(ref _connection);
Antilatency.Utils.SafeDispose(ref _network);
}
}