diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite index e04df336..82aad21c 100644 Binary files a/.vs/slnx.sqlite and b/.vs/slnx.sqlite differ diff --git a/Common/Cdy.Tag.Common/Common/DateTimeSpan.cs b/Common/Cdy.Tag.Common/Common/DateTimeSpan.cs index e21558f5..1082533c 100644 --- a/Common/Cdy.Tag.Common/Common/DateTimeSpan.cs +++ b/Common/Cdy.Tag.Common/Common/DateTimeSpan.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; using System.Text; +using System.Linq; namespace Cdy.Tag { @@ -80,6 +81,16 @@ public bool Contains(DateTime time) return time >= Start & time < End; } + /// + /// + /// + /// + /// + public IEnumerable GetCrossTime(IEnumerable times) + { + return times.Where(e => Contains(e)); + } + /// /// /// diff --git a/Common/Cdy.Tag/ITagQuery.cs b/Common/Cdy.Tag/ITagQuery.cs index d2f62c21..2d3d6f8c 100644 --- a/Common/Cdy.Tag/ITagQuery.cs +++ b/Common/Cdy.Tag/ITagQuery.cs @@ -38,6 +38,20 @@ public interface ITagManager /// Tagbase GetTagByName(string name); + /// + /// + /// + /// + /// + List GetTagsByGroup(string group); + + /// + /// + /// + /// + /// + IEnumerable GetTagsByName(IEnumerable tagnames); + /// /// /// @@ -63,6 +77,12 @@ public interface ITagManager /// IEnumerable ListAllTags(); + /// + /// + /// + /// + IEnumerable ListTagGroups(); + /// /// /// diff --git a/Common/Cdy.Tag/Interface/QueryValueCalType.cs b/Common/Cdy.Tag/Interface/QueryValueCalType.cs index a6bbe582..4a1a651c 100644 --- a/Common/Cdy.Tag/Interface/QueryValueCalType.cs +++ b/Common/Cdy.Tag/Interface/QueryValueCalType.cs @@ -37,7 +37,7 @@ public enum QueryValueMatchType } /// - /// + /// 数字型变量比较类型 /// public enum NumberStatisticsType { diff --git a/Common/Cdy.Tag/Real/RealDatabase.cs b/Common/Cdy.Tag/Real/RealDatabase.cs index 87f61cb2..93f39e31 100644 --- a/Common/Cdy.Tag/Real/RealDatabase.cs +++ b/Common/Cdy.Tag/Real/RealDatabase.cs @@ -187,6 +187,16 @@ public List GetTagsById(List ids) return re; } + /// + /// + /// + /// + /// + public IEnumerable GetTagsByName(IEnumerable tagnames) + { + return Tags.Values.Where(e => tagnames.Contains(e.FullName)); + } + /// /// /// @@ -452,33 +462,38 @@ public List GetTagsByGroup(string group) /// /// /// - public void RemoveByGroup(string group) + public List RemoveByGroup(string group) { + List re = new List(); if (this.Groups.ContainsKey(group)) { var vv = this.Groups[group].Tags; foreach (var vvv in vv) { Tags.Remove(vvv.Id); + re.Add(vvv.Id); } vv.Clear(); MinId = Tags.Keys.Count > 0 ? Tags.Keys.Min() : 0; IsDirty = true; } + return re; } /// /// /// /// - public void RemoveGroup(string group) + public List RemoveGroup(string group) { + List re = new List(); if (this.Groups.ContainsKey(group)) { var vv = this.Groups[group].Tags; foreach (var vvv in vv) { Tags.Remove(vvv.Id); + re.Add(vvv.Id); } //获取改组的所有子组 @@ -489,6 +504,7 @@ public void RemoveGroup(string group) foreach (var vvv in vvg.Tags) { Tags.Remove(vvv.Id); + re.Add(vvv.Id); } vvg.Tags.Clear(); } @@ -503,6 +519,7 @@ public void RemoveGroup(string group) IsDirty = true; } + return re; } /// @@ -764,6 +781,17 @@ public IEnumerable ListAllTags() return Tags.Values; } + /// + /// + /// + /// + public IEnumerable ListTagGroups() + { + var re = Groups.Keys.ToList(); + re.Add(""); + return re; + } + /// /// /// diff --git a/Common/Cdy.Tag/Real/Tagbase.cs b/Common/Cdy.Tag/Real/Tagbase.cs index ed6e2c6d..aa37f633 100644 --- a/Common/Cdy.Tag/Real/Tagbase.cs +++ b/Common/Cdy.Tag/Real/Tagbase.cs @@ -222,7 +222,7 @@ public abstract class FloatingTagBase : NumberTagBase /// /// 小数位数 /// - public byte Precision { get; set; } = 6; + public byte Precision { get; set; } = 2; #endregion ...Properties... #region ... Methods ... diff --git a/Common/Cdy.Tag/TagValue.cs b/Common/Cdy.Tag/TagValue.cs index 7c53b16d..4d566c96 100644 --- a/Common/Cdy.Tag/TagValue.cs +++ b/Common/Cdy.Tag/TagValue.cs @@ -89,7 +89,8 @@ public struct RealTagValue public object Value { get; set; } /// - /// + /// 值类型 + /// /// public byte ValueType { get; set; } @@ -139,7 +140,8 @@ public struct RealTagValue2 public object Value { get; set; } /// - /// + /// 值类型 + /// /// public byte ValueType { get; set; } diff --git a/Develop/DBDevelopService/Services/DevelopServerService.cs b/Develop/DBDevelopService/Services/DevelopServerService.cs index e5859eac..9a45e93f 100644 --- a/Develop/DBDevelopService/Services/DevelopServerService.cs +++ b/Develop/DBDevelopService/Services/DevelopServerService.cs @@ -995,7 +995,14 @@ public override Task RemoveTagGroup(RemoveGroupRequest request lock (db) { DbManager.Instance.CheckAndContinueLoadDatabase(db); - db.RealDatabase.RemoveGroup(request.Name); + var reids = db.RealDatabase.RemoveGroup(request.Name); + if (reids != null && reids.Count > 0) + { + foreach (var vv in reids) + { + db.HisDatabase.RemoveHisTag(vv); + } + } } return Task.FromResult(new BoolResultReplay() { Result = true }); } diff --git a/Develop/DbManager.Desktop/DBInStudio.Desktop.csproj b/Develop/DbManager.Desktop/DBInStudio.Desktop.csproj index fd67ad01..002efaf9 100644 --- a/Develop/DbManager.Desktop/DBInStudio.Desktop.csproj +++ b/Develop/DbManager.Desktop/DBInStudio.Desktop.csproj @@ -15,6 +15,13 @@ 3 + + + + + + + @@ -36,6 +43,7 @@ + @@ -62,6 +70,7 @@ + @@ -85,6 +94,7 @@ + diff --git a/Develop/DbManager.Desktop/Image/monitor.png b/Develop/DbManager.Desktop/Image/monitor.png new file mode 100644 index 00000000..5a7acdef Binary files /dev/null and b/Develop/DbManager.Desktop/Image/monitor.png differ diff --git a/Develop/DbManager.Desktop/MainWindow.xaml b/Develop/DbManager.Desktop/MainWindow.xaml index c95e8195..175b17ee 100644 --- a/Develop/DbManager.Desktop/MainWindow.xaml +++ b/Develop/DbManager.Desktop/MainWindow.xaml @@ -279,6 +279,20 @@ + + + + + + public class RealDataServerProcess : ServerProcessBase + { + + #region ... Variables ... + + + private Dictionary mCallBackRegistorIds = new Dictionary(); + + + private Queue> mChangedTags = new Queue>(10); + + + private Thread mScanThread; + + private ManualResetEvent resetEvent; + + private bool mIsClosed = false; + + private Dictionary buffers = new Dictionary(); + + private Dictionary mDataCounts = new Dictionary(); + + private ITagManager mTagManager; + + ///// + ///// + ///// + //public static HashSet Driver.AllowTagIds = new HashSet(); + + //private bool mIsBusy = false; + + private string mName; + + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + /// + /// + /// + public RealDataServerProcess() + { + mTagManager = Cdy.Tag.ServiceLocator.Locator.Resolve(); + } + + #endregion ...Constructor... + + #region ... Properties ... + + public override byte FunId => APIConst.RealValueFun; + + #endregion ...Properties... + + #region ... Methods ... + + /// + /// + /// + public void Init() + { + mName = "DirectAccessDriver" + Guid.NewGuid().ToString(); + ServiceLocator.Locator.Resolve().SubscribeValueChangedForProducter(mName, + new ProducterValueChangedNotifyProcesser.ValueChangedDelagete((vals) => + { + lock (mChangedTags) + { + foreach (var vv in vals) + { + mChangedTags.Enqueue(vv); + } + } + //mChangedTags.Enqueue(vals); + resetEvent.Set(); + }), () => { return new List() { -1 }; }); + } + + /// + /// + /// + /// + public override void CheckDataBusy(string client) + { + //if (mDatasCach.ContainsKey(client) && mDatasCach[client].Count > 100) + //{ + // Parent.AsyncCallback(client, ToByteBuffer(APIConst.AysncReturn, APIConst.RealServerBusy)); + // mIsBusy = true; + //} + //else if(mIsBusy) + //{ + // mIsBusy = false; + // Parent.AsyncCallback(client, ToByteBuffer(APIConst.AysncReturn, APIConst.RealServerNoBusy)); + //} + } + + /// + /// + /// + /// + /// + protected override void ProcessSingleData(string client, ByteBuffer data) + { + if(data==null || data.RefCount==0) + { + Debug.Print("invailed data buffer in RealDataServerProcess"); + return; + } + + //如果暂停,则不处理数据 + if(IsPause) + { + //to do 需要通知采集端,系统已经暂停 + //Parent.AsyncCallback(client, FunId, new byte[1], 0); + return; + } + + byte cmd = data.ReadByte(); + + if (cmd >= 100) + { + string user = data.ReadString(); + string pass = data.ReadString(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().LoginOnce(user,pass)) + { + try + { + switch (cmd) + { + case APIConst.SetTagValueAndQualityWithUserFun: + ProcessSetRealDataAndQualityWithTagNames(client, data); + break; + case APIConst.SetTagRealAndHisValueWithUserFun: + ProcessSetRealAndHistDataWithTagNames(client, data); + break; + } + } + catch (Exception ex) + { + LoggerService.Service.Warn("DirectAccessDriver", ex.Message); + } + } + } + else + { + long id = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(id)) + { + try + { + switch (cmd) + { + case APIConst.SetTagValueAndQualityFun: + ProcessSetRealDataAndQuality(client, data); + break; + case APIConst.SetTagRealAndHisValueFun: + ProcessSetRealAndHistData(client, data); + break; + case APIConst.RegistorTag: + ProcessValueChangeNotify(client, data); + break; + case APIConst.RemoveRegistorTag: + ProcessRemoveValueChangeNotify(client, data); + break; + case APIConst.ClearRegistorTag: + ProcessResetValueChangedNotify(client, data); + break; + } + } + catch (Exception ex) + { + LoggerService.Service.Warn("DirectAccessDriver", ex.Message); + } + } + else + { + Parent.AsyncCallback(client, FunId, new byte[1], 0); + } + } + base.ProcessSingleData(client, data); + } + + /// + /// + /// + /// + /// + private void ProcessSetRealDataAndQualityWithTagNames(string clientid, ByteBuffer block) + { + Parent?.AsyncCallback(clientid, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + var service = ServiceLocator.Locator.Resolve(); + var hisservice = ServiceLocator.Locator.Resolve(); + int count = block.ReadInt(); + byte qua; + lock (Driver.DriverdRecordTags) + { + for (int i = 0; i < count; i++) + { + var id = block.ReadString(); + byte typ = block.ReadByte(); + switch (typ) + { + case (byte)TagType.Bool: + var bvalue = block.ReadByte(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref bvalue, qua); + } + break; + case (byte)TagType.Byte: + var bbvalue = block.ReadByte(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref bbvalue, qua); + } + break; + case (byte)TagType.Short: + var svalue = block.ReadShort(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref svalue, qua); + } + break; + case (byte)TagType.UShort: + var uvalue = (ushort)block.ReadShort(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref uvalue, qua); + } + break; + case (byte)TagType.Int: + var ivalue = block.ReadInt(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref ivalue, qua); + } + break; + case (byte)TagType.UInt: + var uivalue = (uint)block.ReadInt(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref uivalue, qua); + } + break; + case (byte)TagType.Long: + var lvalue = block.ReadLong(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref lvalue, qua); + } + break; + case (byte)TagType.ULong: + var ulvalue = (ulong)block.ReadLong(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref ulvalue, qua); + } + break; + case (byte)TagType.Float: + var fvalue = block.ReadFloat(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref fvalue, qua); + } + break; + case (byte)TagType.Double: + var dvalue = block.ReadDouble(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref dvalue, qua); + } + break; + case (byte)TagType.String: + var ssvalue = block.ReadString(); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ssvalue, qua); + } + break; + case (byte)TagType.DateTime: + var tick = block.ReadLong(); + var ddvalue = new DateTime(tick); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref ddvalue, qua); + } + break; + case (byte)TagType.IntPoint: + var ipvalue = new IntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref ipvalue, qua); + } + break; + case (byte)TagType.UIntPoint: + var uipvalue = new UIntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref uipvalue, qua); + } + break; + case (byte)TagType.IntPoint3: + var ip3value = new IntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref ip3value, qua); + } + break; + case (byte)TagType.UIntPoint3: + var uip3value = new UIntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref uip3value, qua); + } + break; + case (byte)TagType.LongPoint: + var lpvalue = new LongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref lpvalue, qua); + } + break; + case (byte)TagType.ULongPoint: + var upvalue = new ULongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref upvalue, qua); + } + break; + case (byte)TagType.LongPoint3: + var lp3value = new LongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(Driver.AllowTagNames[id], ref lp3value, qua); + } + break; + case (byte)TagType.ULongPoint3: + var up3value = new ULongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagNames.ContainsKey(id)) + { + var vid = Driver.AllowTagNames[id]; + service.SetTagValue(vid, ref up3value, qua); + } + break; + } + } + } + service?.SubmiteNotifyChanged(); + + } + + /// + /// + /// + /// + /// + private void ProcessSetRealAndHistDataWithTagNames(string clientid, ByteBuffer block) + { + var service = ServiceLocator.Locator.Resolve(); + var hisservice = ServiceLocator.Locator.Resolve(); + Parent?.AsyncCallback(clientid, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + + int count = block.ReadInt(); + string id = ""; + byte typ; + byte qua = 0; + for (int i = 0; i < count; i++) + { + id = block.ReadString(); + typ = block.ReadByte(); + + switch (typ) + { + case (byte)TagType.Bool: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadByte(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval > 0, qua); + } + else + { + block.ReadByte(); + qua = block.ReadByte(); + } + break; + case (byte)TagType.Byte: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadByte(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadByte(); + qua = block.ReadByte(); + } + break; + case (byte)TagType.Short: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadShort(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadShort(); + qua = block.ReadByte(); + } + //value = block.ReadShort(); + break; + case (byte)TagType.UShort: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = (ushort)block.ReadShort(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadShort(); + qua = block.ReadByte(); + } + //value = (ushort)block.ReadShort(); + break; + case (byte)TagType.Int: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadInt(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadInt(); + qua = block.ReadByte(); + } + //value = block.ReadInt(); + break; + case (byte)TagType.UInt: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = (uint)block.ReadInt(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadInt(); + qua = block.ReadByte(); + } + //value = (uint)block.ReadInt(); + break; + case (byte)TagType.Long: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadLong(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + qua = block.ReadByte(); + } + //value = block.ReadLong(); + break; + case (byte)TagType.ULong: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = (ulong)block.ReadLong(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + qua = block.ReadByte(); + } + //value = (ulong)block.ReadLong(); + break; + case (byte)TagType.Float: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadFloat(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadFloat(); + qua = block.ReadByte(); + } + // value = block.ReadFloat(); + break; + case (byte)TagType.Double: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = block.ReadDouble(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadDouble(); + qua = block.ReadByte(); + } + // block.ReadDouble(); + break; + case (byte)TagType.String: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bs = block.ReadString(); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], bs, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bs, qua); + } + else + { + block.ReadString(); + qua = block.ReadByte(); + } + //value = block.ReadString(); + break; + case (byte)TagType.DateTime: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = DateTime.FromBinary(block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + qua = block.ReadByte(); + } + //value = DateTime.FromBinary(block.ReadLong()); + break; + case (byte)TagType.IntPoint: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new IntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new IntPointData(block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.UIntPoint: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new UIntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new UIntPointData(block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.IntPoint3: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new IntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new IntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.UIntPoint3: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new UIntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new UIntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.LongPoint: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new LongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new LongPointData(block.ReadLong(), block.ReadLong()); + break; + case (byte)TagType.ULongPoint: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new ULongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new ULongPointData(block.ReadLong(), block.ReadLong()); + break; + case (byte)TagType.LongPoint3: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new LongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new LongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + break; + case (byte)TagType.ULongPoint3: + if (Driver.AllowTagNames.ContainsKey(id)) + { + var bval = new ULongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(Driver.AllowTagNames[id], ref bval, qua); + hisservice.SetTagHisValue(Driver.AllowTagNames[id], bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new ULongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + break; + } + + } + service?.SubmiteNotifyChanged(); + + } + + + + /// + /// + /// + /// + /// + private void ProcessSetRealAndHistData(string clientid, ByteBuffer block) + { + var service = ServiceLocator.Locator.Resolve(); + var hisservice = ServiceLocator.Locator.Resolve(); + Parent?.AsyncCallback(clientid, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + + int count = block.ReadInt(); + int id = 0; + byte typ; + byte qua = 0; + for (int i = 0; i < count; i++) + { + id = block.ReadInt(); + typ = block.ReadByte(); + + switch (typ) + { + case (byte)TagType.Bool: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadByte(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + + hisservice.SetTagHisValue(id, bval > 0, qua); + } + else + { + block.ReadByte(); + qua = block.ReadByte(); + } + break; + case (byte)TagType.Byte: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadByte(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadByte(); + qua = block.ReadByte(); + } + break; + case (byte)TagType.Short: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadShort(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadShort(); + qua = block.ReadByte(); + } + //value = block.ReadShort(); + break; + case (byte)TagType.UShort: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = (ushort)block.ReadShort(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadShort(); + qua = block.ReadByte(); + } + //value = (ushort)block.ReadShort(); + break; + case (byte)TagType.Int: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadInt(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadInt(); + qua = block.ReadByte(); + } + //value = block.ReadInt(); + break; + case (byte)TagType.UInt: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = (uint)block.ReadInt(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadInt(); + qua = block.ReadByte(); + } + //value = (uint)block.ReadInt(); + break; + case (byte)TagType.Long: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadLong(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + qua = block.ReadByte(); + } + //value = block.ReadLong(); + break; + case (byte)TagType.ULong: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = (ulong)block.ReadLong(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + qua = block.ReadByte(); + } + //value = (ulong)block.ReadLong(); + break; + case (byte)TagType.Float: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadFloat(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadFloat(); + qua = block.ReadByte(); + } + // value = block.ReadFloat(); + break; + case (byte)TagType.Double: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = block.ReadDouble(); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadDouble(); + qua = block.ReadByte(); + } + // block.ReadDouble(); + break; + case (byte)TagType.String: + if (Driver.AllowTagIds.Contains(id)) + { + var bs = block.ReadString(); + qua = block.ReadByte(); + service.SetTagValue(id, bs, qua); + hisservice.SetTagHisValue(id, bs, qua); + } + else + { + block.ReadString(); + qua = block.ReadByte(); + } + //value = block.ReadString(); + break; + case (byte)TagType.DateTime: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = DateTime.FromBinary(block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + qua = block.ReadByte(); + } + //value = DateTime.FromBinary(block.ReadLong()); + break; + case (byte)TagType.IntPoint: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new IntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new IntPointData(block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.UIntPoint: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new UIntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new UIntPointData(block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.IntPoint3: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new IntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new IntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.UIntPoint3: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new UIntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadInt(); + block.ReadInt(); + block.ReadInt(); + qua = block.ReadByte(); + } + //value = new UIntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + break; + case (byte)TagType.LongPoint: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new LongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new LongPointData(block.ReadLong(), block.ReadLong()); + break; + case (byte)TagType.ULongPoint: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new ULongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new ULongPointData(block.ReadLong(), block.ReadLong()); + break; + case (byte)TagType.LongPoint3: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new LongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new LongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + break; + case (byte)TagType.ULongPoint3: + if (Driver.AllowTagIds.Contains(id)) + { + var bval = new ULongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + service.SetTagValue(id, ref bval, qua); + hisservice.SetTagHisValue(id, bval, qua); + } + else + { + block.ReadLong(); + block.ReadLong(); + block.ReadLong(); + qua = block.ReadByte(); + } + //value = new ULongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + break; + } + + } + service?.SubmiteNotifyChanged(); + + } + + /// + /// + /// + /// + /// + private void ProcessSetRealDataAndQuality(string clientid, ByteBuffer block) + { + Parent?.AsyncCallback(clientid, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + var service = ServiceLocator.Locator.Resolve(); + //var hisservice = ServiceLocator.Locator.Resolve(); + int count = block.ReadInt(); + byte qua; + for (int i = 0; i < count; i++) + { + var id = block.ReadInt(); + byte typ = block.ReadByte(); + switch (typ) + { + case (byte)TagType.Bool: + var bvalue = block.ReadByte(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref bvalue, qua); + break; + case (byte)TagType.Byte: + var bbvalue = block.ReadByte(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref bbvalue, qua); + break; + case (byte)TagType.Short: + var svalue = block.ReadShort(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref svalue, qua); + break; + case (byte)TagType.UShort: + var uvalue = (ushort)block.ReadShort(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref uvalue, qua); + + break; + case (byte)TagType.Int: + var ivalue = block.ReadInt(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref ivalue, qua); + + break; + case (byte)TagType.UInt: + var uivalue = (uint)block.ReadInt(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref uivalue, qua); + + break; + case (byte)TagType.Long: + var lvalue = block.ReadLong(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref lvalue, qua); + + break; + case (byte)TagType.ULong: + var ulvalue = (ulong)block.ReadLong(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref ulvalue, qua); + + break; + case (byte)TagType.Float: + var fvalue = block.ReadFloat(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref fvalue, qua); + break; + case (byte)TagType.Double: + var dvalue = block.ReadDouble(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref dvalue, qua); + + break; + case (byte)TagType.String: + var ssvalue = block.ReadString(); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ssvalue, qua); + break; + case (byte)TagType.DateTime: + var tick = block.ReadLong(); + var ddvalue = new DateTime(tick); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref ddvalue, qua); + + break; + case (byte)TagType.IntPoint: + var ipvalue = new IntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref ipvalue, qua); + + break; + case (byte)TagType.UIntPoint: + var uipvalue = new UIntPointData(block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref uipvalue, qua); + + break; + case (byte)TagType.IntPoint3: + var ip3value = new IntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref ip3value, qua); + + break; + case (byte)TagType.UIntPoint3: + var uip3value = new UIntPoint3Data(block.ReadInt(), block.ReadInt(), block.ReadInt()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref uip3value, qua); + break; + case (byte)TagType.LongPoint: + var lpvalue = new LongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref lpvalue, qua); + break; + case (byte)TagType.ULongPoint: + var upvalue = new ULongPointData(block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref upvalue, qua); + break; + case (byte)TagType.LongPoint3: + var lp3value = new LongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref lp3value, qua); + break; + case (byte)TagType.ULongPoint3: + var up3value = new ULongPoint3Data(block.ReadLong(), block.ReadLong(), block.ReadLong()); + qua = block.ReadByte(); + if (Driver.AllowTagIds.Contains(id)) + service.SetTagValue(id, ref up3value, qua); + break; + } + } + service?.SubmiteNotifyChanged(); + + } + + + /// + /// + /// + /// + /// + private void ProcessRemoveValueChangeNotify(string clientId, ByteBuffer block) + { + try + { + if (mCallBackRegistorIds.ContainsKey(clientId)) + { + var itmp = mCallBackRegistorIds[clientId]; + int minid = block.ReadInt(); + for (int i = 0; i < minid; i++) + { + var ival = block.ReadInt(); + itmp.ClearId(ival); + } + } + Parent?.AsyncCallback(clientId, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + } + catch (Exception ex) + { + Debug.Print(ex.Message); + } + } + + /// + /// + /// + /// + private void ProcessValueChangeNotify(string clientId, ByteBuffer block) + { + try + { + int minid = block.ReadInt(); + + for (int i = 0; i < minid; i++) + { + var vv = block.ReadInt(); + if (Driver.AllowTagIds.Contains(vv)) + { + if (mCallBackRegistorIds.ContainsKey(clientId)) + { + var itmp = mCallBackRegistorIds[clientId]; + itmp.SetId(vv); + } + else + { + IdBuffer ids = new IdBuffer(); + mCallBackRegistorIds.Add(clientId, ids); + ids.SetId(vv); + } + } + } + + + + if (!mDataCounts.ContainsKey(clientId)) + { + mDataCounts.Add(clientId, 0); + } + + Parent?.AsyncCallback(clientId, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + } + catch(Exception ex) + { + Debug.Print(ex.Message); + } + } + + /// + /// + /// + /// + private void ProcessResetValueChangedNotify(string clientId, ByteBuffer block) + { + try + { + if (mCallBackRegistorIds.ContainsKey(clientId)) + { + mCallBackRegistorIds.Remove(clientId); + } + if (mDataCounts.ContainsKey(clientId)) + { + mDataCounts.Remove(clientId); + } + } + catch + { + + } + Parent?.AsyncCallback(clientId, ToByteBuffer(APIConst.RealValueFun, (byte)1)); + } + + + /// + /// + /// + /// + /// + private void ProcessTagPush(ByteBuffer re,int id,byte type,object value) + { + re.Write(id); + re.Write(type); + switch (type) + { + case (byte)TagType.Bool: + re.Write(Convert.ToByte(value)); + break; + case (byte)TagType.Byte: + re.Write(Convert.ToByte(value)); + break; + case (byte)TagType.Short: + re.Write(Convert.ToInt16(value)); + break; + case (byte)TagType.UShort: + re.Write(Convert.ToUInt16(value)); + break; + case (byte)TagType.Int: + re.Write(Convert.ToInt32(value)); + break; + case (byte)TagType.UInt: + re.Write(Convert.ToUInt32(value)); + break; + case (byte)TagType.Long: + case (byte)TagType.ULong: + re.Write(Convert.ToInt64(value)); + break; + case (byte)TagType.Float: + re.Write(Convert.ToSingle(value)); + break; + case (byte)TagType.Double: + re.Write(Convert.ToDouble(value)); + break; + case (byte)TagType.String: + string sval = value.ToString(); + //re.Write(sval.Length); + re.Write(sval, Encoding.Unicode); + break; + case (byte)TagType.DateTime: + re.Write(((DateTime)value).Ticks); + break; + case (byte)TagType.IntPoint: + re.Write(((IntPointData)value).X); + re.Write(((IntPointData)value).Y); + break; + case (byte)TagType.UIntPoint: + re.Write((int)((UIntPointData)value).X); + re.Write((int)((UIntPointData)value).Y); + break; + case (byte)TagType.IntPoint3: + re.Write(((IntPoint3Data)value).X); + re.Write(((IntPoint3Data)value).Y); + re.Write(((IntPoint3Data)value).Z); + break; + case (byte)TagType.UIntPoint3: + re.Write((int)((UIntPoint3Data)value).X); + re.Write((int)((UIntPoint3Data)value).Y); + re.Write((int)((UIntPoint3Data)value).Z); + break; + case (byte)TagType.LongPoint: + re.Write(((LongPointData)value).X); + re.Write(((LongPointData)value).Y); + break; + case (byte)TagType.ULongPoint: + re.Write((long)((ULongPointData)value).X); + re.Write((long)((ULongPointData)value).Y); + break; + case (byte)TagType.LongPoint3: + re.Write(((LongPoint3Data)value).X); + re.Write(((LongPoint3Data)value).Y); + re.Write(((LongPoint3Data)value).Z); + break; + case (byte)TagType.ULongPoint3: + re.Write((long)((ULongPoint3Data)value).X); + re.Write((long)((ULongPoint3Data)value).Y); + re.Write((long)((ULongPoint3Data)value).Z); + break; + } + } + + + + /// + /// + /// + private void SendThreadPro() + { + while(!mIsClosed) + { + try + { + resetEvent.WaitOne(); + if (mIsClosed) return; + resetEvent.Reset(); + + HashSet hval = new HashSet(); + + List> changtags = new List>(); + + lock (mChangedTags) + { + changtags.AddRange(mChangedTags); + mChangedTags.Clear(); + } + + if (mCallBackRegistorIds.Count == 0) break; + + var clients = mCallBackRegistorIds.ToArray(); + foreach (var cb in clients) + { + var buffer = Parent.Allocate(APIConst.PushDataChangedFun, changtags.Count * 64 + 5); + buffer.Write(0); + buffers.Add(cb.Key, buffer); + mDataCounts[cb.Key] = 0; + } + + foreach (var vv in changtags) + { + foreach (var vvc in clients) + { + try + { + if (vvc.Value.CheckId(vv.Key)) + { + byte tp = (byte)mTagManager.GetTagById(vv.Key).Type; + ProcessTagPush(buffers[vvc.Key], vv.Key, tp, vv.Value); + mDataCounts[vvc.Key]++; + } + } + catch (Exception ex) + { + LoggerService.Service.Erro("DirectAccessDriver", "RealDataService " + ex.Message); + } + } + } + + foreach (var cb in buffers) + { + if (cb.Value.WriteIndex > 6) + { + var idx = cb.Value.WriteIndex; + //cb.Value.MarkWriterIndex(); + cb.Value.WriteIndex = 1; + //cb.Value.SetWriterIndex(1); + cb.Value.Write(mDataCounts[cb.Key]); + //cb.Value.ResetWriterIndex(); + cb.Value.WriteIndex = idx; + + Parent.PushRealDatatoClient(cb.Key, cb.Value); + } + + } + buffers.Clear(); + } + catch(Exception ex) + { + LoggerService.Service.Erro("RealDataServerProcess", ex.StackTrace); + } + } + } + + /// + /// + /// + + public override void Start() + { + + base.Start(); + resetEvent = new ManualResetEvent(false); + mScanThread = new Thread(SendThreadPro); + mScanThread.IsBackground = true; + mScanThread.Start(); + + } + + /// + /// + /// + public override void Stop() + { + mIsClosed = true; + resetEvent.Set(); + resetEvent.Close(); + base.Stop(); + } + + /// + /// + /// + /// + public override void OnClientConnected(string id) + { + if(!mCallBackRegistorIds.ContainsKey(id)) + { + mCallBackRegistorIds.Add(id,new IdBuffer()); + } + base.OnClientConnected(id); + } + + + /// + /// + /// + /// + public override void OnClientDisconnected(string id) + { + if(mCallBackRegistorIds.ContainsKey(id)) + { + mCallBackRegistorIds[id].Dispose(); + mCallBackRegistorIds.Remove(id); + } + base.OnClientDisconnected(id); + } + + /// + /// + /// + public override void Dispose() + { + ServiceLocator.Locator.Resolve().UnSubscribeValueChangedForProducter(mName); + this.mTagManager = null; + base.Dispose(); + } + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + + } +} diff --git a/Driver/DirectAccess/DirectAccessDriver/ServerProcessBase.cs b/Driver/DirectAccess/DirectAccessDriver/ServerProcessBase.cs new file mode 100644 index 00000000..fbf11a52 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessDriver/ServerProcessBase.cs @@ -0,0 +1,320 @@ +//============================================================== +// Copyright (C) 2022 Inc. All rights reserved. +// +//============================================================== +// Create by 种道洋 at 2020/1/2 11:00:57. +// Version 1.0 +// 种道洋 +//============================================================== + +using Cdy.Tag; +using Cheetah; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading; + +namespace DirectAccessDriver +{ + public abstract class ServerProcessBase:IDisposable + { + + #region ... Variables ... + /// + /// + /// + protected Dictionary> mDatasCach = new Dictionary>(); + + private Thread mProcessThread; + + private ManualResetEvent resetEvent; + + private bool mIsClosed = false; + + private List mClients = new List(); + + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + #endregion ...Constructor... + + #region ... Properties ... + /// + /// + /// + public abstract byte FunId { get; } + + /// + /// + /// + public DataService Parent { get; set; } + + /// + /// + /// + public bool IsPause { get; set; } = false; + + #endregion ...Properties... + + #region ... Methods ... + + + /// + /// + /// + /// + /// + protected ByteBuffer ToByteBuffer(byte id, string value) + { + var re = Parent.Allocate(id, value.Length*2+4); + re.Write(value); + return re; + } + + /// + /// + /// + /// + /// + /// + protected ByteBuffer ToByteBuffer(byte id, byte value) + { + var re = Parent.Allocate(id, 1); + re.Write(value); + return re; + } + + /// + /// + /// + /// + /// + /// + protected ByteBuffer ToByteBuffer(byte id, long value) + { + var re = Parent.Allocate(id, 8); + re.Write(value); + return re; + } + + /// + /// + /// + /// + /// + /// + /// + protected ByteBuffer ToByteBuffer(byte id, byte cid,long value) + { + var re = Parent.Allocate(id, 8+1); + re.Write(cid); + re.Write(value); + return re; + } + + /// + /// + /// + /// + /// + /// + /// + protected ByteBuffer ToByteBuffer(byte id, byte cid, string value) + { + var re = Parent.Allocate(id, value.Length * 2 + 4 + 1); + re.Write(cid); + re.Write(value); + return re; + } + /// + /// + /// + /// + /// + /// + /// + protected ByteBuffer ToByteBuffer(byte id, byte value, byte value2) + { + var re = Parent.Allocate(id, 2); + re.Write(value); + re.Write(value2); + return re; + } + + /// + /// + /// + /// + public virtual void ProcessData(string client, ByteBuffer data) + { + data.IncRef(); + if (mDatasCach.ContainsKey(client)) + { + mDatasCach[client].Enqueue(data); + } + else + { + var vq = new Queue(); + vq.Enqueue(data); + + lock (mDatasCach) + mDatasCach.Add(client, vq); + lock (mClients) + mClients.Add(client); + } + CheckDataBusy(client); + resetEvent.Set(); + } + + /// + /// + /// + public virtual void CheckDataBusy(string client) + { + + } + + /// + /// + /// + /// + public void RemoveClient(string client) + { + lock (mClients) + { + if (mClients.Contains(client)) + { + mClients.Remove(client); + } + } + + lock (mDatasCach) + { + if (mDatasCach.ContainsKey(client)) + { + mDatasCach.Remove(client); + } + } + } + + /// + /// + /// + private void DataProcess() + { + string sname=""; + Queue datas = null; + while (!mIsClosed) + { + resetEvent.WaitOne(); + if (mIsClosed) return; + resetEvent.Reset(); + + for (int i = 0; i < mClients.Count; i++) + { + sname = ""; + datas = null; + lock (mClients) + { + if (i < mClients.Count) + { + sname = mClients[i]; + } + } + + if (!string.IsNullOrEmpty(sname)) + { + lock (mDatasCach) + { + if (mDatasCach.ContainsKey(sname)) + { + datas = mDatasCach[sname]; + } + } + if (datas != null) + { + //Stopwatch sw = new Stopwatch(); + //sw.Start(); + //Debug.Print("开始实时数据请求:" + FunId +" " + datas.Count); + while (datas.Count > 0) + { + ProcessSingleData(sname, datas.Dequeue()); + } + //sw.Stop(); + //Debug.Print("结束实时数据请求:" + sw.ElapsedMilliseconds); + } + } + } + } + } + + /// + /// + /// + /// + /// + protected virtual void ProcessSingleData(string client, ByteBuffer data) + { + data.UnlockAndReturn(); + } + + /// + /// + /// + public virtual void Start() + { + resetEvent = new ManualResetEvent(false); + mProcessThread = new Thread(DataProcess); + mProcessThread.IsBackground = true; + mProcessThread.Start(); + } + + /// + /// + /// + public virtual void Stop() + { + mIsClosed = true; + resetEvent.Set(); + resetEvent.Close(); + } + + /// + /// + /// + public virtual void Dispose() + { + Parent = null; + } + + /// + /// + /// + /// + public virtual void OnClientConnected(string id) + { + + } + + /// + /// + /// + /// + public virtual void OnClientDisconnected(string id) + { + RemoveClient(id); + } + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + } +} diff --git a/Driver/DirectAccess/DirectAccessDriver/TagInfoServerProcess.cs b/Driver/DirectAccess/DirectAccessDriver/TagInfoServerProcess.cs new file mode 100644 index 00000000..b78dc381 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessDriver/TagInfoServerProcess.cs @@ -0,0 +1,396 @@ +//============================================================== +// Copyright (C) 2022 Inc. All rights reserved. +// +//============================================================== +// Create by 种道洋 at 2020/1/2 11:00:57. +// Version 1.0 +// 种道洋 +//============================================================== + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Cdy.Tag; +using Cdy.Tag.Driver; +using Cheetah; + +namespace DirectAccessDriver +{ + public class TagInfoServerProcess : ServerProcessBase + { + + #region ... Variables ... + + public const byte GetTagIdByNameFun = 0; + + public const byte QueryAllTagNameAndIds = 2; + + public const byte GetTagIdByFilterRegistor = 3; + + public const byte GetDriverRecordTypeTagIds = 5; + + public const byte GetDriverRecordTypeTagIds2 = 51; + + + + public const byte Login = 1; + /// + /// + /// + public const byte Login2 = 11; + + private Dictionary mClients = new Dictionary(); + + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + #endregion ...Constructor... + + #region ... Properties ... + + public override byte FunId => APIConst.TagInfoRequestFun; + + #endregion ...Properties... + + #region ... Methods ... + + + + /// + /// + /// + /// + /// + protected unsafe override void ProcessSingleData(string client, ByteBuffer data) + { + var mm = Cdy.Tag.ServiceLocator.Locator.Resolve(); + byte sfun = data.ReadByte(); + switch (sfun) + { + case GetTagIdByNameFun: + long loginId = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(loginId)||loginId<1) + { + int count = data.ReadInt(); + if (count > 0) + { + var re = Parent.Allocate(APIConst.TagInfoRequestFun, (count+1) * 4+1); + re.Write(GetTagIdByNameFun); + re.Write(count); + + //首先删除旧的缓冲 + //Span sp=null; + int[] sp; + lock (mClients) + { + + sp = new int[count]; + if(mClients.ContainsKey(client)) + { + mClients[client] = sp; + } + else + { + mClients.Add(client, sp); + } + } + + for (int i = 0; i < count; i++) + { + // string stag = data.ReadString(); + var ival = mm.GetTagIdByName(data.ReadString()); + if (ival.HasValue) + { + re.Write(ival.Value); + sp[i] = ival.Value; + } + else + { + re.Write((int)-1); + sp[i] = -1; + } + } + + Parent.AsyncCallback(client, re); + } + } + break; + case QueryAllTagNameAndIds: + loginId = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(loginId)) + { + int psize = 500000; + var vtags = mm.ListAllTags().Where(e=>e.LinkAddress.StartsWith("DirectAccess")); + int tcount = vtags.Count() / psize; + tcount += (vtags.Count() % psize > 0 ? 1 : 0); + for(int i=0;ivtags.Count()) + { + var vv = vtags.Skip(i * psize).Take(vtags.Count() % psize); + Parent.AsyncCallback(client, GetTagBuffer(vv, (short)i, (short)tcount)); + } + else + { + var vv = vtags.Skip(i * psize).Take(psize); + Parent.AsyncCallback(client, GetTagBuffer(vv, (short)i, (short)tcount)); + } + } + + if(tcount==0) + { + Parent.AsyncCallback(client, GetTagBuffer(new List(), (short)0, (short)0)); + } + + } + break; + case GetTagIdByFilterRegistor: + loginId = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(loginId)) + { + string filter = data.ReadString(); + int psize = 500000; + var vtags = mm.ListAllTags().Where(e => e.LinkAddress.StartsWith("DirectAccess")&&e.LinkAddress.Contains(filter)); + int tcount = vtags.Count() / psize; + tcount += (vtags.Count() % psize > 0 ? 1 : 0); + for (int i = 0; i < tcount; i++) + { + if ((i + 1) * psize > vtags.Count()) + { + var vv = vtags.Skip(i * psize).Take(vtags.Count() % psize); + Parent.AsyncCallback(client, GetTagBuffer(vv, (short)i, (short)tcount)); + } + else + { + var vv = vtags.Skip(i * psize).Take(psize); + Parent.AsyncCallback(client, GetTagBuffer(vv, (short)i, (short)tcount)); + } + } + + if (tcount == 0) + { + Parent.AsyncCallback(client, GetTagBuffer(new List(), (short)0, (short)0)); + } + + } + break; + case GetDriverRecordTypeTagIds: + loginId = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(loginId)) + { + int psize = 500000; + + var vserver = ServiceLocator.Locator.Resolve(); + + var vtags = vserver.ListAllDriverRecordTags(); + int tcount = vtags.Count() / psize; + tcount += (vtags.Count() % psize > 0 ? 1 : 0); + for (int i = 0; i < tcount; i++) + { + if ((i + 1) * psize > vtags.Count()) + { + var vv = vtags.Skip(i * psize).Take(vtags.Count() % psize); + Parent.AsyncCallback(client, GetRecordTypeBuffer(vv, (short)i, (short)tcount)); + } + else + { + var vv = vtags.Skip(i * psize).Take(psize); + Parent.AsyncCallback(client, GetRecordTypeBuffer(vv, (short)i, (short)tcount)); + } + } + + if (tcount == 0) + { + Parent.AsyncCallback(client, GetRecordTypeBuffer(new List(), (short)0, (short)0)); + } + } + break; + case GetDriverRecordTypeTagIds2: + loginId = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(loginId)) + { + + var vserver = ServiceLocator.Locator.Resolve(); + int icount = data.ReadInt(); + + ByteBuffer re = Parent.Allocate(APIConst.TagInfoRequestFun, icount + 5); + re.WriteByte(GetDriverRecordTypeTagIds2); + re.Write(icount); + for (int i = 0; i < icount; i++) + { + if(vserver.GetHisTagById(data.ReadInt())?.Type == RecordType.Driver) + { + re.WriteByte(1); + } + else + { + re.WriteByte(0); + } + } + Parent.AsyncCallback(client, re); + } + break; + case Login: + try + { + string user = data.ReadString(); + string pass = data.ReadString(); + long result = Cdy.Tag.ServiceLocator.Locator.Resolve().Login(user, pass, client); + + if (result > 0) + { + lock (mClients) + { + if (!mClients.ContainsKey(client)) + mClients.Add(client, null); + } + LoggerService.Service.Info("DirectAccessDriver", user + " at client " + client + " login sucessfull " + result); + } + else + { + LoggerService.Service.Warn("DirectAccessDriver", user + " at client " + client + " login failed."); + } + + Parent.AsyncCallback(client, ToByteBuffer(APIConst.TagInfoRequestFun,Login, result)); + } + catch(Exception eex) + { + LoggerService.Service.Erro("DirectAccessDriver", $"{eex.Message}:{eex.StackTrace}" ); + } + break; + case Login2: + try + { + loginId = data.ReadLong(); + if (Cdy.Tag.ServiceLocator.Locator.Resolve().CheckLogin(loginId)) + { + string user = data.ReadString(); + string pass = data.ReadString(); + string result = Cdy.Tag.ServiceLocator.Locator.Resolve().Login(user, pass); + Parent.AsyncCallback(client, ToByteBuffer(APIConst.TagInfoRequestFun, Login2, result)); + } + } + catch (Exception eex) + { + LoggerService.Service.Erro("DirectAccessDriver", $"{eex.Message}:{eex.StackTrace}"); + } + break; + } + } + + /// + /// 通知数据发送变化 + /// + public void NotifyDatabaseChanged(bool realchanged, bool hischanged) + { + byte val = 0; + if (realchanged) val += 1; + if (hischanged) val += 2; + + if (val > 0) + { + ByteBuffer data = ToByteBuffer(APIConst.DatabaseChangedNotify, val); + foreach (var vv in mClients) + { + Parent.AsyncCallback(vv.Key, data); + } + } + } + + /// + /// + /// + /// + /// + /// + /// + private ByteBuffer GetTagBuffer(IEnumerable tags,short bcount,short totalcount) + { + ByteBuffer re = Parent.Allocate(APIConst.TagInfoRequestFun, tags.Count() * 302+9); + re.Write(QueryAllTagNameAndIds); + re.Write(totalcount); + re.Write(bcount); + re.Write(tags.Count()); + foreach(var vv in tags) + { + re.Write(vv.Id); + re.Write(vv.FullName); + re.WriteByte((byte)vv.Type); + } + return re; + } + + /// + /// + /// + /// + /// + /// + /// + private ByteBuffer GetRecordTypeBuffer(IEnumerable tags, short bcount, short totalcount) + { + ByteBuffer re = Parent.Allocate(APIConst.TagInfoRequestFun, tags.Count() * 4 + 9); + re.Write(GetDriverRecordTypeTagIds); + re.Write(totalcount); + re.Write(bcount); + re.Write(tags.Count()); + foreach (var vv in tags) + { + re.Write(vv.Id); + } + return re; + } + + /// + /// + /// + /// + public unsafe override void OnClientDisconnected(string id) + { + if (mClients.ContainsKey(id)) + { + //Tuple pp = mClients[id]; + var pp = mClients[id]; + + lock (mClients) + mClients.Remove(id); + + //to do update bad quality + if(pp!=null) + { + var service = ServiceLocator.Locator.Resolve(); + //Span sp = new Span((byte*)pp.Item1, pp.Item2*4); + DateTime dtime = DateTime.Now; + //for(int i=0;i -1) + { + service.SetTagQuality(ip, (byte)QualityConst.Offline, dtime); + } + } + + //Marshal.FreeHGlobal(pp.Item1); + + } + } + base.OnClientDisconnected(id); + } + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc.Client/Client.cs b/Driver/DirectAccess/DirectAccessGrpc.Client/Client.cs new file mode 100644 index 00000000..b954cd28 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc.Client/Client.cs @@ -0,0 +1,399 @@ +using Grpc.Net.Client; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Reflection; +using System.Linq; + +namespace DirectAccess +{ + /// + /// + /// + public class Client:IDisposable + { + + #region ... Variables ... + + private string mLoginId = string.Empty; + + + private DirectAccess.Data.DataClient mDataClient; + + + private Grpc.Net.Client.GrpcChannel grpcChannel; + + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + + + /// + /// + /// + /// + /// + public Client(string ip,int port) + { + Ip = ip; + Port = port; + Init(); + } + + #endregion ...Constructor... + + #region ... Properties ... + + /// + /// 使用TLS加密 + /// + public bool UseTls { get; set; } = true; + + public string Ip { get; set; } + + /// + /// + /// + public int Port { get; set; } + + /// + /// + /// + public bool IsLogined + { + get + { + return !string.IsNullOrEmpty(mLoginId); + } + } + + /// + /// 超时时间 + /// + public int TimeOut { get; set; } + + /// + /// + /// + public DateTime LoginTime { get; set; } + + #endregion ...Properties... + + #region ... Methods ... + + /// + /// + /// + public Client Init() + { + try + { + var httpClientHandler = new HttpClientHandler(); + httpClientHandler.ServerCertificateCustomValidationCallback = + HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + var httpClient = new HttpClient(httpClientHandler); + if(UseTls) + grpcChannel = Grpc.Net.Client.GrpcChannel.ForAddress(@"https://" + Ip + ":"+ Port, new GrpcChannelOptions { HttpClient = httpClient }); + else + { + grpcChannel = Grpc.Net.Client.GrpcChannel.ForAddress(@"http://" + Ip + ":" + Port, new GrpcChannelOptions { HttpClient = httpClient }); + } + mDataClient = new DirectAccess.Data.DataClient(grpcChannel); + } + catch (Exception ex) + { + //LoggerService.Service.Erro("DevelopService", ex.Message); + } + return this; + } + + + /// + /// 登录 + /// + /// 用户名 + /// 密码 + /// + public bool Login(string username,string password) + { + if (mDataClient != null) + { + try + { + var re = mDataClient.Login(new LoginRequest() { Name = username, Password = password }); + TimeOut = re.Timeout; + LoginTime = DateTime.FromBinary(re.Time).ToLocalTime(); + mLoginId = re.Token; + } + catch + { + return false; + } + } + return false; + } + + /// + /// 登出 + /// + public void Logout() + { + if(mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + try + { + mDataClient.Logout(new LogoutRequest() { Token = mLoginId }); + mLoginId = string.Empty; + } + catch + { + + } + } + } + + /// + /// 定时心跳,维持登录 + /// + /// + public bool Hart() + { + try + { + if(mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + return mDataClient.Hart(new HartRequest() { Token = mLoginId }).Result; + } + } + catch + { + + } + return false; + } + + /// + /// 更新实时数据 + /// + /// 变量 + /// 值 + /// 质量 + /// + public bool UpdateTagValue(string tag,object value,byte quality) + { + try + { + if (mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + var dr = new DataRequest() { Token = mLoginId }; + dr.Value.Add(new TagValue() { Tag = tag, Value = value.ToString(), Quality = quality }); + return mDataClient.UpdateValue(dr).Result; + } + } + catch + { + + } + return false; + } + + /// + /// 更新实时数据 + /// + /// 值 + /// + public bool UpdateTagValue(Dictionary> values) + { + try + { + if (mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + var dr = new DataRequest() { Token = mLoginId }; + foreach(var vv in values) + dr.Value.Add(new TagValue() { Tag = vv.Key, Value = vv.Value.Item1.ToString(), Quality = vv.Value.Item2 }); + return mDataClient.UpdateValue(dr).Result; + } + } + catch + { + + } + return false; + } + + /// + /// 更新实时数据 + /// + /// 值 + /// + public bool UpdateTagValue(Dictionary values) + { + try + { + if (mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + var dr = new DataRequest() { Token = mLoginId }; + foreach (var vv in values) + dr.Value.Add(new TagValue() { Tag = vv.Key, Value = vv.Value.Value.ToString(), Quality = vv.Value.Quality }); + return mDataClient.UpdateValue(dr).Result; + } + } + catch + { + + } + return false; + } + + /// + /// 更新历史数据 + /// + /// 值 + /// + public bool UpdateTagHisValue(Dictionary>> values) + { + try + { + if (mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + var dr = new HisDataRequest() { Token = mLoginId }; + foreach(var vv in values) + { + var vval = new TagHisDataValue(); + vval.Tag = vv.Key; + vval.Value.AddRange(vv.Value.Select(e => new HisValue() { Time = e.Item1.ToBinary(), Value = e.Item2.ToString(), Quality = e.Item3 })); + dr.Value.Add(vval); + } + return mDataClient.UpdateHisValue(dr).Result; + } + } + catch + { + + } + return false; + } + + /// + /// 更新历史数据 + /// + /// 值 + /// + public bool UpdateTagHisValue(List values) + { + try + { + if (mDataClient != null && !string.IsNullOrEmpty(mLoginId)) + { + var dr = new HisDataRequest() { Token = mLoginId }; + foreach (var vv in values) + { + var vval = new TagHisDataValue(); + vval.Tag = vv.Tag; + foreach (var vvv in vv) + { + vval.Value.AddRange(vv.Select(e => new HisValue() { Time = e.Time.ToBinary(), Value = e.Value.ToString(), Quality = e.Quality })); + } + } + return mDataClient.UpdateHisValue(dr).Result; + } + } + catch + { + + } + return false; + } + /// + /// + /// + public void Dispose() + { + mLoginId = string.Empty; + grpcChannel.Dispose(); + } + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + } + + /// + /// + /// + public class HisDataValueCollection: List + { + + #region ... Variables ... + + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + #endregion ...Constructor... + + #region ... Properties ... + + /// + /// + /// + public string Tag { get; set; } + + #endregion ...Properties... + + #region ... Methods ... + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + } + /// + /// + /// + public struct HisDataValuePoint + { + /// + /// + /// + public object Value { get; set; } + + /// + /// + /// + public DateTime Time { get; set; } + + /// + /// + /// + public byte Quality { get; set; } + } + + + public struct RealValuePoint + { + /// + /// + /// + public object Value { get; set; } + + + /// + /// + /// + public byte Quality { get; set; } + } + +} diff --git a/Driver/DirectAccess/DirectAccessGrpc.Client/DirectAccessGrpc.Client.csproj b/Driver/DirectAccess/DirectAccessGrpc.Client/DirectAccessGrpc.Client.csproj new file mode 100644 index 00000000..fd92bed3 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc.Client/DirectAccessGrpc.Client.csproj @@ -0,0 +1,30 @@ + + + + netstandard2.1 + + + + true + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + Client + + + + diff --git a/Driver/DirectAccess/DirectAccessGrpc.Client/Protos/Data.proto b/Driver/DirectAccess/DirectAccessGrpc.Client/Protos/Data.proto new file mode 100644 index 00000000..f1d0235e --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc.Client/Protos/Data.proto @@ -0,0 +1,84 @@ +syntax = "proto3"; + +option csharp_namespace = "DirectAccess"; + +package GrpcService; + +// The greeting service definition. +service Data { + // ʷ + rpc UpdateHisValue (HisDataRequest) returns (BoolReply); + //ʵʱ + rpc UpdateValue (DataRequest) returns (BoolReply); + + rpc Login (LoginRequest) returns (LoginReply); + rpc Hart (HartRequest) returns (BoolReply); + rpc Logout (LogoutRequest) returns (BoolReply); +} + +// +message DataRequest +{ + string Token=1; + repeated TagValue Value=2; +} + +// +message TagValue +{ + string Tag=1; + string Value=2; + int32 Quality=3; +} + +// +message HisDataRequest{ + string Token=1; + repeated TagHisDataValue Value=2; +} + +// +message TagHisDataValue +{ + string Tag=1; + repeated HisValue Value=2; +} + +// +message HisValue +{ + int64 Time=1; + string Value=2; + int32 Quality=3; +} + +// The request message containing the user's name. +message LoginRequest { + string name = 1; + string password=2; +} + +// The response message containing the Data. +message LoginReply { + string Token = 1; + int64 Time=2; + int32 Timeout=3; +} + +message HartRequest { + string Token = 1; + int64 Time=2; +} + + +message LogoutRequest { + string Token = 1; +} + + +message BoolReply { + bool Result = 1; + string ErroMessage=2; +} + + diff --git a/Driver/DirectAccess/DirectAccessGrpc/Config/DirectAccessGrpc.cfg b/Driver/DirectAccess/DirectAccessGrpc/Config/DirectAccessGrpc.cfg new file mode 100644 index 00000000..a27d79b6 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/Config/DirectAccessGrpc.cfg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Driver/DirectAccess/DirectAccessGrpc/DirectAccessGrpc.csproj b/Driver/DirectAccess/DirectAccessGrpc/DirectAccessGrpc.csproj new file mode 100644 index 00000000..09520c2d --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/DirectAccessGrpc.csproj @@ -0,0 +1,38 @@ + + + + net5.0 + + + + true + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + + + + + diff --git a/Driver/DirectAccess/DirectAccessGrpc/DirectAccessProxy.cs b/Driver/DirectAccess/DirectAccessGrpc/DirectAccessProxy.cs new file mode 100644 index 00000000..d50af5df --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/DirectAccessProxy.cs @@ -0,0 +1,347 @@ +using Cdy.Tag; +using DirectAccessDriver.ClientApi; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace DirectAccessGrpc +{ + public class DirectAccessProxy + { + + #region ... Variables ... + + public static DirectAccessProxy Proxy = new DirectAccessProxy(); + + private string mIp; + private int mPort; + private string mUserName; + private string mPassword; + + private int mServerPort = 10081; + + private DirectAccessDriver.ClientApi.DriverProxy mClient; + + private bool mIsConnected = false; + + private Dictionary> mTagCach = new Dictionary>(); + + public object RealSyncLocker { get; set; } = new object(); + + public object HisSyncLocker { get; set; } = new object(); + + private Thread mMonitorThread; + private bool mIsConnectedChanged = false; + bool isClosed = false; + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + #endregion ...Constructor... + + #region ... Properties ... + + /// + /// + /// + public Dictionary> TagCach + { + get + { + return mTagCach; + } + } + + /// + /// + /// + public bool IsConnected + { + get + { + return mIsConnected; + } + set + { + if (mIsConnected != value) + { + mIsConnected = value; + } + } + } + + /// + /// + /// + public int ServerPort + { + get + { + return mServerPort; + } + } + + + #endregion ...Properties... + + #region ... Methods ... + + /// + /// + /// + public DirectAccessProxy Load() + { + string sfileName = Assembly.GetEntryAssembly().Location; + string spath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(sfileName), "Config"); + sfileName = System.IO.Path.Combine(spath, System.IO.Path.GetFileNameWithoutExtension(sfileName) + ".cfg"); + + if (System.IO.File.Exists(sfileName)) + { + XElement xx = XElement.Load(sfileName); + if (xx.Element("ProxyClient") == null) + return this; + var xe = xx.Element("ProxyClient"); + if (xe.Attribute("Ip") != null) + { + mIp = xe.Attribute("Ip").Value; + } + + if (xe.Attribute("Port") != null) + { + mPort = int.Parse(xe.Attribute("Port").Value); + } + + if (xe.Attribute("LoginUser") != null) + { + mUserName = xe.Attribute("LoginUser").Value; + } + + if (xe.Attribute("LoginPassword") != null) + { + mPassword = xe.Attribute("LoginPassword").Value; + } + + if(xx.Attribute("ServerPort") !=null) + { + mServerPort = int.Parse(xx.Attribute("ServerPort").Value); + } + } + return this; + } + + /// + /// + /// + public DirectAccessProxy Start() + { + mClient = new DirectAccessDriver.ClientApi.DriverProxy(); + //mClient.PropertyChanged += MClient_PropertyChanged; + mClient.DatabaseChanged = (his, real) => { + Task.Run(() => { InitTagInfos(); }); + }; + mClient.Open(mIp, mPort); + mMonitorThread = new Thread(MonitorProcess); + mMonitorThread.IsBackground = true; + mMonitorThread.Start(); + return this; + } + + /// + /// + /// + public void Close() + { + isClosed = true; + mClient.Close(); + } + + private void MonitorProcess() + { + while(!isClosed) + { + if (!mClient.IsLogin) + { + if (mClient.IsConnected) + { + var re = mClient.Login(mUserName, mPassword); + if (re) + { + InitTagInfos(); + IsConnected = true; + Cdy.Tag.LoggerService.Service.Info("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} sucessfull."); + mIsConnectedChanged = false; + } + else + { + IsConnected = false; + Cdy.Tag.LoggerService.Service.Info("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} failed."); + } + } + else if (IsConnected) + { + IsConnected = false; + SecurityManager.Manager.Clear(); + Cdy.Tag.LoggerService.Service.Info("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} failed."); + } + Thread.Sleep(2000); + } + else + { + mClient.Hart(); + Thread.Sleep(3000); + } + } + } + + ///// + ///// + ///// + ///// + ///// + //private void MClient_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + //{ + // if(e.PropertyName== "IsConnected") + // { + // mIsConnectedChanged = true; + // //if(mClient.IsConnected) + // //{ + // // if(!mClient.IsLogin) + // // { + // // Task.Run(() => { + // // var re = mClient.Login(mUserName, mPassword); + // // if (re) + // // { + // // InitTagInfos(); + // // IsConnected = true; + // // Cdy.Tag.LoggerService.Service.Info("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} sucessfull."); + // // } + // // else + // // { + // // IsConnected = false; + // // Cdy.Tag.LoggerService.Service.Info("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} failed."); + // // } + // // }); + + // // } + // // else + // // { + // // IsConnected = true; + // // Cdy.Tag.LoggerService.Service.Info("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} sucessfull."); + // // } + // //} + // //else + // //{ + // // SecurityManager.Manager.Clear(); + // // IsConnected = false; + // // Cdy.Tag.LoggerService.Service.Warn("DataAccess", $"Login {mClient.ServerIp}:{mClient.Port} failed."); + // //} + // } + //} + + /// + /// + /// + /// + /// + /// + public string Login(string user,string password) + { + if(IsConnected) + { + var re = mClient.Login2(user, password); + return re; + } + return string.Empty; + } + + /// + /// + /// + private void InitTagInfos() + { + lock (HisSyncLocker) + lock (RealSyncLocker) + { + try + { + mTagCach.Clear(); + var vids = mClient.QueryAllTagIdAndNames(); + if (vids != null && vids.Count > 0) + { + foreach (var vv in vids) + { + if (mTagCach.ContainsKey(vv.Value.Item1)) + { + mTagCach[vv.Value.Item1] = new Tuple(vv.Key, vv.Value.Item2); + } + else + { + mTagCach.Add(vv.Value.Item1, new Tuple(vv.Key, vv.Value.Item2)); + } + } + } + } + catch (Exception ex) + { + + } + } + } + + /// + /// + /// + /// + /// + public bool UpdateData(RealDataBuffer values) + { + if(IsConnected) + { + return mClient.SetTagRealAndHisValue(values); + } + return true; + } + + /// + /// + /// + /// + /// + public bool UpdateHisData(HisDataBuffer values,int count) + { + if (IsConnected) + { + return mClient.SetMutiTagHisValue(values,count,10000); + } + return true; + } + + /// + /// + /// + /// + /// + public bool UpdateHisData(Dictionary> values) + { + if (IsConnected) + { + return mClient.SetMutiTagHisValue(values, 10000); + } + return true; + } + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc/Program.cs b/Driver/DirectAccess/DirectAccessGrpc/Program.cs new file mode 100644 index 00000000..b5d731ac --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/Program.cs @@ -0,0 +1,68 @@ +using Cdy.Tag; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace DirectAccessGrpc +{ + public class Program + { + static int Port = 14338; + + public static void Main(string[] args) + { + ServiceLocator.Locator.Registor(new ConsoleLogger()); + + Port = DirectAccessProxy.Proxy.Load().ServerPort; + Console.Title = "DirectAccessGrpcApi"; + if (args.Contains("/m")) + { + WindowConsolHelper.MinWindow("DirectAccessGrpcApi"); + } + CreateHostBuilder(args).Build().Run(); + } + + /// + /// + /// + public static bool IsWin7 + { + get + { + return Environment.OSVersion.Version.Major < 8 && Environment.OSVersion.Platform == PlatformID.Win32NT; + } + } + + // Additional configuration is required to successfully run gRPC on macOS. + // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682 + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureLogging(logging => + { + logging.AddFilter("Grpc", LogLevel.Warning); + logging.SetMinimumLevel(LogLevel.Warning); + }) + .ConfigureWebHostDefaults(webBuilder => + { + if (IsWin7) + { + //Win 7 ʹ ֧TLS HTTP/2 + webBuilder.ConfigureKestrel(options => + { + options.Listen(System.Net.IPAddress.Parse("0.0.0.0"), Port, a => a.Protocols = + Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2); + }); + } + else + { + webBuilder.UseUrls("https://0.0.0.0:" + Port); + } + webBuilder.UseStartup(); + }); + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc/Properties/launchSettings.json b/Driver/DirectAccess/DirectAccessGrpc/Properties/launchSettings.json new file mode 100644 index 00000000..2890c2dd --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "DirectAccessGrpc": { + "commandName": "Project", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": "true", + "applicationUrl": "http://localhost:5000;https://localhost:5001" + } + } +} \ No newline at end of file diff --git a/Driver/DirectAccess/DirectAccessGrpc/Protos/Data.proto b/Driver/DirectAccess/DirectAccessGrpc/Protos/Data.proto new file mode 100644 index 00000000..f1d0235e --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/Protos/Data.proto @@ -0,0 +1,84 @@ +syntax = "proto3"; + +option csharp_namespace = "DirectAccess"; + +package GrpcService; + +// The greeting service definition. +service Data { + // ʷ + rpc UpdateHisValue (HisDataRequest) returns (BoolReply); + //ʵʱ + rpc UpdateValue (DataRequest) returns (BoolReply); + + rpc Login (LoginRequest) returns (LoginReply); + rpc Hart (HartRequest) returns (BoolReply); + rpc Logout (LogoutRequest) returns (BoolReply); +} + +// +message DataRequest +{ + string Token=1; + repeated TagValue Value=2; +} + +// +message TagValue +{ + string Tag=1; + string Value=2; + int32 Quality=3; +} + +// +message HisDataRequest{ + string Token=1; + repeated TagHisDataValue Value=2; +} + +// +message TagHisDataValue +{ + string Tag=1; + repeated HisValue Value=2; +} + +// +message HisValue +{ + int64 Time=1; + string Value=2; + int32 Quality=3; +} + +// The request message containing the user's name. +message LoginRequest { + string name = 1; + string password=2; +} + +// The response message containing the Data. +message LoginReply { + string Token = 1; + int64 Time=2; + int32 Timeout=3; +} + +message HartRequest { + string Token = 1; + int64 Time=2; +} + + +message LogoutRequest { + string Token = 1; +} + + +message BoolReply { + bool Result = 1; + string ErroMessage=2; +} + + diff --git a/Driver/DirectAccess/DirectAccessGrpc/SecurityManager.cs b/Driver/DirectAccess/DirectAccessGrpc/SecurityManager.cs new file mode 100644 index 00000000..9a099927 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/SecurityManager.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace DirectAccessGrpc +{ + public class SecurityManager + { + + #region ... Variables ... + /// + /// + /// + public static SecurityManager Manager = new SecurityManager(); + + private Dictionary mLoginCach = new Dictionary(); + + #endregion ...Variables... + + #region ... Events ... + + #endregion ...Events... + + #region ... Constructor... + + #endregion ...Constructor... + + #region ... Properties ... + + public int Timeout { get; set; } = 10 * 60; + + #endregion ...Properties... + + #region ... Methods ... + + /// + /// + /// + public void Clear() + { + lock(mLoginCach) + mLoginCach.Clear(); + } + + /// + /// + /// + /// + public void RemoveUser(string id) + { + lock (mLoginCach) + { + if (mLoginCach.ContainsKey(id)) + { + mLoginCach.Remove(id); + } + } + } + + /// + /// + /// + /// + public void CachUser(string id) + { + lock (mLoginCach) + { + if (!mLoginCach.ContainsKey(id)) + { + mLoginCach.Add(id, DateTime.Now); + } + else + { + mLoginCach[id] = DateTime.Now; + } + } + } + + /// + /// + /// + /// + public bool IsLogin(string id) + { + lock (mLoginCach) + { + DateTime dnow = DateTime.Now; + if (mLoginCach.ContainsKey(id)) + { + var re = (dnow - mLoginCach[id]).TotalSeconds < Timeout; + if (re) + { + mLoginCach[id] = dnow; + } + return re; + } + } + return false; + } + + /// + /// + /// + /// + public void RefreshLogin(string id) + { + lock (mLoginCach) + { + if (mLoginCach.ContainsKey(id)) + { + mLoginCach[id] = DateTime.Now; + } + } + } + + #endregion ...Methods... + + #region ... Interfaces ... + + #endregion ...Interfaces... + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc/Services/DataService.cs b/Driver/DirectAccess/DirectAccessGrpc/Services/DataService.cs new file mode 100644 index 00000000..01f0b9c9 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/Services/DataService.cs @@ -0,0 +1,463 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Cdy.Tag; +using DirectAccess; +using DirectAccessDriver.ClientApi; +using Grpc.Core; +using Microsoft.Extensions.Logging; + +namespace DirectAccessGrpc +{ + /// + /// + /// + public class DataService : DirectAccess.Data.DataBase + { + private RealDataBuffer rdb = new RealDataBuffer(); + + private HisDataBuffer hdb = new HisDataBuffer(); + + private readonly ILogger _logger; + + public DataService(ILogger logger) + { + _logger = logger; + } + + /// + /// + /// + /// + /// + /// + public override Task UpdateValue(DataRequest request, ServerCallContext context) + { + try + { + if (SecurityManager.Manager.IsLogin(request.Token)) + { + bool re = false; + if (DirectAccessProxy.Proxy.IsConnected && DirectAccessProxy.Proxy.TagCach.Count > 0) + { + lock (DirectAccessProxy.Proxy.RealSyncLocker) + { + rdb.CheckAndResize(request.Value.Count * 305); + rdb.Clear(); + foreach (var vv in request.Value) + { + if (DirectAccessProxy.Proxy.TagCach.ContainsKey(vv.Tag)) + { + var vtg = DirectAccessProxy.Proxy.TagCach[vv.Tag]; + + switch (vtg.Item2) + { + case (byte)(Cdy.Tag.TagType.Bool): + rdb.AppendValue(vtg.Item1, Convert.ToBoolean(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.Byte): + rdb.AppendValue(vtg.Item1, Convert.ToByte(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.Short): + rdb.AppendValue(vtg.Item1, Convert.ToInt16(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.UShort): + rdb.AppendValue(vtg.Item1, Convert.ToUInt16(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.Int): + rdb.AppendValue(vtg.Item1, Convert.ToInt32(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.UInt): + rdb.AppendValue(vtg.Item1, Convert.ToUInt32(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.Long): + rdb.AppendValue(vtg.Item1, Convert.ToInt64(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.ULong): + rdb.AppendValue(vtg.Item1, Convert.ToUInt64(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.Double): + rdb.AppendValue(vtg.Item1, Convert.ToDouble(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.Float): + rdb.AppendValue(vtg.Item1, Convert.ToSingle(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.String): + rdb.AppendValue(vtg.Item1, vv.Value, (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.DateTime): + rdb.AppendValue(vtg.Item1, DateTime.Parse(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.IntPoint): + rdb.AppendValue(vtg.Item1, Cdy.Tag.IntPointData.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.IntPoint3): + rdb.AppendValue(vtg.Item1, Cdy.Tag.IntPoint3Data.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.UIntPoint): + rdb.AppendValue(vtg.Item1, Cdy.Tag.UIntPointData.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.UIntPoint3): + rdb.AppendValue(vtg.Item1, Cdy.Tag.UIntPoint3Data.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.LongPoint): + rdb.AppendValue(vtg.Item1, Cdy.Tag.LongPointData.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.LongPoint3): + rdb.AppendValue(vtg.Item1, Cdy.Tag.LongPoint3Data.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.ULongPoint): + rdb.AppendValue(vtg.Item1, Cdy.Tag.ULongPointData.FromString(vv.Value), (byte)vv.Quality); + break; + case (byte)(Cdy.Tag.TagType.ULongPoint3): + rdb.AppendValue(vtg.Item1, Cdy.Tag.ULongPoint3Data.FromString(vv.Value), (byte)vv.Quality); + break; + + } + } + } + if (rdb.ValueCount > 0) + { + re = DirectAccessProxy.Proxy.UpdateData(rdb); + } + } + + return Task.FromResult(new BoolReply() { Result = re, ErroMessage = re ? "" : "Send data failed" }); + } + else + { + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Connect server failed" }); + } + + } + else + { + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Login failed" }); + } + } + catch(Exception ex) + { + Cdy.Tag.LoggerService.Service.Erro("DataService", $"UpdateValue: {ex.Message} {ex.StackTrace}"); + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = ex.Message }); + } + } + + //public override Task UpdateHisValue(HisDataRequest request, ServerCallContext context) + //{ + // try + // { + // if (SecurityManager.Manager.IsLogin(request.Token)) + // { + // if (DirectAccessProxy.Proxy.IsConnected && DirectAccessProxy.Proxy.TagCach.Count > 0) + // { + // Dictionary> values = new Dictionary>(); + // foreach (var vv in request.Value) + // { + // if (DirectAccessProxy.Proxy.TagCach.ContainsKey(vv.Tag)) + // { + // var vtg = DirectAccessProxy.Proxy.TagCach[vv.Tag]; + // List val; + // if (values.ContainsKey(vtg.Item1)) + // { + // val = values[vtg.Item1] as List; + // } + // else + // { + // val = new List(); + // } + + // foreach (var vvv in vv.Value) + // { + // val.Add(new TagValueAndType() { Value = vvv.Value, ValueType = (TagType)vtg.Item2, Quality = (byte)vvv.Quality, Time = DateTime.FromBinary(vvv.Time) }); + // } + // } + // } + + // var re = DirectAccessProxy.Proxy.UpdateHisData(values); + // return Task.FromResult(new BoolReply() { Result = re, ErroMessage = re ? "" : "Send data failed" }); + // } + // else + // { + // return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Connect server failed" }); + // } + // } + // return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Login failed" }); + // } + // catch (Exception ex) + // { + // Cdy.Tag.LoggerService.Service.Erro("DataService", $"UpdateHisValue: {ex.Message} {ex.StackTrace}"); + // return Task.FromResult(new BoolReply() { Result = false, ErroMessage = ex.Message }); + // } + //} + + /// + /// + /// + /// + /// + /// + /// + private void SetTagValueToBuffer2(TagType type, object value, byte quality, HisDataBuffer re) + { + switch (type) + { + case TagType.Bool: + re.Write(Convert.ToByte(value)); + break; + case TagType.Byte: + re.Write(Convert.ToByte(value)); + break; + case TagType.Short: + re.Write(Convert.ToInt16(value)); + break; + case TagType.UShort: + re.Write(Convert.ToUInt16(value)); + break; + case TagType.Int: + re.Write(Convert.ToInt32(value)); + break; + case TagType.UInt: + re.Write(Convert.ToUInt32(value)); + break; + case TagType.Long: + case TagType.ULong: + re.Write(Convert.ToInt64(value)); + break; + case TagType.Float: + re.Write(Convert.ToSingle(value)); + break; + case TagType.Double: + re.Write(Convert.ToDouble(value)); + break; + case TagType.String: + string sval = value.ToString(); + //re.WriteInt(sval.Length); + re.Write(sval, Encoding.Unicode); + break; + case TagType.DateTime: + re.Write(((DateTime)value).ToBinary()); + break; + case TagType.IntPoint: + re.Write(((IntPointData)value).X); + re.Write(((IntPointData)value).Y); + break; + case TagType.UIntPoint: + re.Write((int)((UIntPointData)value).X); + re.Write((int)((UIntPointData)value).Y); + break; + case TagType.IntPoint3: + re.Write(((IntPoint3Data)value).X); + re.Write(((IntPoint3Data)value).Y); + re.Write(((IntPoint3Data)value).Z); + break; + case TagType.UIntPoint3: + re.Write((int)((UIntPoint3Data)value).X); + re.Write((int)((UIntPoint3Data)value).Y); + re.Write((int)((UIntPoint3Data)value).Z); + break; + case TagType.LongPoint: + re.Write(((LongPointData)value).X); + re.Write(((LongPointData)value).Y); + break; + case TagType.ULongPoint: + re.Write((long)((ULongPointData)value).X); + re.Write((long)((ULongPointData)value).Y); + break; + case TagType.LongPoint3: + re.Write(((LongPoint3Data)value).X); + re.Write(((LongPoint3Data)value).Y); + re.Write(((LongPoint3Data)value).Z); + break; + case TagType.ULongPoint3: + re.Write((long)((ULongPoint3Data)value).X); + re.Write((long)((ULongPoint3Data)value).Y); + re.Write((long)((ULongPoint3Data)value).Z); + break; + } + re.WriteByte(quality); + } + + /// + /// + /// + /// + /// + /// + public override Task UpdateHisValue(HisDataRequest request, ServerCallContext context) + { + try + { + if (SecurityManager.Manager.IsLogin(request.Token)) + { + if (DirectAccessProxy.Proxy.IsConnected && DirectAccessProxy.Proxy.TagCach.Count > 0) + { + int size = 0; + + foreach (var vv in request.Value) + { + if (DirectAccessProxy.Proxy.TagCach.ContainsKey(vv.Tag)) + { + size += 9; + var vtg = DirectAccessProxy.Proxy.TagCach[vv.Tag]; + switch (vtg.Item2) + { + case (byte)(Cdy.Tag.TagType.Bool): + size += vv.Value.Count * (8 + 1 + 1); + break; + case (byte)(Cdy.Tag.TagType.Byte): + size += vv.Value.Count * (8 + 1 + 1); + break; + case (byte)(Cdy.Tag.TagType.Short): + size += vv.Value.Count * (8 + 2 + 1); + break; + case (byte)(Cdy.Tag.TagType.UShort): + size += vv.Value.Count * (8 + 2 + 1); + break; + case (byte)(Cdy.Tag.TagType.Int): + case (byte)(Cdy.Tag.TagType.UInt): + size += vv.Value.Count * (8 + 4 + 1); + break; + case (byte)(Cdy.Tag.TagType.Long): + case (byte)(Cdy.Tag.TagType.ULong): + size += vv.Value.Count * (8 + 8 + 1); + break; + case (byte)(Cdy.Tag.TagType.Double): + size += vv.Value.Count * (8 + 8 + 1); + break; + case (byte)(Cdy.Tag.TagType.Float): + size += vv.Value.Count * (8 + 4 + 1); + break; + case (byte)(Cdy.Tag.TagType.String): + size += vv.Value.Count * (8 + 258 + 1); + break; + case (byte)(Cdy.Tag.TagType.DateTime): + size += vv.Value.Count * (8 + 8 + 1); + break; + case (byte)(Cdy.Tag.TagType.IntPoint): + size += vv.Value.Count * (8 + 8 + 1); + break; + case (byte)(Cdy.Tag.TagType.IntPoint3): + size += vv.Value.Count * (8 + 12 + 1); + break; + case (byte)(Cdy.Tag.TagType.UIntPoint): + size += vv.Value.Count * (8 + 8 + 1); + break; + case (byte)(Cdy.Tag.TagType.UIntPoint3): + size += vv.Value.Count * (8 + 12 + 1); + break; + case (byte)(Cdy.Tag.TagType.LongPoint): + size += vv.Value.Count * (8 + 16 + 1); + break; + case (byte)(Cdy.Tag.TagType.LongPoint3): + size += vv.Value.Count * (8 + 24 + 1); + break; + case (byte)(Cdy.Tag.TagType.ULongPoint): + size += vv.Value.Count * (8 + 16 + 1); + break; + case (byte)(Cdy.Tag.TagType.ULongPoint3): + size += vv.Value.Count * (8 + 24 + 1); + break; + } + } + } + + hdb.CheckAndResize(size); + hdb.Clear(); + int valuegroupcount = 0; + lock (DirectAccessProxy.Proxy.HisSyncLocker) + { + foreach (var vv in request.Value) + { + if (DirectAccessProxy.Proxy.TagCach.ContainsKey(vv.Tag)) + { + valuegroupcount++; + var vtg = DirectAccessProxy.Proxy.TagCach[vv.Tag]; + hdb.Write(vtg.Item1); + hdb.Write(vv.Value.Count); + hdb.Write((byte)vtg.Item2); + + foreach (var val in vv.Value) + { + hdb.Write(val.Time); + SetTagValueToBuffer2((TagType)vtg.Item2, val.Value, (byte)val.Quality, hdb); + } + } + } + } + bool re = false; + if (hdb.Position > 0) + { + re = DirectAccessProxy.Proxy.UpdateHisData(hdb, valuegroupcount); + } + return Task.FromResult(new BoolReply() { Result = re, ErroMessage = re ? "" : "Send data failed" }); + } + else + { + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Connect server failed" }); + } + } + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Login failed" }); + } + catch(Exception ex) + { + Cdy.Tag.LoggerService.Service.Erro("DataService", $"UpdateHisValue: {ex.Message} {ex.StackTrace}"); + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = ex.Message }); + } + } + + /// + /// + /// + /// + /// + /// + public override Task Login(LoginRequest request, ServerCallContext context) + { + string Token = DirectAccessProxy.Proxy.Login(request.Name, request.Password); + if (!string.IsNullOrEmpty(Token)) + { + SecurityManager.Manager.CachUser(Token); + return Task.FromResult(new LoginReply() { Token = Token, Time = DateTime.UtcNow.ToBinary(), Timeout = SecurityManager.Manager.Timeout }); + } + else + return Task.FromResult(new LoginReply()); + } + + + /// + /// + /// + /// + /// + /// + public override Task Logout(LogoutRequest request, ServerCallContext context) + { + //Cdy.Tag.ServiceLocator.Locator.Resolve().Logout(request.Token); + SecurityManager.Manager.RemoveUser(request.Token); + return Task.FromResult(new BoolReply() { Result = true }); + } + + + /// + /// + /// + /// + /// + /// + public override Task Hart(HartRequest request, ServerCallContext context) + { + + var dt = DateTime.FromBinary(request.Time); + if ((DateTime.UtcNow - dt).TotalSeconds > SecurityManager.Manager.Timeout) + { + return Task.FromResult(new BoolReply() { Result = false, ErroMessage = "Login failed" }); + } + + SecurityManager.Manager.RefreshLogin(request.Token); + return Task.FromResult(new BoolReply() { Result = true }); + } + + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc/Startup.cs b/Driver/DirectAccess/DirectAccessGrpc/Startup.cs new file mode 100644 index 00000000..b9f013dd --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/Startup.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace DirectAccessGrpc +{ + public class Startup + { + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) + { + services.AddGrpc(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseEndpoints(endpoints => + { + endpoints.MapGrpcService(); + + endpoints.MapGet("/", async context => + { + await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); + }); + }); + DirectAccessProxy.Proxy.Start(); + } + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc/appsettings.Development.json b/Driver/DirectAccess/DirectAccessGrpc/appsettings.Development.json new file mode 100644 index 00000000..fe20c40c --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/appsettings.Development.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Grpc": "Information", + "Microsoft": "Information" + } + } +} diff --git a/Driver/DirectAccess/DirectAccessGrpc/appsettings.json b/Driver/DirectAccess/DirectAccessGrpc/appsettings.json new file mode 100644 index 00000000..1f292413 --- /dev/null +++ b/Driver/DirectAccess/DirectAccessGrpc/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*", + "Kestrel": { + "EndpointDefaults": { + "Protocols": "Http2" + } + } +} diff --git a/Driver/SpiderDriver.ClientApi/DriverProxy.cs b/Driver/SpiderDriver.ClientApi/DriverProxy.cs index 8bd4b6eb..035a012a 100644 --- a/Driver/SpiderDriver.ClientApi/DriverProxy.cs +++ b/Driver/SpiderDriver.ClientApi/DriverProxy.cs @@ -93,6 +93,19 @@ public class DriverProxy:Cdy.Tag.SocketClient2 #region ... Methods ... + /// + /// 心跳 + /// + public void Hart() + { + lock (mTagInfoLockObj) + { + var mb = GetBuffer(ApiFunConst.TagInfoRequestFun, 2); + mb.Write(ApiFunConst.Hart); + SendData(mb); + } + } + /// /// 退出登录 /// @@ -279,6 +292,19 @@ private Dictionary ProcessSingleBufferData(ByteBuffer block) return re; } + /// + /// 删除并释放缓存 + /// + /// + private void ClearData(Queue datas) + { + while(mInfoRequreData.Count>0) + { + var vdata = mInfoRequreData.Dequeue(); + vdata?.UnlockAndReturn(); + } + } + /// /// 登录 /// @@ -290,7 +316,7 @@ public bool Login(string username, string password, int timeount = 5000) { lock (mTagInfoLockObj) { - mInfoRequreData.Clear(); + ClearData(mInfoRequreData); mUser = username; mPass = password; int size = username.Length + password.Length + 9; @@ -354,6 +380,8 @@ private void CheckLogin() } } + #region 实时值相关 + ///// ///// ///// @@ -871,32 +899,128 @@ public bool SetTagRealAndHisValueAsync(RealDataBuffer data, int timeout = 5000) return true; } + ///// + ///// 设置变量的实时、历史值 + ///// 历史值只有在变量的记录类型为:驱动时起作用 + ///// + ///// + ///// + ///// + //public bool SetTagRealAndHisValueAsync2(RealDataBuffer data) + //{ + // //CheckLogin(); + + // if (data.Position <= 0 || mIsRealDataBusy) return false; + + // var mb = GetBuffer(ApiFunConst.RealValueFun, 14 + (int)data.Position+64); + // mb.Write(ApiFunConst.SetTagRealAndHisValueWithUserFun); + // mb.Write(this.mUser); + // mb.Write(this.mPass); + // mb.Write(data.ValueCount); + + // mb.Write(data.Buffers, (int)data.Position); + // //System.Runtime.InteropServices.Marshal.Copy(data.Buffers, mb.Array, mb.ArrayOffset + mb.WriterIndex, (int)data.Position); + // //mb.SetWriterIndex((int)(mb.WriterIndex + data.Position)); + // SendData(mb); + // return true; + //} + /// /// 设置变量的实时、历史值 /// 历史值只有在变量的记录类型为:驱动时起作用 /// - /// + /// /// /// - public bool SetTagRealAndHisValueAsync2(RealDataBuffer data) + public bool SetTagRealAndHisValue(List ids, int timeout = 5000) { - //CheckLogin(); + CheckLogin(); + if (mIsRealDataBusy) return false; - if (data.Position <= 0 || mIsRealDataBusy) return false; + var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + ids.Count * 32); + mb.Write(ApiFunConst.SetTagRealAndHisValueFun); + mb.Write(this.mLoginId); + mb.Write(ids.Count); + foreach (var vv in ids) + { + mb.Write(vv.Id); + SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); + } + realRequreEvent.Reset(); + SendData(mb); - var mb = GetBuffer(ApiFunConst.RealValueFun, 14 + (int)data.Position+64); + if (realRequreEvent.WaitOne(timeout)) + { + try + { + return mRealRequreData != null && mRealRequreData.ReadableCount > 1; + } + catch + { + mRealRequreData?.UnlockAndReturn(); + } + + } + + + return false; + } + + /// + /// 设置变量的实时、历史值 + /// 历史值只有在变量的记录类型为:驱动时起作用 + /// + /// + /// + /// + public bool SetTagRealAndHisValueAsync(List ids, int timeout = 5000) + { + CheckLogin(); + if (mIsRealDataBusy) return false; + + var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + ids.Count * 32); + mb.Write(ApiFunConst.SetTagRealAndHisValueFun); + mb.Write(this.mLoginId); + mb.Write(ids.Count); + foreach (var vv in ids) + { + mb.Write(vv.Id); + SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); + } + realRequreEvent.Reset(); + SendData(mb); + + return IsConnected; + } + + /// + /// 设置变量的实时、历史值 + /// 历史值只有在变量的记录类型为:驱动时起作用 + /// + /// + /// + /// + public bool SetTagRealAndHisValue2(List ids) + { + //CheckLogin(); + if (mIsRealDataBusy) return false; + + var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + ids.Count * (32 + 64) + 64); mb.Write(ApiFunConst.SetTagRealAndHisValueWithUserFun); mb.Write(this.mUser); mb.Write(this.mPass); - mb.Write(data.ValueCount); - - mb.Write(data.Buffers, (int)data.Position); - //System.Runtime.InteropServices.Marshal.Copy(data.Buffers, mb.Array, mb.ArrayOffset + mb.WriterIndex, (int)data.Position); - //mb.SetWriterIndex((int)(mb.WriterIndex + data.Position)); + mb.Write(ids.Count); + foreach (var vv in ids) + { + mb.Write(vv.Id); + SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); + } SendData(mb); - return true; + return IsConnected; } + + /// /// 设置一组变量的实时值 /// @@ -1008,77 +1132,33 @@ public bool SetTagValueAndQualityAsync(RealDataBuffer data, int timeout = 5000) return true; } - /// - /// 设置一组变量的实时值, - /// 立即返回 - /// - /// - /// - /// - public bool SetTagValueAndQualityAsync2(RealDataBuffer data) - { - //CheckLogin(); - if (mIsRealDataBusy) return false; - - var mb = GetBuffer(ApiFunConst.RealValueFun, 14 + (int)data.Position+64); - mb.Write(ApiFunConst.SetTagValueAndQualityWithUserFun); - mb.Write(this.mUser); - mb.Write(this.mPass); - mb.Write(data.ValueCount); - - mb.Write(data.Buffers, (int)data.Position); - - //realRequreEvent.Reset(); - SendData(mb); + ///// + ///// 设置一组变量的实时值, + ///// + ///// + ///// + ///// + //public bool SetTagValueAndQualityAsync2(RealDataBuffer data) + //{ + // //CheckLogin(); + // if (mIsRealDataBusy) return false; - return true; - } - + // var mb = GetBuffer(ApiFunConst.RealValueFun, 14 + (int)data.Position+64); + // mb.Write(ApiFunConst.SetTagValueAndQualityWithUserFun); + // mb.Write(this.mUser); + // mb.Write(this.mPass); + // mb.Write(data.ValueCount); - /// - /// - /// - /// - /// - /// - public bool SetTagRealAndHisValue(List ids, int timeout = 5000) - { - CheckLogin(); - if (mIsRealDataBusy) return false; + // mb.Write(data.Buffers, (int)data.Position); - var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + ids.Count * 32); - mb.Write(ApiFunConst.SetTagRealAndHisValueFun); - mb.Write(this.mLoginId); - mb.Write(ids.Count); - foreach (var vv in ids) - { - mb.Write(vv.Id); - SetTagValueToBuffer((TagType)vv.ValueType, vv.Value,vv.Quality, mb); - } - realRequreEvent.Reset(); - SendData(mb); - - if (realRequreEvent.WaitOne(timeout)) - { - try - { - return mRealRequreData != null && mRealRequreData.ReadableCount > 1; - } - catch - { - mRealRequreData?.UnlockAndReturn(); - } - - } - - - return false; - } + // //realRequreEvent.Reset(); + // SendData(mb); + // return true; + //} /// - /// 设置变量的实时、历史值 - /// 历史值只有在变量的记录类型为:驱动时起作用 + /// 设置变量的实时 /// /// ID,值类型,值,质量 /// @@ -1095,7 +1175,7 @@ public bool SetTagValueAndQuality(List values, int timeout = 5000) foreach (var vv in values) { mb.Write(vv.Id); - SetTagValueToBuffer((TagType)vv.ValueType, vv.Value,vv.Quality, mb); + SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); } realRequreEvent.Reset(); SendData(mb); @@ -1109,59 +1189,19 @@ public bool SetTagValueAndQuality(List values, int timeout = 5000) catch { mRealRequreData?.UnlockAndReturn(); - + } - + } - + return false; } - /// - /// - /// - /// - /// - /// - public bool SetTagRealAndHisValue2(List ids) - { - //CheckLogin(); - if (mIsRealDataBusy) return false; - - var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + ids.Count * (32+64)+64); - mb.Write(ApiFunConst.SetTagRealAndHisValueWithUserFun); - mb.Write(this.mUser); - mb.Write(this.mPass); - mb.Write(ids.Count); - foreach (var vv in ids) - { - mb.Write(vv.Id); - SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); - } - //realRequreEvent.Reset(); - SendData(mb); - return IsConnected; - //if (realRequreEvent.WaitOne(timeout)) - //{ - // try - // { - // return mRealRequreData != null && mRealRequreData.ReadableCount > 1; - // } - // catch - // { - // mRealRequreData?.UnlockAndReturn(); - // } - - //} - - //return false; - } /// - /// 设置变量的实时、历史值 - /// 历史值只有在变量的记录类型为:驱动时起作用 + /// 设置变量的实时 /// /// ID,值类型,值,质量 /// @@ -1171,7 +1211,7 @@ public bool SetTagValueAndQuality2(List values) //CheckLogin(); if (mIsRealDataBusy) return false; - var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + values.Count * (32+64)+64); + var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + values.Count * (32 + 64) + 64); mb.Write(ApiFunConst.SetTagValueAndQualityWithUserFun); mb.Write(this.mUser); mb.Write(this.mPass); @@ -1202,9 +1242,9 @@ public bool SetTagValueAndQuality2(List values) //return false; } + /// - /// 设置变量的实时、历史值. - /// 历史值只有在变量的记录类型为:驱动时起作用 + /// 设置变量的实时 /// 立即返回 /// /// ID,值类型,值,质量 @@ -1228,31 +1268,31 @@ public bool SetTagValueAndQualityAsync(List values, int timeout = return true; } - /// - /// 设置变量的实时、历史值. - /// 历史值只有在变量的记录类型为:驱动时起作用 - /// 立即返回 - /// - /// ID,值类型,值,质量 - /// - public bool SetTagValueAndQualityAsync2(List values) - { - //CheckLogin(); - if (mIsRealDataBusy) return false; - var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + values.Count * (32+64)+64); - mb.Write(ApiFunConst.SetTagValueAndQualityWithUserFun); - mb.Write(this.mUser); - mb.Write(this.mPass); - mb.Write(values.Count); - foreach (var vv in values) - { - mb.Write(vv.Id); - SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); - } - //realRequreEvent.Reset(); - SendData(mb); - return true; - } + ///// + ///// 设置变量的实时、历史值. + ///// 历史值只有在变量的记录类型为:驱动时起作用 + ///// 立即返回 + ///// + ///// ID,值类型,值,质量 + ///// + //public bool SetTagValueAndQualityAsync2(List values) + //{ + // //CheckLogin(); + // if (mIsRealDataBusy) return false; + // var mb = GetBuffer(ApiFunConst.RealValueFun, 13 + values.Count * (32+64)+64); + // mb.Write(ApiFunConst.SetTagValueAndQualityWithUserFun); + // mb.Write(this.mUser); + // mb.Write(this.mPass); + // mb.Write(values.Count); + // foreach (var vv in values) + // { + // mb.Write(vv.Id); + // SetTagValueToBuffer((TagType)vv.ValueType, vv.Value, vv.Quality, mb); + // } + // //realRequreEvent.Reset(); + // SendData(mb); + // return true; + //} /// /// 订购指定变量的值改变通知信息 @@ -1292,7 +1332,7 @@ public bool AppendRegistorDataChangedCallBack(IEnumerable ids,int timeout=5 /// /// 取消订购指定变量的值改变通知信息 /// - /// + /// 变量Id的集合 /// /// public bool UnRegistorDataChangedCallBack(IEnumerable ids, int timeout = 5000) @@ -1356,6 +1396,7 @@ public bool ResetRegistorDataChangedCallBack(int timeout = 5000) return false; } + #endregion /// /// 设置变量的一组历史值 @@ -1810,7 +1851,7 @@ public List QueryTagId(IEnumerable tags,int timeout = 5000) { lock (mTagInfoLockObj) { - mInfoRequreData.Clear(); + ClearData(mInfoRequreData); List re = new List(); CheckLogin(); var mb = GetBuffer(ApiFunConst.TagInfoRequestFun, 13 + tags.Count() * 256); @@ -1888,6 +1929,7 @@ public Dictionary> QueryAllTagIdAndNames(int timeout = { lock (mTagInfoLockObj) { + ClearData(mInfoRequreData); Dictionary> re = new Dictionary>(); CheckLogin(); var mb = GetBuffer(ApiFunConst.TagInfoRequestFun, 9); @@ -1983,6 +2025,7 @@ public List GetDriverRecordTypeTagIds(int timeout = 5000) { lock (mTagInfoLockObj) { + ClearData(mInfoRequreData); List re = new List(); CheckLogin(); var mb = GetBuffer(ApiFunConst.TagInfoRequestFun, 9); @@ -2065,6 +2108,7 @@ public List CheckRecordTypeByTagId(IEnumerable ids, int timeout = 500 { lock (mTagInfoLockObj) { + ClearData(mInfoRequreData); List re = new List(); CheckLogin(); var mb = GetBuffer(ApiFunConst.TagInfoRequestFun, 13 + ids.Count() * 4); diff --git a/Driver/SpiderDriver.ClientApi/HisDataBuffer.cs b/Driver/SpiderDriver.ClientApi/HisDataBuffer.cs index 7bb1d38a..d6234945 100644 --- a/Driver/SpiderDriver.ClientApi/HisDataBuffer.cs +++ b/Driver/SpiderDriver.ClientApi/HisDataBuffer.cs @@ -1071,6 +1071,7 @@ public byte[] ReadBytes(int len) public HisDataBuffer AppendValue(DateTime time,double value,byte quality) { ValueCount++; + CheckAndResize(Position + 17); this.WriteLong(Position, time.ToBinary()); this.WriteDouble(Position, value); this.WriteByte(Position, quality); @@ -1085,6 +1086,7 @@ public HisDataBuffer AppendValue(DateTime time,double value,byte quality) public HisDataBuffer AppendValue(int id, DateTime time, double value,byte quality) { ValueCount++; + CheckAndResize(Position + 22); this.WriteInt(Position, id); this.WriteLong(Position, time.ToBinary()); this.WriteByte(Position, (byte)TagType.Double); @@ -1102,6 +1104,7 @@ public HisDataBuffer AppendValue(int id, DateTime time, double value,byte qualit public HisDataBuffer AppendValue(DateTime time, float value, byte quality) { ValueCount++; + CheckAndResize(Position + 13); this.WriteLong(Position, time.ToBinary()); this.WriteFloat(Position, value); this.WriteByte(Position, quality); @@ -1116,6 +1119,7 @@ public HisDataBuffer AppendValue(DateTime time, float value, byte quality) public HisDataBuffer AppendValue(int id, DateTime time, float value, byte quality) { ValueCount++; + CheckAndResize(Position + 18); this.WriteInt(Position, id); this.WriteLong(Position, time.ToBinary()); this.WriteByte(Position, (byte)TagType.Float); @@ -1134,6 +1138,7 @@ public HisDataBuffer AppendValue(int id, DateTime time, float value, byte qualit public HisDataBuffer AppendValue(DateTime time, int value, byte quality) { ValueCount++; + CheckAndResize(Position + 13); this.WriteLong(Position, time.ToBinary()); this.WriteInt(Position, value); this.WriteByte(Position, quality); @@ -1148,6 +1153,7 @@ public HisDataBuffer AppendValue(DateTime time, int value, byte quality) public HisDataBuffer AppendValue(int id, DateTime time, int value, byte quality) { ValueCount++; + CheckAndResize(Position + 18); this.WriteInt(Position, id); this.WriteLong(Position, time.ToBinary()); this.WriteByte(Position, (byte)TagType.Int); @@ -1165,6 +1171,7 @@ public HisDataBuffer AppendValue(int id, DateTime time, int value, byte quality) public HisDataBuffer AppendValue(DateTime time, uint value, byte quality) { ValueCount++; + CheckAndResize(Position + 13); this.WriteLong(Position, time.ToBinary()); this.WriteUInt(Position, value); this.WriteByte(Position, quality); @@ -1180,6 +1187,7 @@ public HisDataBuffer AppendValue(DateTime time, uint value, byte quality) public HisDataBuffer AppendValue(int id, DateTime time, uint value, byte quality) { ValueCount++; + CheckAndResize(Position + 18); this.WriteInt(Position, id); this.WriteLong(Position, time.ToBinary()); this.WriteByte(Position, (byte)TagType.UInt); @@ -1198,6 +1206,7 @@ public HisDataBuffer AppendValue(int id, DateTime time, uint value, byte quality public HisDataBuffer AppendValue(DateTime time, short value, byte quality) { ValueCount++; + CheckAndResize(Position + 11); this.WriteLong(Position, time.ToBinary()); this.WriteShort(Position, value); this.WriteByte(Position, quality); @@ -1213,6 +1222,7 @@ public HisDataBuffer AppendValue(DateTime time, short value, byte quality) public HisDataBuffer AppendValue(int id, DateTime time, short value, byte quality) { ValueCount++; + CheckAndResize(Position + 16); this.WriteInt(Position, id); this.WriteLong(Position, time.ToBinary()); this.WriteByte(Position, (byte)TagType.Short); @@ -1230,6 +1240,7 @@ public HisDataBuffer AppendValue(int id, DateTime time, short value, byte qualit public HisDataBuffer AppendValue(DateTime time, ushort value, byte quality) { ValueCount++; + CheckAndResize(Position + 11); this.WriteLong(Position, time.ToBinary()); this.WriteUShort(Position, value); this.WriteByte(Position, quality); @@ -1245,6 +1256,7 @@ public HisDataBuffer AppendValue(DateTime time, ushort value, byte quality) public HisDataBuffer AppendValue(int id, DateTime time, ushort value, byte quality) { ValueCount++; + CheckAndResize(Position + 16); this.WriteInt(Position, id); this.WriteLong(Position, time.ToBinary()); this.WriteByte(Position, (byte)TagType.UShort); @@ -1296,7 +1308,7 @@ public HisDataBuffer AppendValue(int id, DateTime time, byte value, byte quality public HisDataBuffer AppendValue(DateTime time, long value, byte quality) { ValueCount++; - CheckAndResize(Position + 15); + CheckAndResize(Position + 17); this.WriteLong(Position, time.ToBinary()); this.WriteLong(Position, value); this.WriteByte(Position, quality); diff --git a/Driver/SpiderDriver.ClientApi/SpiderDriver.ClientApi.csproj b/Driver/SpiderDriver.ClientApi/SpiderDriver.ClientApi.csproj index ad09f352..675d5c3e 100644 --- a/Driver/SpiderDriver.ClientApi/SpiderDriver.ClientApi.csproj +++ b/Driver/SpiderDriver.ClientApi/SpiderDriver.ClientApi.csproj @@ -6,10 +6,10 @@ chongdaoyang Mars https://github.com/cdy816/mars - 1.2.0 - 1.2.0.0 - 1.2.0.0 - true + 1.3.1 + 1.3.1.0 + 1.3.1.0 + false false Spider driver develop api of mars database. diff --git a/Driver/SpiderDriver/TagInfoServerProcess.cs b/Driver/SpiderDriver/TagInfoServerProcess.cs index 197b961d..737d0c60 100644 --- a/Driver/SpiderDriver/TagInfoServerProcess.cs +++ b/Driver/SpiderDriver/TagInfoServerProcess.cs @@ -34,6 +34,8 @@ public class TagInfoServerProcess : ServerProcessBase public const byte Login = 1; + public const byte Hart = 255; + private Dictionary mClients = new Dictionary(); #endregion ...Variables... @@ -231,7 +233,8 @@ protected unsafe override void ProcessSingleData(string client, ByteBuffer data) { LoggerService.Service.Erro("SpiderDriver",$"{eex.Message}:{eex.StackTrace}" ); } - + break; + case Hart: break; } diff --git a/Example/Consumer/DBGrpcApiDemo/MainViewModel.cs b/Example/Consumer/DBGrpcApiDemo/MainViewModel.cs index 6318e036..b5eb9e0c 100644 --- a/Example/Consumer/DBGrpcApiDemo/MainViewModel.cs +++ b/Example/Consumer/DBGrpcApiDemo/MainViewModel.cs @@ -235,7 +235,13 @@ public ICommand SetTagValueCommand { mSetTagValueCommand = new RelayCommand(() => { - clinet.SetTagValue(Id, Value); + Dictionary values = new Dictionary(); + string[] ss = Id.Split(","); + foreach(var vv in ss) + { + values.Add(vv, Value.ToString()); + } + clinet.SetTagValue(values); }); } return mSetTagValueCommand; diff --git a/Example/Consumer/DBGrpcApiDemo/MainWindow.xaml b/Example/Consumer/DBGrpcApiDemo/MainWindow.xaml index ddc8b46a..f7f4ad45 100644 --- a/Example/Consumer/DBGrpcApiDemo/MainWindow.xaml +++ b/Example/Consumer/DBGrpcApiDemo/MainWindow.xaml @@ -32,11 +32,11 @@ - private void Init() { - for(int i=1;i<1000;i++) + mIds = new List(); + for(int i=1;i<100000;i++) { mTags.Add(new TagItemInfo() { Id = i, Value = "0" }); + mIds.Add(i); } clinet = new DBHighApi.ApiClient(); clinet.TagValueChangedCallBack = (val) => @@ -179,15 +183,27 @@ private void Clinet_PropertyChanged(object sender, PropertyChangedEventArgs e) { if(clinet.IsConnected) { - clinet.Login("Admin", "Admin"); - clinet.RegistorTagValueCallBack(500, 999); - mScanThread = new Thread(ScanProcess); - mScanThread.IsBackground = true; - mScanThread.Start(); + Task.Run(() => { + clinet.Login("Admin", "Admin"); + clinet.RegistorTagValueCallBack(500, 999); + InitFunTest(); + mScanThread = new Thread(ScanProcess); + mScanThread.IsBackground = true; + mScanThread.Start(); + }); + } } } + private void InitFunTest() + { + clinet.GetTagIds(new List() { "Double.Double1" }); + clinet.ListAllTag(); + var grps = clinet.ListALlTagGroup(); + clinet.ListTagByGroup("Double"); + } + /// /// /// @@ -205,7 +221,7 @@ private void ScanProcess() while (!mExited) { UpdateValue(); - Thread.Sleep(1000); + Thread.Sleep(500); } } @@ -214,14 +230,52 @@ private void ScanProcess() /// private void UpdateValue() { - if (!clinet.IsLogin) return; - var vals = clinet.GetRealDataValueOnly(0, 500); + if (!clinet.IsLogin) + { + clinet.Login("Admin", "Admin"); + return; + } + Stopwatch sw = new Stopwatch(); + sw.Start(); + + var vals = clinet.GetRealDataValueOnly(mIds,true); + sw.Stop(); + Debug.WriteLine($"time : { sw.ElapsedMilliseconds }"); if (vals != null) { - for (int i = 0; i < 500; i++) + for (int i = 0; i < 50000; i++) { if(vals.ContainsKey(i)) - mTags[i].Value = vals[i].ToString(); + mTags[i].Value = vals[i]?.ToString(); + } + } + + sw.Restart(); + + var avals = clinet.GetRealData(mIds, true); + sw.Stop(); + Debug.WriteLine($"time : { sw.ElapsedMilliseconds }"); + if (avals != null) + { + for (int i = 0; i < 50000; i++) + { + if (avals.ContainsKey(i)) + mTags[i].Value = avals[i].Item1?.ToString(); + } + } + + + sw.Restart(); + + var aqvals = clinet.GetRealDataValueAndQualityOnly(mIds, true); + sw.Stop(); + Debug.WriteLine($"time : { sw.ElapsedMilliseconds }"); + if (aqvals != null) + { + for (int i = 0; i < 50000; i++) + { + if (aqvals.ContainsKey(i)) + mTags[i].Value = aqvals[i].Item1?.ToString(); } } } diff --git a/Example/Producter/DirectAccessDriverApiDemo/App.xaml b/Example/Producter/DirectAccessDriverApiDemo/App.xaml new file mode 100644 index 00000000..933a6248 --- /dev/null +++ b/Example/Producter/DirectAccessDriverApiDemo/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/Example/Producter/DirectAccessDriverApiDemo/App.xaml.cs b/Example/Producter/DirectAccessDriverApiDemo/App.xaml.cs new file mode 100644 index 00000000..452dd2f1 --- /dev/null +++ b/Example/Producter/DirectAccessDriverApiDemo/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace DirectAccessDriverApiDemo +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/Example/Producter/DirectAccessDriverApiDemo/AssemblyInfo.cs b/Example/Producter/DirectAccessDriverApiDemo/AssemblyInfo.cs new file mode 100644 index 00000000..8b5504ec --- /dev/null +++ b/Example/Producter/DirectAccessDriverApiDemo/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/Example/Producter/DirectAccessDriverApiDemo/DirectAccessDriverApiDemo.csproj b/Example/Producter/DirectAccessDriverApiDemo/DirectAccessDriverApiDemo.csproj new file mode 100644 index 00000000..08d0360d --- /dev/null +++ b/Example/Producter/DirectAccessDriverApiDemo/DirectAccessDriverApiDemo.csproj @@ -0,0 +1,13 @@ + + + + WinExe + net5.0-windows + true + + + + + + + diff --git a/Example/Producter/DirectAccessDriverApiDemo/MainWindow.xaml b/Example/Producter/DirectAccessDriverApiDemo/MainWindow.xaml new file mode 100644 index 00000000..d0e846c5 --- /dev/null +++ b/Example/Producter/DirectAccessDriverApiDemo/MainWindow.xaml @@ -0,0 +1,79 @@ + + + + + + + + + + + + +