2021-06-08 10:30:26 +08:00

90 lines
2.7 KiB
C#

using Assets.Scripts.Devices.Ant;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using UnityEngine;
using Newtonsoft.Json;
using Assets.Scripts.Devices;
namespace Assets.Scripts.UI.Prefab.Device
{
public class DeviceCache
{
private static Dictionary<string, string> dict = null;
private static string _dataPath;
public static void Init(string dataPath) {
if(dict != null)
{
return;
}
_dataPath = dataPath;
if(!System.IO.File.Exists(_dataPath + "/Devices.txt"))
{
dict = new Dictionary<string, string>();
return;
}
//var str = PlayerPrefs.GetString("DeviceCache", "");
var str = System.IO.File.ReadAllText(_dataPath + "/Devices.txt", Encoding.UTF8);
if (!string.IsNullOrWhiteSpace(str)) {
dict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
}
else {
dict = new Dictionary<string, string>();
}
}
public static void Add(AbstractDevice antDevice)
{
//Debug.Log("添加设备" + antDevice.DeviceNumber);
//new System.Collections.Concurrent.ConcurrentDictionary<string, string>().AddOrUpdate
//dict.AddOrUpdate(antDevice.Sensor.ToString(), antDevice.DeviceNumber, (key, oldValue)=> {
// Debug.Log("真正添加" + dict.Count);
// Write();
// return antDevice.DeviceNumber;
//});
dict[antDevice.Sensor.ToString()] = antDevice.Id;
Write();
}
public static bool Exist(AbstractDevice antDevice)
{
string a;
if(dict.TryGetValue(antDevice.Sensor.ToString(), out a))
{
return a == antDevice.Id;
}
return false;
}
public static void Remove(AbstractDevice antDevice)
{
if(dict == null)
{
return;
}
if (dict.ContainsKey(antDevice.Sensor.ToString()))
{
if(dict[antDevice.Sensor.ToString()] == antDevice.Id)
{
dict.Remove(antDevice.Sensor.ToString());
Write();
}
}
}
private static void Write()
{
//PlayerPrefs.SetString("DeviceCache", JsonConvert.SerializeObject(dict));
System.IO.File.WriteAllText(_dataPath + "/Devices.txt", JsonConvert.SerializeObject(dict));
}
}
}