CompressMemory2.cs 12.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
//==============================================================
//  Copyright (C) 2020  Inc. All rights reserved.
//
//==============================================================
//  Create by 种道洋 at 2020/4/9 9:41:02.
//  Version 1.0
//  种道洋
//==============================================================

using Cdy.Tag;
using DBRuntime.His;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Threading;

namespace Cdy.Tag
{
    /// <summary>
    /// 
    /// </summary>
    public class CompressMemory2: MarshalMemoryBlock
    {

        #region ... Variables  ...

        private DateTime mCurrentTime;
        private IHisEngine2 mHisTagService;
        private Dictionary<int, CompressUnitbase2> mCompressCach = new Dictionary<int, CompressUnitbase2>();
        private Dictionary<int, long> dtmp = new Dictionary<int, long>();

        private List<int> mTagIds=new List<int>();

        private bool mIsRunning=false;

38
        private Queue<ManualHisDataMemoryBlock> mMemoryCach = new Queue<ManualHisDataMemoryBlock>();
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
       
        #endregion ...Variables...

        #region ... Events     ...

        #endregion ...Events...

        #region ... Constructor...

        /// <summary>
        /// 
        /// </summary>
        public CompressMemory2():base()
        {
            mHisTagService = ServiceLocator.Locator.Resolve<IHisEngine2>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="size"></param>
        public CompressMemory2(long size):base(size)
        {

        }

        #endregion ...Constructor...

        #region ... Properties ...

        /// <summary>
        /// 
        /// </summary>
        public int  Id { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public static int TagCountPerMemory { get; set; }

       

        /// <summary>
        /// 
        /// </summary>
        public int HeadSize 
        {
            get
            {
                return 8 + TagCountPerMemory * 8;
            } 
        }

        ///// <summary>
        ///// 变量内存地址缓存
        ///// Tuple 每项的含义:起始地址,值地址偏移,质量地址偏移,数据大小
        ///// </summary>
        //public Dictionary<int, HisDataMemoryBlock> TagAddress
        //{
        //    get
        //    {
        //        return mTagAddress;
        //    }
        //    set
        //    {
        //        if (mTagAddress != value)
        //        {
        //            mTagAddress = value;
        //        }
        //    }
        //}

        /// <summary>
            /// 
            /// </summary>
        public DateTime CurrentTime
        {
            get
            {
                return mCurrentTime;
            }
            set
            {
                if (mCurrentTime != value)
                {
                    mCurrentTime = value;
                }
            }
        }

cdy816's avatar
cdy816 已提交
129 130 131 132 133
        /// <summary>
        /// 
        /// </summary>
        public DateTime EndTime { get; set; }

134 135 136 137 138

        #endregion ...Properties...

        #region ... Methods    ...

139 140 141 142 143
        /// <summary>
        /// 
        /// </summary>
        public void RequestManualToCompress()
        {
144
            lock (mMemoryCach)
145
            {
146 147 148 149 150 151
                mIsRunning = true;
                while (mMemoryCach.Count > 0)
                {
                    RequestManualToCompress(mMemoryCach.Dequeue());
                }
                mIsRunning = false;
152 153
            }
        }
154

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        public void AddRequestManualToCompress(ManualHisDataMemoryBlock data)
        {
            mMemoryCach.Enqueue(data);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        private void RequestManualToCompress(ManualHisDataMemoryBlock data)
        {
            int datasize = 0;
            var cdata = CompressMemory(data, out datasize);
            cdata.MakeMemoryBusy();
cdy816's avatar
cdy816 已提交
173
            ServiceLocator.Locator.Resolve<IDataSerialize2>().ManualRequestToSeriseFile(data.Id, data.Time,data.EndTime, cdata, datasize);
174
            data.MakeMemoryNoBusy();
175
            ManualHisDataMemoryBlockPool.Pool.Release(data);
176 177 178 179 180 181
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceM"></param>
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        public void Init(HisDataMemoryBlockCollection sourceM)
        {
            mTagIds.Clear();
            long lsize = 0;
            foreach (var vv in sourceM.TagAddress.Where(e => e.Key >= Id * TagCountPerMemory && e.Key < (Id + 1) * TagCountPerMemory))
            {
                mTagIds.Add(vv.Key);
                dtmp.Add(vv.Key, 0);
                var cpt = mHisTagService.GetHisTag(vv.Key).CompressType;
                if (!mCompressCach.ContainsKey(cpt))
                {
                    mCompressCach.Add(cpt, CompressUnitManager2.Manager.GetCompressQuick(cpt).Clone());
                }
                lsize += vv.Value.Length;
            }

            this.ReAlloc(HeadSize + (long)(lsize*1.2));
            this.Clear();
        }

        /// <summary>
        /// 
        /// </summary>
        public void ReInit(HisDataMemoryBlockCollection sourceM)
        {
            mTagIds.Clear();
            long lsize = 0;
            foreach (var vv in sourceM.TagAddress.Where(e => e.Key >= Id * TagCountPerMemory && e.Key < (Id + 1) * TagCountPerMemory))
            {
                mTagIds.Add(vv.Key);
                
                if (!dtmp.ContainsKey(vv.Key))
                    dtmp.Add(vv.Key, 0);

                var cpt = mHisTagService.GetHisTag(vv.Key).CompressType;
                if (!mCompressCach.ContainsKey(cpt))
                {
                    mCompressCach.Add(cpt, CompressUnitManager2.Manager.GetCompressQuick(cpt).Clone());
                }
                lsize += vv.Value.Length;
            }

            this.Resize(HeadSize + lsize);
        }

        /// <summary>
        /// 执行压缩
        /// </summary>
        public void Compress(HisDataMemoryBlockCollection source)
        {
232
            lock (mMemoryCach)
233
            {
234 235 236 237 238 239 240 241 242 243 244
                /*
                 内存结构:Head+数据指针区域+数据区
                 Head:数据区大小(4)+变量数量(4)
                 数据区指针:[ID(4) + address(4)]
                 数据区:[data block]
                 */
                mIsRunning = true;
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
245

246 247 248 249
                    //CheckTagAddress(source);
                    long datasize = 0;
                    int headOffset = 4 + 4;
                    long Offset = headOffset + mTagIds.Count * 8;
250

251
                    this.MakeMemoryBusy();
252

253
                    long ltmp1 = sw.ElapsedMilliseconds;
254

255 256
                    //更新数据区域
                    foreach (var vv in mTagIds)
257
                    {
258 259 260 261 262 263 264 265 266 267 268 269 270
                        var val = source.TagAddress[vv];
                        if (val != null)
                        {
                            var size = CompressBlockMemory(val, Offset, val.QualityAddress, val.Length, vv);
                            if (dtmp.ContainsKey(vv))
                                dtmp[vv] = Offset;
                            Offset += size;
                            datasize += size;
                        }
                        else
                        {
                            dtmp[vv] = 0;
                        }
271
                    }
272 273 274 275 276 277 278 279 280 281

                    //更新指针区域
                    this.WriteInt(0, (int)datasize);//写入整体数据大小
                    this.Write((int)mTagIds.Count); //写入变量个数

                    long ltmp2 = sw.ElapsedMilliseconds;

                    //写入变量、数据区对应的索引
                    int count = 0;
                    foreach (var vv in dtmp)
282
                    {
283 284 285
                        this.WriteInt(headOffset + count, (int)vv.Key);
                        this.WriteInt(headOffset + count + 4, (int)vv.Value);
                        count += 8;
286
                    }
287

288
                    long ltmp3 = sw.ElapsedMilliseconds;
289

cdy816's avatar
cdy816 已提交
290
                    ServiceLocator.Locator.Resolve<IDataSerialize2>().RequestToSeriseFile(this);
291 292
                    sw.Stop();
                    LoggerService.Service.Info("CompressEnginer", Id + "压缩完成 耗时:" + sw.ElapsedMilliseconds + " ltmp1:" + ltmp1 + " ltmp2:" + (ltmp2 - ltmp1) + " ltmp3:" + (ltmp3 - ltmp2) + " CPU Id:" + ThreadHelper.GetCurrentProcessorNumber(), ConsoleColor.Blue);
293

294 295
                }
                catch (Exception ex)
296
                {
297
                    LoggerService.Service.Erro("CompressEnginer", ex.StackTrace + "  " + ex.Message);
298
                }
299
                mIsRunning = false;
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mSourceMemory"></param>
        /// <param name="addr"></param>
        /// <param name="targetPosition"></param>
        /// <param name="len"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private long CompressBlockMemory(HisDataMemoryBlock mSourceMemory, long targetPosition,long qulityOffset, long len, int id)
        {
            //var qulityoffset = mSourceMemory.ReadInt(addr);
            // var id = mSourceMemory.ReadInt(addr + 4);

            var histag = mHisTagService.GetHisTag(id);
            
            if (histag == null) return 0;

            var qulityoffset = qulityOffset;

            var comtype = histag.CompressType;//压缩类型

          //  this.CheckAndResize(targetPosition + len);

            //写入压缩类型
            this.WriteByte(targetPosition + 4, (byte)comtype);

            var tp = mCompressCach[comtype];
            if (tp != null)
            {
                tp.QulityOffset = (int)qulityoffset;
                tp.TagType = histag.TagType;
                tp.RecordType = histag.Type;
                tp.StartTime = mCurrentTime;
                tp.Parameters = histag.Parameters;
                tp.Precision = histag.Precision;
339
                tp.TimeTick = 100;
340 341 342 343 344 345 346 347 348 349
                var size = tp.Compress(mSourceMemory, 0, this, targetPosition + 5, len) + 1;
                this.WriteInt(targetPosition, (int)size);
                //this.Dump();
            
                return size + 5;
            }
            
            return 0;
        }

350 351 352 353 354 355 356
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private MarshalMemoryBlock CompressMemory(ManualHisDataMemoryBlock data,out int datasize)
        {
357
            MarshalMemoryBlock block = MarshalMemoryBlockPool.Pool.Get(data.Length * 2);
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            var histag = mHisTagService.GetHisTag(data.Id);
            if (histag == null)
            {
                datasize = 0;
                return null;
            }

            var qulityoffset = data.QualityAddress;
            var comtype = histag.CompressType;//压缩类型
            block.WriteByte(4, (byte)comtype);

            var tp = mCompressCach[comtype];
            if (tp != null)
            {
                tp.QulityOffset = (int)qulityoffset;
                tp.TagType = histag.TagType;
                tp.RecordType = histag.Type;
                tp.StartTime = data.Time;
                tp.Parameters = histag.Parameters;
                tp.Precision = histag.Precision;
378
                tp.TimeTick = data.TimeUnit;
379 380 381 382 383 384 385 386 387 388 389 390
                var size = tp.Compress(data, 0, block, 5, data.Length) + 1;
                block.WriteInt(0, (int)size);
                datasize = (int)(size + 5);
            }
            else
            {
                datasize = 0;
            }

            return block;
        }

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
            while (mIsRunning) Thread.Sleep(1);
            mHisTagService = null;
            mTagIds.Clear();
            mTagIds = null;
            //mIsDisposed = true;
            base.Dispose();
        }

        #endregion ...Methods...

        #region ... Interfaces ...

        #endregion ...Interfaces...
    }
}