コード例 #1
0
        public static void InitDic()
        {
            RealData.Clear();
            FrontData.Clear();

            DataTable dt = DevicePoint.GetTagName();

            if (dt != null && dt.Rows.Count > 0)
            {
                string tagid = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    tagid = dt.Rows[i]["TagID"].ToString().Trim();

                    Log.Info("[ReadData Dic Add TagID:] " + tagid);
                    RealData.dic.Add(tagid, uint.MaxValue);

                    PLCHisData data = new PLCHisData();
                    data.Value = uint.MaxValue;
                    data.refid = 0;
                    data.TagID = tagid;
                    data.Time  = DateTime.Now;
                    data.type  = "";

                    FrontData.dic.Add(tagid, data);
                    Log.Info("[FrontData Dic Add TagID:] " + tagid);
                }
            }
        }
コード例 #2
0
        public int UpdatePoint(DevicePoint point)
        {
            if (point.id == null && this.db.DevicePointFolder.Any(m => m.Name == point.Name))
            {
                throw new Exception("点名已存在");
            }
            else if (point.id == null && this.db.DevicePointFolder.Any(m => m.id != point.id && m.Name == point.Name))
            {
                throw new Exception("点名已存在");
            }

            bool needRestartHistory = false;

            if (point.ChangedProperties.Any(m => m.Key.Contains("ValueOnTimeChange") || m.Key.Contains("ValueAbsoluteChange") || m.Key.Contains("ValueRelativeChange") || m.Key.Contains("IsAlarm")))
            {
                //需要重新启动历史保存
                needRestartHistory = true;
            }

            if (point.Type == DevicePoint_TypeEnum.Analog)
            {
                if (point.ValueAbsoluteChangeSetting < point.TransMin || point.ValueAbsoluteChangeSetting > point.TransMax)
                {
                    throw new Exception($"历史数据变化定义中,绝对值变化定义超出量程范围,量程范围目前为{point.TransMin } - {point.TransMax}");
                }
            }
            SystemHelper.AddSysLog(this.User.id.Value, "更新点“" + point.Name + "”信息:" + Newtonsoft.Json.JsonConvert.SerializeObject(point.ChangedProperties));

            this.db.Update(point);
            if (needRestartHistory)
            {
                HistoryRecord.HistoryAutoRec.ReStart();
            }
            return(point.id.Value);
        }
コード例 #3
0
        internal DigitalPointDocument(Device device, SolutionNode parent, DevicePoint dataModel, int folderId)
        {
            InitializeComponent();

            //报警组
            var items = new List <object>();

            for (int i = 0; i < 16; i++)
            {
                items.Add(new
                {
                    text  = (i + 1).ToString(),
                    value = (1 << i)
                });
            }
            cmd_AlarmGroup.ItemsSource = items;

            //安全区
            items = new List <object>();
            for (int i = 0; i < 26; i++)
            {
                items.Add(new
                {
                    text  = ((char)(((int)('A')) + i)).ToString(),
                    value = (1 << i)
                });
            }
            cmbSafeArea.ItemsSource = items;

            Controller = new PointDocumentController(this, gridProperty, device, DevicePoint_TypeEnum.Digital, parent, dataModel, folderId);
            this.Title = Controller.OriginalModel.Name;
        }
コード例 #4
0
        public DevicePointNode(DevicePoint point)
        {
            _point                 = point;
            this.Text              = point.Desc;
            point.PropertyChanged += Point_PropertyChanged;

            this.Icon                = "/Images/solution/point.png";
            this.ShowInTree          = false;
            this.DoublicClickHandler = doubleClick;

            this.ContextMenuItems.Add(new ContextMenuItem()
            {
                ClickHandler = (s, e) => doubleClick(s, e),
                Text         = "属性"
            });

            this.ContextMenuItems.Add(new ContextMenuItem()
            {
                ClickHandler = (s, e) => transformTest(),
                Text         = "值转换测试(正向)..."
            });

            this.ContextMenuItems.Add(new ContextMenuItem()
            {
                ClickHandler = (s, e) => transformBackTest(),
                Text         = "值转换测试(反向)..."
            });
        }
コード例 #5
0
        public PointDocumentController(BaseDocument container, Grid gridProperty, Device device, DevicePoint_TypeEnum type, SolutionNode parent, DevicePoint dataModel, int folderId)
        {
            _container    = container;
            _gridProperty = gridProperty;
            Device        = device;
            _parentNode   = parent;
            OriginalModel = dataModel;
            if (OriginalModel == null)
            {
                OriginalModel = new DevicePoint()
                {
                    Type     = type,
                    DeviceId = this.Device.id,
                    FolderId = folderId
                };
            }

            //复制一份,给刷新按钮使用
            _pointModel                  = OriginalModel.Clone <DevicePoint>();
            _container.DataContext       = _pointModel;
            _pointModel.PropertyChanged += _pointModel_PropertyChanged;
            if (_pointModel.AddrSetting.IsBlank() == false)
            {
                _PointJsonDict = _pointModel.AddrSetting.JsonToObject <Dictionary <string, string> >();
            }
            setPointPropertyInput();
        }
コード例 #6
0
        public static void DevicePoint_Start_AddRemoveAgents(DevicePoint __instance)
        {
            if (__instance.RecoverPoints.Count >= girlCount)
            {
                return;
            }

            for (var i = 3; i < girlCount; i++)
            {
                __instance.RecoverPoints.Add(__instance.RecoverPoints[0]);
            }
        }
コード例 #7
0
        public static void RefreshSheets()
        {
            List <ADMSheet>  sheets     = new List <ADMSheet>();
            PlayerActor      player     = Map.Instance.Player;
            PlayerController controller = player.PlayerController;

            DevicePoint[] devices = Object.FindObjectsOfType <DevicePoint>();

            if (devices != null && devices.Length > 0)
            {
                DevicePoint device = devices.FirstOrDefault(v => v.ID == 0);

                if (device != null)
                {
                    sheets.Add(new ADMSheet("数据终端", () =>
                    {
                        MapUIContainer.SystemMenuUI.IsActiveControl = false;

                        Manager.Resources.Instance.SoundPack.Play(SoundPack.SystemSE.BootDevice);
                        MapUIContainer.SetCommandLabelAcception(CommandLabel.AcceptionState.None);

                        player.CurrentDevicePoint = device;

                        MapUIContainer.RefreshCommands(0, player.DeviceCommandInfos);
                        MapUIContainer.SetActiveCommandList(true, "データ端末");
                        controller.ChangeState("DeviceMenu");
                    }));
                }
            }

            sheets.Add(MakeSheet(controller, /*"Item Box"*/ "物品箱", "ItemBox", MapUIContainer.ItemBoxUI));
            sheets.Add(MakeSheet(controller, /*"Bathing Outfits"*/ "更衣处", "DressRoom", MapUIContainer.DressRoomUI));
            sheets.Add(MakeSheet(controller, /*"Closet Outfits"*/ "服装棚", "ClothChange", MapUIContainer.ClosetUI));
            sheets.Add(MakeSheet(controller, /*"Shan's Shop"*/ "商店", null, MapUIContainer.ShopUI, true));

            sheets.Add(new ADMSheet(/*"Kitchen"*/ "灶台", () =>
            {
                MapUIContainer.SystemMenuUI.IsActiveControl = false;

                MapUIContainer.SetCommandLabelAcception(CommandLabel.AcceptionState.None);
                MapUIContainer.RefreshCommands(0, player.CookCommandInfos);
                MapUIContainer.SetActiveCommandList(true, "料理");
                controller.ChangeState("Kitchen");
            }));

            sheets.Add(MakeSheet(controller, /*"Pet Synthesis"*/ "宠物合成", "Craft", MapUIContainer.PetCraftUI, true));
            sheets.Add(MakeSheet(controller, /*"Medicine Table"*/ "制药台", "Craft", MapUIContainer.MedicineCraftUI, true));
            sheets.Add(MakeSheet(controller, /*"Jukebox"*/ "更改BGM", null, MapUIContainer.JukeBoxUI, true));

            sheet.SetSheets(sheets);
        }
コード例 #8
0
        protected override void OnUpdate(PlayerActor player, ref Actor.InputInfo info)
        {
            player.NavMeshAgent.set_velocity(info.move = Vector3.get_zero());
            if (MapUIContainer.FadeCanvas.IsFadeIn || !this._completeWait || MapUIContainer.FadeCanvas.IsFadeOut)
            {
                return;
            }
            DevicePoint currentDevicePoint = player.CurrentDevicePoint;

            if (Object.op_Inequality((Object)this._agent, (Object)null) && (this._agent.Animation.PlayingInLocoAnimation || currentDevicePoint.PlayingInAnimation || this.PlayingCameraAnimation) || this._onEndAction == null)
            {
                return;
            }
            this._onEndAction.OnNext(Unit.get_Default());
        }
コード例 #9
0
            static void OpenDeviceMenu()
            {
                DevicePoint[] devices = FindObjectsOfType <DevicePoint>();
                DevicePoint   device  = devices?.FirstOrDefault(v => v.ID == 0);

                if (device != null)
                {
                    PlayerActor player = Map.Instance.Player;
                    player.CurrentDevicePoint = device;

                    Resources.Instance.SoundPack.Play(SoundPack.SystemSE.BootDevice);
                    MapUIContainer.SetCommandLabelAcception(CommandLabel.AcceptionState.None);
                    MapUIContainer.RefreshCommands(0, player.DeviceCommandInfos);
                    MapUIContainer.SetActiveCommandList(true, "データ端末");
                    player.PlayerController.ChangeState("DeviceMenu");
                }
            }
コード例 #10
0
        public static void InitData()
        {
            EqpPoint.Clear();


            DataTable device = DevicePoint.GetDistinctDevice();

            if (device == null || device.Rows.Count == 0)
            {
            }
            else
            {
                string deviceid = "";
                for (int i = 0; i < device.Rows.Count; i++)
                {
                    deviceid = device.Rows[i]["deviceid"].ToString().Trim();
                    if (!string.IsNullOrEmpty(deviceid))
                    {
                        DataTable dt = DevicePoint.GetDataPointByDeviceID(deviceid);
                        if (dt == null || dt.Rows.Count == 0)
                        {
                        }
                        else
                        {
                            ArrayList list = new ArrayList();
                            for (int j = 0; j < dt.Rows.Count; j++)
                            {
                                RowDataPoint point = new RowDataPoint();
                                point.IP        = dt.Rows[j]["IP"].ToString().Trim();
                                point.TagID     = dt.Rows[j]["TagID"].ToString().Trim();
                                point.TagName   = dt.Rows[j]["TagName"].ToString().Trim();
                                point.type      = dt.Rows[j]["type"].ToString().Trim();
                                point.datatype  = Convert.ToInt32(dt.Rows[j]["dataType"].ToString().Trim());
                                point.dbNumber  = Convert.ToInt32(dt.Rows[j]["dbNumber"].ToString().Trim());
                                point.startByte = Convert.ToInt32(dt.Rows[j]["startByte"].ToString().Trim());
                                point.bitNumber = Convert.ToInt32(dt.Rows[j]["bitNumber"].ToString().Trim());
                                point.vartype   = Convert.ToInt32(dt.Rows[j]["varType"].ToString().Trim());
                                list.Add(point);
                            }
                            EqpPoint.Add(deviceid, list);
                        }
                    }
                }
            }
        }
コード例 #11
0
        public static void InitTagDic()
        {
            TagDic.Clear();

            DataTable dt = DevicePoint.GetTagData();

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TagData data = new TagData();
                    data.LineID   = dt.Rows[i]["LineID"].ToString().Trim();
                    data.DeviceID = dt.Rows[i]["DeviceID"].ToString().Trim();
                    data.TagID    = dt.Rows[i]["TagID"].ToString().Trim();
                    data.TagName  = dt.Rows[i]["TagName"].ToString().Trim();
                    data.type     = dt.Rows[i]["type"].ToString().Trim();
                    TagDic.Add(data.TagID, data);
                }
            }
        }
コード例 #12
0
ファイル: JobGetPLCData.cs プロジェクト: farmwang/ABIPLC
 public static void SetEQPRealDataMax(string eqpid)
 {
     try
     {
         if (string.IsNullOrEmpty(eqpid))
         {
             return;
         }
         DataTable dt = DevicePoint.GetTagIDByEqp(eqpid);
         if (dt != null && dt.Rows.Count > 0)
         {
             for (int i = 0; i < dt.Rows.Count; i++)
             {
                 RealData.dic[dt.Rows[i]["TagID"].ToString()] = uint.MaxValue;
             }
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex.ToString());
     }
 }
コード例 #13
0
        /// <summary>
        /// 写历史记录
        /// </summary>
        /// <param name="point"></param>
        /// <param name="value"></param>
        static void WriteHistory(DevicePoint point, double value)
        {
            if (hisDB == null)
            {
                return;
            }
            try
            {
                lock (hisDB)
                {
                    var data = new SunRizServer.History();
                    data.PointId = point.id;
                    data.Address = point.Name;
                    data.Time    = DateTime.Now;
                    data.Value   = value;
                    hisDB.Insert(data);

                    if ((DateTime.Now - LastHisTime).TotalMinutes >= 2)
                    {
                        hisDB.CommitTransaction();
                        LastHisTime = DateTime.Now;
                        hisDB.BeginTransaction();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Way.Lib.CLog log = new Way.Lib.CLog("HistoryAutoRec WriteHistory error"))
                {
                    log.Log(ex.ToString());
                }
                hisDB.Dispose();
                hisDB = null;
                SystemHelper.AddAlarm(new Alarm()
                {
                    Content = $"记录历史时,发生错误,错误信息:{ex.Message}"
                });
            }
        }
コード例 #14
0
        static Newtonsoft.Json.Linq.JObject GetJsonObject(DevicePoint point)
        {
            var detail = new Newtonsoft.Json.Linq.JObject();

            detail["IsSquare"]    = point.IsSquare.GetValueOrDefault();
            detail["IsTransform"] = point.IsTransform.GetValueOrDefault();
            detail["IsLinear"]    = point.IsLinear.GetValueOrDefault();
            detail["DPCount"]     = point.DPCount;
            if (point.IsTransform == true)
            {
                detail["SensorMax"] = point.SensorMax;
                detail["SensorMin"] = point.SensorMin;
            }
            if (point.IsLinear == true)
            {
                detail["LinearX1"] = point.LinearX1;
                detail["LinearX2"] = point.LinearX2;
                detail["LinearX3"] = point.LinearX3;
                detail["LinearX4"] = point.LinearX4;
                detail["LinearX5"] = point.LinearX5;
                detail["LinearX6"] = point.LinearX6;
                detail["LinearY1"] = point.LinearY1;
                detail["LinearY2"] = point.LinearY2;
                detail["LinearY3"] = point.LinearY3;
                detail["LinearY4"] = point.LinearY4;
                detail["LinearY5"] = point.LinearY5;
                detail["LinearY6"] = point.LinearY6;
            }
            var data = new Newtonsoft.Json.Linq.JObject();

            data["detail"] = detail;
            data["max"]    = point.TransMax;
            data["min"]    = point.TransMin;

            return(data);
        }
コード例 #15
0
 private void StartEventSeq(PlayerActor player)
 {
     if (Object.op_Inequality((Object)this._agent, (Object)null))
     {
         DevicePoint devicePoint = player.CurrentDevicePoint;
         AgentData   agentData   = Singleton <Game> .Instance.WorldData.AgentTable[devicePoint.ID];
         AgentActor  agent       = this._agent;
         if (agentData.PlayEnterScene)
         {
             return;
         }
         agentData.PlayEnterScene = true;
         int           personality    = agent.ChaControl.fileParam.personality;
         PoseKeyPair   appearId       = Singleton <Resources> .Instance.AgentProfile.PoseIDTable.AppearIDList[personality];
         PlayState     playState      = Singleton <Resources> .Instance.Animation.AgentActionAnimTable[appearId.postureID][appearId.poseID];
         ActorAnimInfo actorAnimInfo1 = new ActorAnimInfo()
         {
             layer          = playState.Layer,
             inEnableBlend  = playState.MainStateInfo.InStateInfo.EnableFade,
             inBlendSec     = playState.MainStateInfo.InStateInfo.FadeSecond,
             outEnableBlend = playState.MainStateInfo.OutStateInfo.EnableFade,
             outBlendSec    = playState.MainStateInfo.OutStateInfo.FadeSecond,
             directionType  = playState.DirectionType,
             endEnableBlend = playState.EndEnableBlend,
             endBlendSec    = playState.EndBlendRate
         };
         agent.Animation.AnimInfo = actorAnimInfo1;
         ActorAnimInfo   actorAnimInfo2  = actorAnimInfo1;
         AssetBundleInfo assetBundleInfo = playState.MainStateInfo.AssetBundleInfo;
         agent.ChangeAnimator((string)assetBundleInfo.assetbundle, (string)assetBundleInfo.asset);
         float  shapeBodyValue      = agent.ChaControl.GetShapeBodyValue(0);
         string heightParameterName = Singleton <Resources> .Instance.DefinePack.AnimatorParameter.HeightParameterName;
         agent.Animation.Animator.SetFloat(heightParameterName, shapeBodyValue);
         this._locator.SetFloat(heightParameterName, shapeBodyValue);
         agent.Animation.LoadEventKeyTable(appearId.postureID, appearId.poseID);
         agent.LoadEventItems(playState);
         agent.LoadEventParticles(appearId.postureID, appearId.poseID);
         agent.Animation.InitializeStates(playState.MainStateInfo.InStateInfo.StateInfos, playState.MainStateInfo.OutStateInfo.StateInfos, playState.MainStateInfo.AssetBundleInfo);
         Transform basePoint = devicePoint.PivotPoint;
         agent.Position = basePoint.get_position();
         agent.Rotation = basePoint.get_rotation();
         agent.Animation.PlayInLocoAnimation(actorAnimInfo2.inEnableBlend, actorAnimInfo2.inBlendSec, actorAnimInfo2.layer);
         devicePoint.PlayInAnimation();
         this._locator.set_speed(1f);
         this.PlayCameraAnimation(this._locator, personality);
         ObservableExtensions.Subscribe <Unit>(Observable.Take <Unit>((IObservable <M0>) this._onEndAction, 1), (System.Action <M0>)(__ =>
         {
             this.packData.Init();
             this.openData.FindLoad("0", agent.AgentData.param.charaID, 6);
             this.packData.SetParam((IParams)agent.AgentData, (IParams)player.PlayerData);
             this.packData.onComplete = (System.Action)(() =>
             {
                 if (agent.IsEvent)
                 {
                     agent.IsEvent = false;
                 }
                 if (!Manager.Config.GraphicData.CharasEntry[agent.ID])
                 {
                     this.packData.Release();
                     Singleton <Manager.ADV> .Instance.Captions.EndADV((System.Action)null);
                     devicePoint.PlayOutAnimation();
                     this.PlayCloseSE(player, basePoint);
                     ObservableExtensions.Subscribe <Unit>((IObservable <M0>)MapUIContainer.StartFade(FadeCanvas.PanelType.Blackout, (global::FadeType)0, 1f, true), (System.Action <M0>)(_ => {}), (System.Action)(() =>
                     {
                         Singleton <Manager.Map> .Instance.RemoveAgent(agent);
                         agent = (AgentActor)null;
                         ObservableExtensions.Subscribe <Unit>((IObservable <M0>)MapUIContainer.StartFade(FadeCanvas.PanelType.Blackout, (global::FadeType)1, 1f, true), (System.Action <M0>)(_ => {}), (System.Action)(() => this.Elapsed(player)));
                     }));
                 }
                 else
                 {
                     this.packData.Release();
                     Singleton <Manager.ADV> .Instance.Captions.EndADV((System.Action)null);
                     this.Elapsed(player);
                     devicePoint.PlayOutAnimation();
                     this.PlayCloseSE(player, basePoint);
                 }
             });
             Singleton <MapUIContainer> .Instance.OpenADV(this.openData, (IPack)this.packData);
         }));
     }
     else
     {
         ObservableExtensions.Subscribe <Unit>(Observable.Take <Unit>((IObservable <M0>) this._onEndAction, 1), (System.Action <M0>)(__ =>
         {
             player.CurrentDevicePoint = (DevicePoint)null;
             player.PlayerController.CommandArea.UpdateCollision(player);
             player.Controller.ChangeState("Normal");
         }));
     }
 }
コード例 #16
0
    private static DeviceFile FromGPXV1_Base(XmlDocument document, decimal lapIntervalMeters)
    {
        var nav = document.CreateNavigator();

        nav.MoveToFollowing(XPathNodeType.Element);
        if (nav == null)
        {
            throw new Exception("File Type Not Supported");
        }

        var namespaces = nav.GetNamespacesInScope(XmlNamespaceScope.Local);

        if (namespaces == null || !namespaces.Keys.Any())
        {
            throw new Exception("File Type Not Supported");
        }

        var namespacePrefixes =
            namespaces.Join(
                ValidNamespaces,
                o => o.Value.ToLower(),
                i => i.Value.ToLower(),
                (i, o) => new { Type = o.Key, Prefix = string.IsNullOrWhiteSpace(i.Key) ? "gpx" : i.Key, Url = o.Value })
            .ToList();

        var prefixGpx           = namespacePrefixes.Single(x => x.Type == NamespaceType.GPX).Prefix;
        var prefixTrackPointExt = namespacePrefixes.SingleOrDefault(x => x.Type == NamespaceType.TrackPointExtensions)?.Prefix;
        var prefixCluetrustExt  = namespacePrefixes.SingleOrDefault(x => x.Type == NamespaceType.CluetrustExtensions)?.Prefix;

        var namespaceManager = new XmlNamespaceManager(document.NameTable);

        namespacePrefixes.ForEach(x => namespaceManager.AddNamespace(x.Prefix, x.Url));
        XMLParserHelper.Manager = namespaceManager;

        var creator = new DeviceCreator
        {
            Name =
                XMLParserHelper.SelectSingleAttributeString(
                    document.DocumentElement,
                    "creator"),
            Version =
                XMLParserHelper.SelectSingleAttributeString(
                    document.DocumentElement,
                    "version")
        };

        var author = new DeviceAuthor {
            Name = creator.Name, Version = creator.Version
        };

        var file = new DeviceFile();

        file.Author = author;
        DateTimeOffset dtoFileTime;
        DateTime?      fileTime       = null;
        var            fileTimeString = XMLParserHelper.SelectSingleTextString(document, $"/{prefixGpx}:gpx/{prefixGpx}:metadata/{prefixGpx}:time");

        if (!string.IsNullOrWhiteSpace(fileTimeString) && DateTimeOffset.TryParse(fileTimeString, out dtoFileTime))
        {
            // TODO: dtoFileTime = FSSecurity.Current.ToUserTime(dtoFileTime);
            fileTime = dtoFileTime.DateTime;
        }

        // Walk through all tracks and assign to Activities; usually just 1...
        var activityNodes = document.GetElementsByTagName("trk");

        foreach (XmlNode activityNode in activityNodes)
        {
            var activity = new DeviceActivity();
            file.Activities.Add(activity);

            activity.Id           = XMLParserHelper.SelectSingleTextString(activityNode, $"{prefixGpx}:name");
            activity.Creator      = creator;
            activity.Sport        = XMLParserHelper.SelectSingleTextString(activityNode, $"{prefixGpx}:type", "Unknown");
            activity.ActivityTime = fileTime;

            // Parse entire list of track points...
            var allTrackPoints  = new List <DevicePoint>();
            var trackPointNodes = activityNode.SelectNodes($"{prefixGpx}:trkseg/{prefixGpx}:trkpt", namespaceManager);
            if (trackPointNodes != null)
            {
                DateTime?activityStartTimeUtc = null;
                foreach (XmlNode trackPointNode in trackPointNodes)
                {
                    var point        = new DevicePoint();
                    var pointTimeUtc = XMLParserHelper.SelectSingleTextDateTime(trackPointNode, $"{prefixGpx}:time");
                    if (pointTimeUtc != null)
                    {
                        if (activityStartTimeUtc == null)
                        {
                            activityStartTimeUtc = pointTimeUtc;
                            point.StartSeconds   = 0;
                            point.Distance       = 0;
                        }
                        else
                        {
                            point.StartSeconds = (pointTimeUtc.Value - activityStartTimeUtc.Value.AddSeconds(1)).TotalSeconds;
                        }
                    }

                    // Parse latitude / longitude...
                    point.Latitude  = XMLParserHelper.SelectSingleAttributeDecimal(trackPointNode, "lat");
                    point.Longitude = XMLParserHelper.SelectSingleAttributeDecimal(trackPointNode, "lon");

                    // Parse altitude...
                    point.Altitude = XMLParserHelper.SelectSingleTextDecimal(
                        trackPointNode,
                        $"{prefixGpx}:ele");

                    // Parse TrackPoint extension data...
                    if (prefixTrackPointExt != null)
                    {
                        // Parse heart rate...
                        point.HR = XMLParserHelper.SelectSingleTextInt(
                            trackPointNode,
                            $"{prefixGpx}:extensions/{prefixTrackPointExt}:TrackPointExtension/{prefixTrackPointExt}:hr");

                        // Parse ambient temp...
                        point.Temp = XMLParserHelper.SelectSingleTextInt(
                            trackPointNode,
                            $"{prefixGpx}:extensions/{prefixTrackPointExt}:TrackPointExtension/{prefixTrackPointExt}:atemp");

                        // Parse cadence...
                        point.CAD = XMLParserHelper.SelectSingleTextInt(
                            trackPointNode,
                            $"{prefixGpx}:extensions/{prefixTrackPointExt}:TrackPointExtension/{prefixTrackPointExt}:cad");
                    }

                    // Parse Cluetrust extension data...
                    if (prefixCluetrustExt != null)
                    {
                        // Parse heart rate...
                        if (point.HR == null)
                        {
                            point.HR = XMLParserHelper.SelectSingleTextInt(trackPointNode, $"{prefixGpx}:extensions/{prefixCluetrustExt}:hr");
                        }

                        // Parse ambient temp...
                        if (point.Temp == null)
                        {
                            point.Temp = XMLParserHelper.SelectSingleTextInt(trackPointNode, $"{prefixGpx}:extensions/{prefixCluetrustExt}:temp");
                        }

                        // Parse cadence...
                        if (point.CAD == null)
                        {
                            point.CAD = XMLParserHelper.SelectSingleTextInt(trackPointNode, $"{prefixGpx}:extensions/{prefixCluetrustExt}:cadence");
                        }
                    }

                    // Parse any generic extensions data...
                    // Parse heart rate...
                    if (point.HR == null)
                    {
                        point.HR = XMLParserHelper.SelectSingleTextInt(trackPointNode, $"{prefixGpx}:extensions/{prefixGpx}:heartrate");
                    }

                    // Parse cadence...
                    if (point.CAD == null)
                    {
                        point.CAD = XMLParserHelper.SelectSingleTextInt(trackPointNode, $"{prefixGpx}:extensions/{prefixGpx}:cadence");
                    }

                    // Parse distance...
                    if (point.Distance == null)
                    {
                        point.Distance = XMLParserHelper.SelectSingleTextDecimal(trackPointNode, $"{prefixGpx}:extensions/{prefixGpx}:distance");
                    }

                    // Parse power...
                    if (point.Watts == null)
                    {
                        point.Watts = XMLParserHelper.SelectSingleTextInt(trackPointNode, $"{prefixGpx}:extensions/{prefixGpx}:power");
                    }

                    // Multiply CAD result x 2 like in TCX?
                    // TODO: Bike no...Run yes?
                    if (point.CAD != null)
                    {
                        point.CAD = point.CAD * 2;
                    }

                    allTrackPoints.Add(point);
                }
            }

            // Re-run through point list to calculate distances and break up into laps...
            var pointsHaveTimeInfo = allTrackPoints.All(p => p.StartSeconds.HasValue);
            var lapList            = new List <DeviceLap>();
            var currentLap         = new DeviceLap {
                StartSeconds = pointsHaveTimeInfo ? (double?)0 : null
            };
            for (var i = 1; i < allTrackPoints.Count; i++)
            {
                var currentPoint  = allTrackPoints[i];
                var previousPoint = allTrackPoints[i - 1];

                if (currentLap.Track.Count == 0)
                {
                    var previousLap = activity.Laps.LastOrDefault();
                    if (previousLap != null && pointsHaveTimeInfo)
                    {
                        previousLap.Time = (decimal)(currentPoint.StartSeconds.Value - previousLap.StartSeconds.Value);
                    }

                    activity.Laps.Add(currentLap);
                }

                decimal?currentPointDistanceDelta = null;
                if (currentPoint.Distance == null)
                {
                    if (currentPoint.Latitude == null ||
                        currentPoint.Longitude == null ||
                        previousPoint.Latitude == null ||
                        previousPoint.Longitude == null)
                    {
                        continue;
                    }

                    var distanceKm = HaversineInKM(
                        (double)previousPoint.Latitude.Value,
                        (double)previousPoint.Longitude.Value,
                        (double)currentPoint.Latitude.Value,
                        (double)currentPoint.Longitude.Value);

                    currentPointDistanceDelta = (decimal)(distanceKm * 1000.0);
                    currentPoint.Distance     = currentPointDistanceDelta + (previousPoint.Distance ?? 0);
                }

                if (i == 1)
                {
                    previousPoint.Distance = previousPoint.Distance ?? 0;
                    currentLap.Track.Add(previousPoint);
                }

                currentLap.Track.Add(currentPoint);

                if (pointsHaveTimeInfo)
                {
                    var startSecondsDelta = (decimal)(currentPoint.StartSeconds.Value - previousPoint.StartSeconds.Value);
                    startSecondsDelta = startSecondsDelta == 0 ? 1 : startSecondsDelta;

                    currentPointDistanceDelta = currentPointDistanceDelta ?? currentPoint.Distance - previousPoint.Distance;
                    currentPoint.Speed        = currentPointDistanceDelta / startSecondsDelta;

                    if (currentLap.StartSeconds == null)
                    {
                        currentLap.StartSeconds = currentPoint.StartSeconds;
                    }
                }

                currentLap.Distance = currentLap.Track.Last().Distance.Value - currentLap.Track.First().Distance.Value;
                if (currentLap.Distance.Value < lapIntervalMeters)
                {
                    continue;
                }

                // Reached the end of the lap, start a new one...
                currentLap = new DeviceLap {
                    StartSeconds = currentLap.Track.Last().StartSeconds
                };
            }

            // Calculate Time for last lap...
            var lastLap = activity.Laps.Last();
            if (pointsHaveTimeInfo)
            {
                lastLap.Time = (decimal)(lastLap.Track.Last().StartSeconds.Value - lastLap.Track.First().StartSeconds.Value);
            }

            // Loop through resulting laps to calculate Time and remaining aggregates...
            activity.Laps.ForEach(lap =>
            {
                // Calculate HRMax and HRAvg from lap's collection of HR points...
                var hrPoints     = lap.Track.Where(t => t.HR != null).Select(x => x.HR.Value).ToList();
                lap.HeartRateMax = hrPoints.Any() ? (int?)hrPoints.Max() : null;
                lap.HeartRateAvg = hrPoints.Any() ? (int?)hrPoints.Average() : null;

                // Calculate CADMax and CADAvg from lap's collection of CAD points...
                var cadPoints = lap.Track.Where(t => t.CAD != null).Select(x => x.CAD.Value).ToList();
                lap.CADMax    = cadPoints.Any() ? (int?)cadPoints.Max() : null;
                lap.CADAvg    = cadPoints.Any() ? (int?)cadPoints.Average() : null;

                // Calculate TempMax and TempAvg from lap's collection of Temp points...
                var tempPoints = lap.Track.Where(t => t.Temp != null).Select(x => x.Temp.Value).ToList();
                lap.TempMax    = tempPoints.Any() ? (int?)tempPoints.Max() : null;
                lap.TempAvg    = tempPoints.Any() ? (int?)tempPoints.Average() : null;

                // Calculage SpeedMax and SpeedAvg from lap's collection of points...
                var speedPoints = lap.Track.Where(t => t.Speed != null).Select(x => x.Speed.Value).ToList();
                lap.SpeedMax    = speedPoints.Any() ? (decimal?)speedPoints.Max() : null;
                lap.SpeedAvg    = speedPoints.Any() ? (decimal?)speedPoints.Average() : null;
            });
        }

        return(file);
    }
コード例 #17
0
    private static DeviceFile FromTcxV2_Base(XmlDocument Doc)
    {
        var ns = new XmlNamespaceManager(Doc.NameTable);

        ns.AddNamespace("tcd", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2");
        ns.AddNamespace("ae", "http://www.garmin.com/xmlschemas/ActivityExtension/v2");
        XMLParserHelper.Manager = ns;
        //var Activities = Doc.SelectNodes("/tcd:TrainingCenterDatabase/tcd:Activities/tcd:Activity", ns);
        var            Activities = Doc.GetElementsByTagName("Activity");
        DeviceActivity CurrentActivity;
        DeviceLap      CurrentLap;
        DevicePoint    CurrentPoint;
        DeviceCreator  CurrentCreator;
        DeviceAuthor   CurrentAuthor;
        XmlNode        WorkNode;
        XmlAttribute   WorkAttr;
        DateTime       dtTryParse;
        DateTimeOffset dtoTryParse;

        DeviceFile File = new DeviceFile();

        CurrentAuthor = new DeviceAuthor();
        File.Author   = CurrentAuthor;

        string VMajor, VMinor, BMajor, BMinor;

        CurrentAuthor.Name       = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:Name");
        CurrentAuthor.Language   = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:LangID");
        CurrentAuthor.PartNumber = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:PartNumber");
        VMajor = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:Build/tcd:Version/tcd:VersionMajor", "0");
        VMinor = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:Build/tcd:Version/tcd:VersionMinor", "0");
        BMajor = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:Build/tcd:Version/tcd:BuildMajor", "0");
        BMinor = XMLParserHelper.SelectSingleTextString(Doc, "/tcd:TrainingCenterDatabase/tcd:Author/tcd:Build/tcd:Version/tcd:BuildMinor", "0");
        CurrentAuthor.Version = VMajor + "." + VMinor + "." + BMajor + "." + BMinor;

        foreach (XmlNode Activity in Activities)
        {
            CurrentActivity = new DeviceActivity();
            File.Activities.Add(CurrentActivity);
            CurrentActivity.Id = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Id");
            if (CurrentActivity.Id != null && DateTimeOffset.TryParse(CurrentActivity.Id, out dtoTryParse))
            {
                //dtoTryParse = FSSecurity.Current.ToUserTime(dtoTryParse);
                dtTryParse = new DateTime(dtoTryParse.Year, dtoTryParse.Month, dtoTryParse.Day, dtoTryParse.Hour, dtoTryParse.Minute, dtoTryParse.Second);
                CurrentActivity.ActivityTime = dtTryParse;
            }
            CurrentActivity.Sport = XMLParserHelper.SelectSingleAttributeString(Activity, "Sport", "Unknown");

            CurrentCreator          = new DeviceCreator();
            CurrentActivity.Creator = CurrentCreator;

            CurrentCreator.Name      = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:Name");
            CurrentCreator.UnitID    = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:UnitId");
            CurrentCreator.ProductID = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:ProductID");
            VMajor = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:Version/tcd:VersionMajor", "0");
            VMinor = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:Version/tcd:VersionMinor", "0");
            BMajor = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:Version/tcd:BuildMajor", "0");
            BMinor = XMLParserHelper.SelectSingleTextString(Activity, "tcd:Creator/tcd:Version/tcd:BuildMinor", "0");
            CurrentCreator.Version = VMajor + "." + VMinor + "." + BMajor + "." + BMinor;
            var CreatorName = CurrentCreator.Name ?? "";
            var Laps        = Activity.SelectNodes("tcd:Lap", ns);
            var IsFirst     = true;
            foreach (XmlNode Lap in Laps)
            {
                var MyInt = XMLParserHelper.SelectSingleTextString(Lap, "tcd:Intensity", "");
                // This is for trailing resting tomtom laps that have zero distance and time
                if (MyInt.ToLower() == "resting" && CreatorName.ToLower().IndexOf("tomtom") >= 0)
                {
                    continue;
                }
                if (IsFirst)
                {
                    IsFirst = false;
                    var TestSeconds = XMLParserHelper.SelectSingleTextDecimal(Lap, "tcd:TotalTimeSeconds", null);
                    var TestDist    = XMLParserHelper.SelectSingleTextDecimal(Lap, "tcd:DistanceMeters", null);
                    if (TestSeconds == 0 && TestDist == 0)
                    {
                        continue;
                    }
                }
                CurrentLap = new DeviceLap();
                CurrentActivity.Laps.Add(CurrentLap);
                WorkAttr = Lap.Attributes["StartTime"];
                if (null != WorkAttr && null != CurrentActivity.ActivityTime && DateTimeOffset.TryParse(WorkAttr.Value, out dtoTryParse))
                {
                    //dtoTryParse = FSSecurity.Current.ToUserTime(dtoTryParse);
                    dtTryParse = new DateTime(dtoTryParse.Year, dtoTryParse.Month, dtoTryParse.Day, dtoTryParse.Hour, dtoTryParse.Minute, dtoTryParse.Second);
                    CurrentLap.StartSeconds = (dtTryParse - (CurrentActivity.ActivityTime ?? DateTime.Now)).TotalSeconds;
                }

                CurrentLap.Time         = XMLParserHelper.SelectSingleTextDecimal(Lap, "tcd:TotalTimeSeconds", null);
                CurrentLap.Distance     = XMLParserHelper.SelectSingleTextDecimal(Lap, "tcd:DistanceMeters", null);
                CurrentLap.SpeedAvg     = XMLParserHelper.SelectSingleTextDecimal(Lap, "tcd:Extensions/ae:LX/ae:AvgSpeed", null);
                CurrentLap.SpeedMax     = XMLParserHelper.SelectSingleTextDecimal(Lap, "tcd:MaximumSpeed", null);
                CurrentLap.Calories     = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:Calories", null);
                CurrentLap.RPMAvg       = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:Cadence", null);
                CurrentLap.RPMMax       = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:Extensions/ae:LX/ae:MaxBikeCadence", null);
                CurrentLap.HeartRateAvg = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:AverageHeartRateBpm/tcd:Value", null);
                CurrentLap.HeartRateMax = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:MaximumHeartRateBpm/tcd:Value", null);
                CurrentLap.WattsAvg     = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:Extensions/ae:LX/ae:AvgWatts", null);
                CurrentLap.WattsMax     = XMLParserHelper.SelectSingleTextInt(Lap, "tcd:Extensions/ae:LX/ae:MaxWatts", null);

                var         TrackPoints    = Lap.SelectNodes("tcd:Track/tcd:Trackpoint", ns);
                DevicePoint LastTrackPoint = null;
                foreach (XmlNode Point in TrackPoints)
                {
                    CurrentPoint = new DevicePoint();
                    CurrentLap.Track.Add(CurrentPoint);
                    WorkNode = Point.SelectSingleNode("tcd:Time", ns);
                    if (null != WorkNode && null != CurrentActivity.ActivityTime && DateTimeOffset.TryParse(WorkNode.InnerText, out dtoTryParse))
                    {
                        //dtoTryParse = FSSecurity.Current.ToUserTime(dtoTryParse);
                        dtTryParse = new DateTime(dtoTryParse.Year, dtoTryParse.Month, dtoTryParse.Day, dtoTryParse.Hour, dtoTryParse.Minute, dtoTryParse.Second);
                        CurrentPoint.StartSeconds = (dtTryParse - (CurrentActivity.ActivityTime ?? DateTime.Now)).TotalSeconds;
                    }

                    CurrentPoint.Latitude  = XMLParserHelper.SelectSingleTextDecimal(Point, "tcd:Position/tcd:LatitudeDegrees", null);
                    CurrentPoint.Longitude = XMLParserHelper.SelectSingleTextDecimal(Point, "tcd:Position/tcd:LongitudeDegrees", null);
                    CurrentPoint.Altitude  = XMLParserHelper.SelectSingleTextDecimal(Point, "tcd:AltitudeMeters", null);
                    CurrentPoint.Distance  = XMLParserHelper.SelectSingleTextDecimal(Point, "tcd:DistanceMeters", null);
                    CurrentPoint.HR        = XMLParserHelper.SelectSingleTextInt(Point, "tcd:HeartRateBpm/tcd:Value", null);
                    CurrentPoint.RPM       = XMLParserHelper.SelectSingleTextInt(Point, "tcd:Cadence", null);
                    CurrentPoint.CAD       = XMLParserHelper.SelectSingleTextInt(Point, "tcd:Extensions/ae:TPX/ae:RunCadence", null);
                    if (CurrentPoint.CAD != null)
                    {
                        CurrentPoint.CAD = CurrentPoint.CAD.Value * 2;
                    }
                    CurrentPoint.Speed = XMLParserHelper.SelectSingleTextDecimal(Point, "tcd:Extensions/ae:TPX/ae:Speed", null);
                    CurrentPoint.Watts = XMLParserHelper.SelectSingleTextInt(Point, "tcd:Extensions/ae:TPX/ae:Watts", null);
                    if (LastTrackPoint != null && CurrentPoint.Speed == null && (CurrentPoint.Distance != null && CurrentPoint.StartSeconds != null) && (LastTrackPoint.Distance != null && LastTrackPoint.StartSeconds != null))
                    {
                        // Last Distance and Time vs Current Distance and Time ->
                        var SecondDelta   = (decimal)(CurrentPoint.StartSeconds - LastTrackPoint.StartSeconds);
                        var DistanceDelta = CurrentPoint.Distance - LastTrackPoint.Distance;
                        if (SecondDelta == 0 || DistanceDelta == 0)
                        {
                            CurrentPoint.Speed = 0;
                        }
                        else
                        {
                            CurrentPoint.Speed = DistanceDelta / SecondDelta;
                        }
                    }
                    LastTrackPoint = CurrentPoint;
                }

                var CadencePoints = from x in CurrentLap.Track
                                    where x.CAD != null
                                    select x;
                if (CadencePoints.Any())
                {
                    var m = (from x in CadencePoints
                             select x.CAD).Max();
                    var a = (from x in CadencePoints
                             select x.CAD).Average();
                    CurrentLap.CADAvg = (int?)a;
                    CurrentLap.CADMax = (int?)m;
                }
            }
        }
        return(File);
    }
コード例 #18
0
 internal void refresh()
 {
     _pointModel            = OriginalModel.Clone <DevicePoint>();
     _container.DataContext = _pointModel;
 }
コード例 #19
0
        internal AnalogPointDocument(Device device, SolutionNode parent, DevicePoint dataModel, int folderId)
        {
            _dataModel = dataModel;
            InitializeComponent();
            List <object> items = new List <object>();

            for (double i = 1; i <= 100; i++)
            {
                items.Add(new {
                    text  = i + "%",
                    value = i
                });
            }
            cmd_ValueRelativeChangeOptions.ItemsSource = items;

            items = new List <object>();
            for (double i = 1; i <= 100; i++)
            {
                items.Add(new
                {
                    text  = i + "%",
                    value = i
                });
            }
            cmd_Percent.ItemsSource = items;

            items = new List <object>();
            for (double i = 1; i <= 120; i++)
            {
                items.Add(new
                {
                    text  = i + "秒",
                    value = i
                });
            }
            cmd_ValueOnTimeChangeOptions.ItemsSource = items;

            items = new List <object>();
            for (double i = 1; i <= 120; i++)
            {
                items.Add(new
                {
                    text  = i + "秒",
                    value = i
                });
            }
            cmd_ChangeCycle.ItemsSource = items;

            //报警组
            items = new List <object>();
            for (int i = 0; i < 16; i++)
            {
                items.Add(new
                {
                    text  = (i + 1).ToString(),
                    value = (1 << i)
                });
            }
            cmd_AlarmGroup.ItemsSource = items;

            //安全区
            items = new List <object>();
            for (int i = 0; i < 26; i++)
            {
                items.Add(new
                {
                    text  = ((char)(((int)('A')) + i)).ToString(),
                    value = (1 << i)
                });
            }
            cmbSafeArea.ItemsSource = items;

            Controller = new PointDocumentController(this, gridProperty, device, DevicePoint_TypeEnum.Analog, parent, dataModel, folderId);
            this.Title = Controller.OriginalModel.Desc;
        }
コード例 #20
0
        public MyDevicePoint(DevicePoint point)
        {
            DevicePoint    = point;
            LowAlarmConfig = (new AlarmConfig[] {
                new AlarmConfig()
                {
                    Value = point.AlarmValue,
                    Priority = point.AlarmPriority,
                    Number = 1,
                },
                new AlarmConfig()
                {
                    Value = point.AlarmValue2,
                    Priority = point.AlarmPriority2,
                    Number = 2,
                },
                new AlarmConfig()
                {
                    Value = point.AlarmValue3,
                    Priority = point.AlarmPriority3,
                    Number = 3,
                },
                new AlarmConfig()
                {
                    Value = point.AlarmValue4,
                    Priority = point.AlarmPriority4,
                    Number = 4,
                },
                new AlarmConfig()
                {
                    Value = point.AlarmValue5,
                    Priority = point.AlarmPriority5,
                    Number = 5,
                }
            }).Where(m => m.Value != null && m.Priority != null).OrderBy(m => m.Value).ToArray();


            HiAlarmConfig = (new AlarmConfig[] {
                new AlarmConfig()
                {
                    Value = point.HiAlarmValue,
                    Priority = point.HiAlarmPriority,
                    Number = 1,
                },
                new AlarmConfig()
                {
                    Value = point.HiAlarmValue2,
                    Priority = point.HiAlarmPriority2,
                    Number = 2,
                },
                new AlarmConfig()
                {
                    Value = point.HiAlarmValue3,
                    Priority = point.HiAlarmPriority3,
                    Number = 3,
                },
                new AlarmConfig()
                {
                    Value = point.HiAlarmValue4,
                    Priority = point.HiAlarmPriority4,
                    Number = 4,
                },
                new AlarmConfig()
                {
                    Value = point.HiAlarmValue5,
                    Priority = point.HiAlarmPriority5,
                    Number = 5,
                }
            }).Where(m => m.Value != null && m.Priority != null).OrderByDescending(m => m.Value).ToArray();
        }