This commit is contained in:
CortexCore
2024-05-31 01:23:15 +08:00
parent c798b224be
commit 299082fe27
164 changed files with 3604 additions and 2018 deletions

View File

@@ -10,22 +10,20 @@ namespace BITKit.Sensors
{
public class SensorQueue : MonoBehaviour
{
internal static readonly Dictionary<int,ISensor> Sensors=new();
internal static readonly ConcurrentDictionary<int,ISensor> Sensors=new();
internal static readonly ConcurrentDictionary<int, float> LastDetectedTime = new();
private static bool IsDirty;
[SerializeField,ReadOnly] private int _position;
private static int[] _keys;
public static void Register(int id,ISensor sensor)
{
Sensors.Add(id,sensor);
Sensors.TryAdd(id,sensor);
MarkDirty();
}
public static void UnRegister(int id)
{
Sensors.Remove(id);
Sensors.TryRemove(id);
MarkDirty();
}
public static void MarkDirty()
@@ -33,7 +31,6 @@ namespace BITKit.Sensors
IsDirty = true;
}
[SerializeField] private MonoBehaviour[] sensors;
[SerializeReference,SubclassSelector] private ITicker ticker;
private bool _isBusy;
@@ -51,44 +48,46 @@ namespace BITKit.Sensors
{
if (_isBusy) return;
if (SensorGlobalSettings.Enabled is false) return;
_isBusy = true;
if(IsDirty)
try
{
_position = 0;
_keys = Sensors.Where(IsEnabled).Select(x=>x.Key).ToArray();
IsDirty = false;
sensors = Sensors.Values.Where(IsEnabled).OfType<MonoBehaviour>().ToArray();
}
if (Sensors.Count is 0)
{
_isBusy = false;
return;
}
var current = Sensors.ElementAt(_position++).Value;
var currentUpdateTime = LastDetectedTime.GetOrAdd(current.Id,Time.time);
await current.Execute(Time.time-currentUpdateTime);
float UpdateValueFactory(int key, float old) => Time.time;
LastDetectedTime.AddOrUpdate(current.Id,Time.time,UpdateValueFactory);
if (destroyCancellationToken.IsCancellationRequested) {
_isBusy = false;
return;
}
_isBusy = true;
if(IsDirty)
{
_position = 0;
IsDirty = false;
}
_position %= Sensors.Count;
if (Sensors.Count is 0)
{
_isBusy = false;
return;
}
var current = Sensors.ElementAt(_position++).Value;
if (current.AutoUpdate)
{
var currentUpdateTime = LastDetectedTime.GetOrAdd(current.Id,Time.time);
await current.Execute(Time.time-currentUpdateTime);
LastDetectedTime.AddOrUpdate(current.Id,Time.time,UpdateValueFactory);
if (destroyCancellationToken.IsCancellationRequested) {
_isBusy = false;
return;
}
}
_position %= Sensors.Count;
float UpdateValueFactory(int key, float old) => Time.time;
}
catch (Exception e)
{
BIT4Log.LogException(e);
}
_isBusy = false;
}
private bool IsEnabled(ISensor sensor)
{
return sensor.AutoUpdate;
}
private bool IsEnabled(KeyValuePair<int,ISensor> pair)
{
return pair.Value.AutoUpdate;
}
}
}