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; namespace Assets.Scripts.UI.Prefab.Device { public class DeviceCache { private static Dictionary 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(); 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>(str); } else { dict = new Dictionary(); } } public static void Add(AbstractAntDevice antDevice) { Debug.Log("添加设备" + antDevice.DeviceNumber); //new System.Collections.Concurrent.ConcurrentDictionary().AddOrUpdate //dict.AddOrUpdate(antDevice.Sensor.ToString(), antDevice.DeviceNumber, (key, oldValue)=> { // Debug.Log("真正添加" + dict.Count); // Write(); // return antDevice.DeviceNumber; //}); dict[antDevice.Sensor.ToString()] = antDevice.DeviceNumber; Write(); } public static bool Exist(AbstractAntDevice antDevice) { ushort a; if(dict.TryGetValue(antDevice.Sensor.ToString(), out a)) { return a == antDevice.DeviceNumber; } return false; } public static void Remove(AbstractAntDevice antDevice) { if(dict == null) { return; } if (dict.ContainsKey(antDevice.Sensor.ToString())) { if(dict[antDevice.Sensor.ToString()] == antDevice.DeviceNumber) { 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)); } } }