JsonDist.cs 2.14 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
using FLY.OBJComponents.IService;
using FObjBase;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.OBJComponents.Server
{
    //1min 保存一次数据

    public class JsonDist : IJsonDistService
    {

21
        public event EventHandler ValueChanged;
潘栩锋's avatar
潘栩锋 committed
22 23 24 25 26 27 28 29 30

        List<DistCell> cells = new List<DistCell>();

        public JsonDist()
        {
            Load();
        }
        

31
        public void GetValue(string key, AsyncCBHandler asyncDelegate, object asyncContext)
潘栩锋's avatar
潘栩锋 committed
32 33
        {
            var distCell = cells.Find(c => c.Key == key);
34
            asyncDelegate(asyncContext, distCell);
潘栩锋's avatar
潘栩锋 committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        }

        public void SetValue(string key, JObject value)
        {
            var distCell = cells.Find(c => c.Key == key);
            if (distCell == null)
            {
                distCell = new DistCell()
                {
                    Key = key,
                    Time = DateTime.Now,
                    Value = value
                };
                cells.Add(distCell);
            }
            else {
                distCell.Time = DateTime.Now;
                distCell.Value = value;
            }
54
            ValueChanged?.Invoke(this, new JsonDistValueChangedEventArgs() { key = key });
潘栩锋's avatar
潘栩锋 committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
            Save();
        }

        string file_path = "dist.json";
        void Load() 
        {
            if (!File.Exists(file_path))
                return;

            string json = File.ReadAllText(file_path);
            try
            {
                var cells = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DistCell>>(json);
                this.cells = cells;
            }
            catch 
            {
                //异常
            }
            if (cells == null)
                cells = new List<DistCell>();
        }
        void Save() 
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(cells, Formatting.Indented);
            File.WriteAllText(file_path, json);
        }
    }

}