public IHttpActionResult PutLocomotive(int id, Locomotive locomotive)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != locomotive.id)
            {
                return BadRequest();
            }

            db.Entry(locomotive).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LocomotiveExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
        public IHttpActionResult PostLocomotive(Locomotive locomotive)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.locomotives.Add(locomotive);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = locomotive.id }, locomotive);
        }
Ejemplo n.º 3
0
        public void AddLocomotiveToTrain(int locomotive_id, int station_id)
        {
            Locomotive locomotive = Locomotive.FindById(locomotive_id);

            locomotive_list.Add(locomotive);

            int index = FindIndexOfStation(station_id);

            this.locomotives_by_station[index].Remove(locomotives_by_station[index].Find(delegate(Locomotive l) {
                return(l.locomotive_id == locomotive_id);
            }));
        }
Ejemplo n.º 4
0
        public void FeedCapacityLabel(Label capacity_label, string patente)
        {
            Locomotive locomotive = Locomotive.FindByPatent(patente);

            if (locomotive != null)
            {
                capacity_label.Text = locomotive.tons_drag.ToString();
            }
            else
            {
                capacity_label.Text = "Seleccione locomotora de arrastre";
            }
        }
Ejemplo n.º 5
0
 public void SetNext(Locomotive loc, Analyze.Route route)
 {
     lock (_manuallyDefinedRoutes)
     {
         if (_manuallyDefinedRoutes.ContainsKey(loc))
         {
             _manuallyDefinedRoutes[loc] = route;
         }
         else
         {
             _manuallyDefinedRoutes.Add(loc, route);
         }
     }
 }
Ejemplo n.º 6
0
        public long AddLocomotive(AddLocomotiveModel model)
        {
            var locomotiveToAdd = new Locomotive
            {
                Id                = GenerateKey(),
                VehicleType       = model.VehicleType,
                VehicleNumber     = model.VehicleNumber,
                VehicleSideNumber = model.VehicleSideNumber
            };

            db.Locomotives.Add(locomotiveToAdd);
            db.SaveChanges();
            return(locomotiveToAdd.Id);
        }
Ejemplo n.º 7
0
        public LocomotiveList01(Locomotive _car, TrainList_OKAdd_Locomotive_Page _page)
        {
            try
            {
                InitializeComponent();

                car  = _car;
                page = _page;
            }
            catch (Exception ex)
            {
                RTCore.Environment.ReportError(ex, AccessManager.AccessKey);
            }
        }
        public async Task <ActionResult <Locomotive> > Get(string id)
        {
            Locomotive locomotive = null;

            try
            {
                locomotive = _Locomotives.First(l => l.ModelRange == id);
            }
            catch (ArgumentNullException)
            {
                return(NotFound());
            }

            return(Ok(locomotive));
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (e.IsNavigationInitiator && e.NavigationMode == NavigationMode.Back)
            {
                if (Locomotive != null)
                {
                    //Locomotive.Update(); // force update
                    Locomotive.UnregisterControl();
                    Locomotive.PropertyChanged -= Item_PropertyChanged;
                    Locomotive = null;
                }

                App.EcosModel.LocomotiveManager.ItemRemoved -= LocomotiveManager_ItemRemoved;
            }
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (e.NavigationMode == NavigationMode.Back)
            {
                if (Locomotive != null)
                {
                    //Locomotive.Update(); // force update
                    Locomotive.UnregisterControlAsync();
                    Locomotive = null;
                }

                AppManager.EcosModel.LocomotivesManager.ItemRemoved -= LocomotiveManager_ItemRemoved;
            }
        }
Ejemplo n.º 11
0
    public static void Main(string[] args)
    {
        Locomotive oldLocomotive = new Locomotive(15);
        Product    newLocomotive = oldLocomotive.clone();
        Train      longTrain     = new Train(oldLocomotive);

        longTrain.add_wagon("Passenger");
        Product shortTrain = longTrain.clone();

        longTrain.add_wagon("Freight");

        oldLocomotive.set_price(7);

        System.Console.WriteLine(newLocomotive.get_cost() - oldLocomotive.get_cost());
        System.Console.WriteLine(shortTrain.get_cost() - longTrain.get_cost());
    }
Ejemplo n.º 12
0
        public async Task <ActionResult <LocomotiveModel> > Create(LocomotiveModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var road = await _roadService.GetById(model.RoadId);

            if (road == null)
            {
                ModelState.AddModelError(nameof(model.RoadId), "Road is not valid");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // TODO: Validate road number (numbers only) road + road number combo

            var locomotive = new Locomotive
            {
                RoadId         = road.Id,
                RoadNumber     = model.RoadNumber,
                ReportingMarks = $"{road.ReportingMarks} {model.RoadNumber}",
                Notes          = model.Notes,
                // Slug is generated below
                ModelNumber  = model.ModelNumber,
                SerialNumber = model.SerialNumber,
                FrameNumber  = model.FrameNumber,
                BuiltAs      = model.BuiltAs,
                BuildMonth   = model.BuildMonth,
                BuildYear    = model.BuildYear
            };

            locomotive.Slug = locomotive.ReportingMarks.Slugify();

            await _locomotiveRepository.CreateAsync(locomotive);

            // Re-fetch the locomotive to make sure the model is fully hydrated
            locomotive = await _locomotiveRepository.GetByIdAsync(locomotive.Id);

            model = _mapper.Map <LocomotiveModel>(locomotive);

            return(CreatedAtAction(nameof(GetById), new { id = locomotive.Id }, model));
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            //Инициализируем параметры класса PassengerTrain
            BaggageCarSequence   bcs  = new BaggageCarSequence((JsonSerialize.DeserializationBaggageCar()).ToList());
            PassengerCarSequence pcs  = new PassengerCarSequence((JsonSerialize.DeserializationPassengerCar()).ToList());
            Locomotive           Loco = JsonSerialize.DeserializationLocomotive();

            //Создаем объект типа PassengerTrain
            PassengerTrain PT = new PassengerTrain("ТЭГК95", Loco, bcs, pcs);

            //Выводим информацию об объектах поезда на консоль
            foreach (string obj in PT.Notation())
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("___________________________________________________");

            Console.WriteLine("Суммарны вес поезда = " + PT.Weight());
            Console.WriteLine("Количество багажа = " + PT.FreightWeight);
            Console.WriteLine("Количество пасажиров = " + PT.OccupiedSeatsNumber);

            //Проводим сортировку и снова выводим информацию об объектах поезда на консоль
            IEnumerable <IPassengerItem> OP = PT.Sort();

            foreach (IPassengerItem obj in OP)
            {
                Console.WriteLine(obj.ToString());
            }

            //Выполняем поиск вагонов по заданным максималным и минимальным значениям
            IEnumerable <IPassengerItem> cars = PT.SearchForPassengerNumber(27);

            Console.WriteLine("Вагоны подходящие под заданное значение = ");
            foreach (IPassengerItem obj in cars)
            {
                Console.WriteLine(obj.ToString());
            }
            Console.WriteLine("Вагоны подходящие под заданный диапазон = ");
            IEnumerable <IPassengerItem> cars2 = PT.SearchForPassengerNumber(20, 28);

            foreach (IPassengerItem obj in cars2)
            {
                Console.WriteLine(obj.ToString());
            }

            Console.ReadLine();
        }
Ejemplo n.º 14
0
        private static void InsertLocomotive()
        {
            var loco_A = new Locomotive
            {
                Name           = "Class 25",
                Description    = "BR Blue.",
                Classification = 6
            };

            var loco_B = new Locomotive
            {
                Name           = "Class 20",
                Description    = "BR Blue.",
                Classification = 6
            };

            var loco_C = new Locomotive
            {
                Name           = "Class 37",
                Description    = "BR Blue.",
                Classification = 6
            };

            var loco_D = new Locomotive
            {
                Name           = "Class 43",
                Description    = "Virgin Trains HST",
                Classification = 11
            };

            using (var context = new RailwaysContextEF())
            {
                context.Database.Log = Console.WriteLine;

                //context.LocomotiveEF.Add(loco_A);

                context.LocomotiveEF.AddRange(new List <Locomotive> {
                    loco_A,
                    loco_B,
                    loco_C,
                    loco_D
                });

                context.SaveChanges();
            }
        }
Ejemplo n.º 15
0
        static public Locomotive DeserializationLocomotive()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto
            };

            string       fileContents;
            StreamReader streamReader = new StreamReader("SourseLocomotive.txt");

            using (streamReader)
            {
                fileContents = streamReader.ReadToEnd();
            }
            Locomotive element = JsonConvert.DeserializeObject <Locomotive>(fileContents, settings);

            return(element);
        }
Ejemplo n.º 16
0
 public bool RepeatedPatent(String patent)
 {
     try
     {
         if (Locomotive.FindByPatent(patent) != null)
         {
             return(true);
         }
         foreach (Locomotive locomotive in this.list_locomotive)
         {
             if (locomotive.patent == patent)
             {
                 return(true);
             }
         }
         return(false);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         return(false);
     }
 }
Ejemplo n.º 17
0
        private int KickStart(int currentSpeed, Locomotive ecosLoc)
        {
            var maxSpeedSteps = ecosLoc.GetNumberOfSpeedsteps();
            var previousSpeed = currentSpeed;

            var kickStartSpeed = 0;

            if (maxSpeedSteps <= 14)
            {
                kickStartSpeed = Globals.DccKickStartM14;
            }
            else if (maxSpeedSteps <= 28)
            {
                kickStartSpeed = Globals.DccKickStartM28;
            }
            else if (maxSpeedSteps <= 128)
            {
                kickStartSpeed = Globals.DccKickStartM128;
            }

            if (currentSpeed > kickStartSpeed)
            {
                return(currentSpeed);
            }

            __showSpeed(kickStartSpeed);
            Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, kickStartSpeed);
            System.Threading.Thread.Sleep(Globals.DccKickStartDelayMsecs);
            if (previousSpeed < 1)
            {
                previousSpeed = 2;
            }
            __showSpeed(previousSpeed);
            Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, previousSpeed);
            return(previousSpeed);
        }
Ejemplo n.º 18
0
 public Train(Locomotive locomotive, List <IWagon> vagony)
 {
     this.locomotive = locomotive;
     this.vagony     = vagony;
 }
Ejemplo n.º 19
0
 public PassengerTrain(int number, DateTime startUpDate, Locomotive locomotive)
     : base(number, startUpDate, locomotive)
 {
 }
Ejemplo n.º 20
0
 public Train(Locomotive locomotive)
 {
     this.locomotive = locomotive;
 }
Ejemplo n.º 21
0
 // Start is called before the first frame update
 protected override void AfterStart()
 {
     _locomotive = GameObject.FindGameObjectWithTag("Locomotive").GetComponent <Locomotive>();
 }
Ejemplo n.º 22
0
        public Boolean AddTrain()
        {
            //var locomotive4 = new Locomotive
            //{
            //    Configuration = "0-6-0",
            //    Functions = new EFunctions()
            //    {
            //        EAddress = 4,
            //        HasSound = false
            //    },
            //    Id = Guid.NewGuid(),
            //    Name = "King Richard II",
            //    Number = "2721",
            //    Owner = "GWR",
            //    Role = LocomotiveRole.Mixed,
            //    Type = LocomotiveType.Steam
            //};
            //locomotiveRepository.Add(locomotive4);

            var locomotive5 = new Locomotive
            {
                Configuration = "2-6-0",
                Functions     = new EFunctions()
                {
                    EAddress = 5,
                    HasSound = true
                },
                Id     = Guid.NewGuid(),
                Name   = "King Richard II",
                Number = "6021",
                Owner  = "British Rail",
                Role   = LocomotiveRole.Passenger,
                Type   = LocomotiveType.Steam
            };

            locomotiveRepository.Add(locomotive5);

            var locomotive6 = new Locomotive
            {
                Configuration = "4-4-2T",
                Functions     = new EFunctions()
                {
                    EAddress = 6,
                    HasSound = false
                },
                Id     = Guid.NewGuid(),
                Name   = "",
                Number = "415",
                Owner  = "LSWR",
                Role   = LocomotiveRole.Mixed,
                Type   = LocomotiveType.Steam
            };

            locomotiveRepository.Add(locomotive6);

            var locomotive7 = new Locomotive
            {
                Configuration = "2-6-4T",
                Functions     = new EFunctions()
                {
                    EAddress = 7,
                    HasSound = false
                },
                Id     = Guid.NewGuid(),
                Name   = "",
                Number = "42334",
                Owner  = "British Railways",
                Role   = LocomotiveRole.Mixed,
                Type   = LocomotiveType.Steam
            };

            locomotiveRepository.Add(locomotive7);

            var locomotive8 = new Locomotive
            {
                Configuration = "BoBo",
                Functions     = new EFunctions()
                {
                    EAddress = 8,
                    HasSound = false
                },
                Id     = Guid.NewGuid(),
                Name   = "101 DMU",
                Number = "E51217",
                Owner  = "British Railways",
                Role   = LocomotiveRole.Passenger,
                Type   = LocomotiveType.Diesel
            };

            locomotiveRepository.Add(locomotive8);
            return(true);
        }
 private void AddRecentItem(Locomotive item)
 {
     if (item != null)
     {
         if (RecentItemsIDs.Any(id => id == item.ID))
         {
             if (RecentItemsIDs.IndexOf(item.ID) != 0)
             {
                 RecentItemsIDs.Remove(item.ID);
                 RecentItemsIDs.Insert(0, item.ID);
                 NotifyPropertyChanged(nameof(RecentItemsIDs));
             }
         }
         else
         {
             RecentItemsIDs.Insert(0, item.ID);
             NotifyPropertyChanged(nameof(RecentItemsIDs));
         }
     }
 }
Ejemplo n.º 24
0
 public FreightTrain(int number, DateTime startUpDate, Locomotive locomotive)
     : base(number, startUpDate, locomotive)
 {
 }
Ejemplo n.º 25
0
        private async Task AccelerateLocomotiveCurve(
            int currentSpeed,
            Locomotive ecosLoc,
            SpeedCurve speedCurve,
            int maxSeconds = -1,
            Func <bool> hasToBeCanceled = null)
        {
            if (ecosLoc == null)
            {
                return;
            }
            if (speedCurve == null)
            {
                return;
            }

            currentSpeed = KickStart(currentSpeed, ecosLoc);

            if (maxSeconds <= -1)
            {
                maxSeconds = speedCurve.MaxTime;
            }

            var targetSpeed = speedCurve.MaxSpeed;
            var timeSteps   = speedCurve.MaxTime / (float)speedCurve.MaxSpeed * 1000.0;

            await Task.Run(() =>
            {
                var hasCanceled = false;

                var sw = Stopwatch.StartNew();
                var idxOfCurrentSpeed = 0;
                for (var i = 0; i < speedCurve.Steps.Count - 1; ++i)
                {
                    var itSpeed  = speedCurve.Steps[i];
                    var itSpeed2 = speedCurve.Steps[i + 1];
                    if (currentSpeed >= itSpeed.Speed && currentSpeed < itSpeed2.Speed)
                    {
                        idxOfCurrentSpeed = i;
                        break;
                    }
                }

                for (var i = idxOfCurrentSpeed; i <= speedCurve.Steps.Count; ++i)
                {
                    var newSpeed = speedCurve.Steps[i].Speed;
                    Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, (int)newSpeed);
                    __showSpeed((int)newSpeed);
                    if (newSpeed >= targetSpeed)
                    {
                        break;
                    }

                    //
                    // walltime reached
                    //
                    if (sw.ElapsedMilliseconds / 1000 > maxSeconds)
                    {
                        return;
                    }

                    if (IsCanceled())
                    {
                        hasCanceled = true;
                        break;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            break;
                        }
                    }

                    if (__delayAccelerate((int)timeSteps, sw, maxSeconds, hasToBeCanceled))
                    {
                        return;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            break;
                        }
                    }
                }

                if (hasCanceled)
                {
                    // TBD
                }
            }, CancelSource.Token);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Filters the routes where the current locomotive
        /// is not allowed to enter the block.
        /// </summary>
        /// <param name="routeList"></param>
        /// <param name="locDataEcos"></param>
        /// <param name="locData"></param>
        /// <param name="feedbacks"></param>
        /// <returns></returns>
        public static RouteList FilterBy(
            this RouteList routeList,
            Locomotive locDataEcos,
            Locomotives.Data locData,
            FeedbacksData feedbacks
            )
        {
            var res = new RouteList();

            foreach (var it in routeList)
            {
                var targetBlock           = it.Blocks[1];
                var targetBlockIdentifier = targetBlock.identifier;
                var targetEnterSide       = targetBlock.side;

                var targetBlockData = feedbacks.GetByBlockId(targetBlockIdentifier, targetEnterSide);
                if (targetBlockData == null)
                {
                    continue;
                }

                //
                // check if the target block denies entering by the current locomotive
                //
                var useIsDenied = false;
                foreach (var itLoc in targetBlockData.DeniedLocomotives)
                {
                    useIsDenied = itLoc.Id.Equals(locDataEcos.Name, StringComparison.Ordinal);
                    if (useIsDenied)
                    {
                        break;
                    }
                }
                if (useIsDenied)
                {
                    continue;
                }

                //
                // check if the locomotive type is not allowed to enter the target block
                //
                targetBlockData.Settings ??= GetDefaultSettings();
                if (targetBlockData.Settings.Count == 0)
                {
                    continue;
                }
                var enterIsAllowed = false;
                foreach (var itLocSetting in locData.Settings)
                {
                    var name  = itLocSetting.Key;
                    var state = itLocSetting.Value;

                    if (targetBlockData.Settings.ContainsKey(name))
                    {
                        enterIsAllowed = state == targetBlockData.Settings[name];
                        if (enterIsAllowed)
                        {
                            break;
                        }
                    }
                }
                if (!enterIsAllowed)
                {
                    continue;
                }

                res.Add(it);
            }

            return(res);
        }
Ejemplo n.º 27
0
        public static void Mainx(string[] args)
        {
            EconomyVagon ew1 = new EconomyVagon(21, 10);

            EconomyVagon ew2 = new EconomyVagon(22, 10);

            Person        st1 = new Person("Lenka", "Kozakova"); //
            BusinessVagon bw1 = new BusinessVagon(st1, 11, 20);  //

            Person        st2 = new Person("Lukas", "Kozak");    //
            BusinessVagon bw2 = new BusinessVagon(st2, 12, 25);  //

            NightVagon nw1 = new NightVagon(31, 5, 10);
            NightVagon nw2 = new NightVagon(32, 5, 10);

            Hopper hw1 = new Hopper(41, 100.5);

            Hopper hw2 = new Hopper(42, 110.5);

            Hopper hw4 = new Hopper(44, 110.5);

            Hopper hw5 = new Hopper(45, 110.5);

            Person     d1 = new Person("Karel", "Novak"); //
            Engine     e1 = new Engine("Diesel");         //
            Locomotive l1 = new Locomotive(d1, e1);       //

            Person     d2 = new Person("Pepa", "Parnik"); //
            Engine     e2 = new Engine("Parni");          //
            Locomotive l2 = new Locomotive(d2, e2);       //


            Train t1 = new Train(l1);

            t1.ConnectWagon(ew1);
            t1.ConnectWagon(ew2);
            t1.ConnectWagon(ew2);
            t1.ConnectWagon(bw1);
            t1.ConnectWagon(nw1);
            t1.ConnectWagon(hw1);
            t1.ConnectWagon(hw1);
            t1.ConnectWagon(hw2);
            t1.ConnectWagon(hw4);
            t1.ConnectWagon(hw5);
            t1.ConnectWagon(hw5);
            Console.WriteLine(t1);
            Console.WriteLine();

            t1.DisconnectWagon(ew1);
            Console.WriteLine(t1);
            Console.WriteLine();

            t1.DisconnectWagon(ew1);
            Console.WriteLine();

            Train t2 = new Train(l2);

            t2.ConnectWagon(ew1);
            t2.ConnectWagon(ew2);
            t2.ConnectWagon(bw2);
            t2.ConnectWagon(nw1);
            t2.ConnectWagon(nw1);
            t2.ConnectWagon(nw2);
            t2.ConnectWagon(hw1);
            t2.ConnectWagon(hw2);
            t2.ConnectWagon(hw4);
            t2.ConnectWagon(hw5);
            Console.WriteLine(t2);
            Console.WriteLine();

            t1.ReserveChair(21, 5);
            t1.ReserveChair(21, 6);
            t1.ReserveChair(22, 7);
            t1.ReserveChair(22, 7);
            t1.ReserveChair(11, 4);
            t1.ReserveChair(11, 5);
            t1.ReserveChair(41, 5);
            t1.ReservedChairs();
            Console.WriteLine();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// in case there is no route to leave on the sideToLeave
        /// probably the trains' direction must change, if change
        /// is allowed:
        /// (1) check for a new route on the opposide sideToLeave
        /// (2) if one or more route available, check if the train is allowed to change the direction (as well the block) [no check if cleaningPriority:=true]
        /// (3) change the direction
        /// (4) change the sideToLeave
        /// (5) ...start the additional route selection routines
        /// </summary>
        /// <param name="routeList"></param>
        /// <param name="occBlock"></param>
        /// <param name="sideToLeave"></param>
        /// <param name="originalSideEntered"></param>
        /// <param name="locDataEcos"></param>
        /// <param name="locData"></param>
        /// <param name="routesOnOpposide"></param>
        /// <param name="cleaningPriority"></param>
        /// <returns></returns>
        public bool CheckOpposide(
            RouteList routeList,
            Occ.OccBlock occBlock,
            SideMarker sideToLeave,
            SideMarker originalSideEntered,
            Locomotive locDataEcos,
            Locomotives.Data locData,
            out RouteList routesOnOpposide,
            bool cleaningPriority = false)
        {
            routesOnOpposide = new RouteList();

            string step4enterBlockSide;

            var occFromBlock = occBlock.FromBlock;

            if (string.IsNullOrEmpty(occFromBlock))
            {
                return(false);
            }

            LogInfo($"The side to leave {sideToLeave} does not have any route to take.");
            if (sideToLeave == SideMarker.Minus)
            {
                step4enterBlockSide = "'-' Side";
                sideToLeave         = SideMarker.Plus;
            }
            else
            {
                step4enterBlockSide = "'+' Side";
                sideToLeave         = SideMarker.Minus;
            }

            #region (1)

            //
            // (1)
            //
            routesOnOpposide = routeList.GetRoutesWithFromBlock(occFromBlock, sideToLeave, true);
            if (routesOnOpposide.Count == 0)
            {
                LogInfo($"The other side to leave {sideToLeave} does not have any route to take.");
                LogInfo($"No route to take from {occFromBlock} for Locomotive({locDataEcos.Name ?? "-"}).");
                return(false);
            }

            #endregion (1)

            #region (2)

            //
            // (2)
            //
            if (cleaningPriority == false)
            {
                if (locData.Settings.ContainsKey("OptionDirection"))
                {
                    var locState = locData.Settings["OptionDirection"];
                    if (!locState)
                    {
                        LogInfo($"Locomotive({locDataEcos.Name}) is not allowed to change the direction.");
                        return(false);
                    }
                }

                var fbData = GetFeedbackDataOf(occBlock.FromBlock, originalSideEntered);
                if (fbData == null)
                {
                    LogInfo($"No feedback data available for block {occBlock.FromBlock}.");
                    return(false);
                }

                if (fbData.Settings.ContainsKey("OptionDirection"))
                {
                    var blockState = fbData.Settings["OptionDirection"];
                    if (!blockState)
                    {
                        LogInfo($"Block({fbData.BlockId}) does not allow to change the direction.");
                        return(false);
                    }
                }
            }

            #endregion (2)

            #region (3)

            //
            // (3)
            //
            var currentDirection = locDataEcos.Direction;
            var newDirection     = currentDirection == 1 ? 0 : 1;
            if (_ctx.IsSimulationMode())
            {
                locDataEcos.ChangeDirectionSimulation(newDirection == 1);
                _ctx.SaveAll();
                _ctx?._sniffer?.TriggerDataProviderModifiedForSimulation();
            }
            else
            {
                locDataEcos.ChangeDirection(newDirection == 1);
                _ctx?._sniffer?.SendCommandsToEcosStation();
            }

            #endregion (3)

            #region (4)

            //
            // (4)
            //
            // EnterBlockSide = "'+' Side"
            // EnterBlockSide = "'-' Side"
            if (string.IsNullOrEmpty(step4enterBlockSide))
            {
                LogInfo($"Invalid enterBlockSide value for Locomotive({locDataEcos.Name}).");
                return(false);
            }

            locData.EnterBlockSide = step4enterBlockSide;
            SaveLocomotivesAndPromote();
            SaveOccAndPromote();

            #endregion (4)

            return(routesOnOpposide.Count > 0);
        }
Ejemplo n.º 29
0
        private async Task DecelerateLocomotive(
            Locomotive ecosLoc,
            int maxSecsToStop           = 10,
            Func <bool> hasToBeCanceled = null)
        {
            var currentSpeed    = (float)ecosLoc.Speedstep;
            var deltaSpeedSteps = maxSecsToStop / currentSpeed; //currentSpeed / maxSecsToStop;
            var noOfSpeedsteps  = ecosLoc.GetNumberOfSpeedsteps();
            var minSpeed        = GetMinSpeed(noOfSpeedsteps);

            await Task.Run(() =>
            {
                //
                // IMPORTANT NOTE:
                // do not slow down the locomotive completly
                // we still have to reach the fbIn, when reached
                // the train will stop right at this moment
                //

                var sw = Stopwatch.StartNew();

                for (var i = currentSpeed; i > minSpeed; i -= deltaSpeedSteps)
                {
                    //
                    // walltime reached
                    //
                    if (sw.ElapsedMilliseconds / 1000 > maxSecsToStop)
                    {
                        return;
                    }

                    __showSpeed((int)i);

                    Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, (int)i);

                    if (IsCanceled())
                    {
                        Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, 0);

                        break;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            break;
                        }
                    }

                    if (__delayDecelerate((int)deltaSpeedSteps, sw, maxSecsToStop, hasToBeCanceled))
                    {
                        return;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            break;
                        }
                    }
                }
            }, CancelSource.Token);
        }
Ejemplo n.º 30
0
        public void SetFavoriteItem(Locomotive item, bool isFavorite)
        {
            item.IsMyFavorite = isFavorite;

            if (isFavorite && !FavoriteItemsIDs.Contains(item.ID))
            {
                FavoriteItemsIDs.Add(item.ID);
                NotifyPropertyChanged("FavoriteItemsIDs");
            }
            if (!isFavorite && FavoriteItemsIDs.Contains(item.ID))
            {
                FavoriteItemsIDs.Remove(item.ID);
                NotifyPropertyChanged("FavoriteItemsIDs");
            }
        }
        public void setLocomotiveinfo(string Name, string Type, string Velocity, string PowerEngin, string information, byte[] pdf, byte[] photo)
        {
            Locomotive locomotive = new Locomotive();

            locomotive.setLocomotive(Name, Type, Velocity, PowerEngin, information, pdf, photo);
        }
Ejemplo n.º 32
0
 // Start is called before the first frame update
 void Start()
 {
     _locomotive = GetComponent <Locomotive>();
 }
Ejemplo n.º 33
0
 // Use this for initialization
 void Start()
 {
     locomotive = FindObjectOfType <Locomotive>();
 }
Ejemplo n.º 34
0
        private async Task AccelerateLocomotive(
            int currentSpeed,
            int targetSpeed,
            Locomotive ecosLoc,
            int maxSeconds = 10,
            Func <bool> hasToBeCanceled = null)
        {
            var maxSpeedSteps = ecosLoc.GetNumberOfSpeedsteps();
            var msecsDelay    = maxSpeedSteps < 30 ? 1000 : 250;

            await Task.Run(() =>
            {
                currentSpeed = KickStart(currentSpeed, ecosLoc);

                var hasCanceled     = false;
                var newCurrentSpeed = currentSpeed;

                var sw = Stopwatch.StartNew();

                for (var i = currentSpeed; i <= targetSpeed; ++i)
                {
                    __showSpeed(i);

                    Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, i);

                    newCurrentSpeed = i;

                    if (IsCanceled())
                    {
                        hasCanceled = true;
                        break;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            break;
                        }
                    }

                    if (__delayAccelerate(msecsDelay, sw, maxSeconds, hasToBeCanceled))
                    {
                        return;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            break;
                        }
                    }
                }

                if (!hasCanceled)
                {
                    Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, newCurrentSpeed);
                }
            }, CancelSource.Token);
        }
Ejemplo n.º 35
0
 public async Task CreateAsync(Locomotive locomotive) =>
 await _locomotiveRepository.CreateAsync(locomotive);
        public byte[] getTypeLocomotive()
        {
            Locomotive locomotive = new Locomotive();

            return(locomotive.getLocomotive());
        }
        private void RegisterItemNotifications(Locomotive item)
        {
            if (item != null)
            {
                item.CommandError += (object sender, MessageEventArgs e) =>
                {
                    if (!item.ProcessCommandError(e.Message))
                        NotifyCommandError(e.Message);
                };

                item.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(item.IsMyFavorite))
                    {
                        if (item.IsMyFavorite)
                        {
                            if (!favoriteItemsIDs.Contains(item.ID))
                            {
                                favoriteItemsIDs.Add(item.ID);
                                NotifyPropertyChanged(nameof(FavoriteItemsIDs));
                            }
                        }
                        else
                        {
                            if (favoriteItemsIDs.Contains(item.ID))
                            {
                                favoriteItemsIDs.Remove(item.ID);
                                NotifyPropertyChanged(nameof(FavoriteItemsIDs));
                            }
                        }
                    }
                };
            }
        }
Ejemplo n.º 38
0
 public void AddRecentItem(Locomotive item, int maxCount)
 {
     if (RecentItemsIDs.Contains(item.ID))
     {
         if (RecentItemsIDs.IndexOf(item.ID) != 0)
         {
             RecentItemsIDs.Remove(item.ID);
             RecentItemsIDs.Insert(0, item.ID);
             NotifyPropertyChanged("RecentItemsIDs");
         }
     }
     else
     {
         RecentItemsIDs.Insert(0, item.ID);
         LimitRecentItemsIDs(maxCount);
     }
 }
        public void setLocomotiveType(string type)
        {
            Locomotive locomotive = new Locomotive();

            locomotive.setLocomotiveType(type);
        }
Ejemplo n.º 40
0
        private async Task DecelerateLocomotiveCurve(
            Locomotive ecosLoc,
            SpeedCurve speedCurve,
            int maxSeconds = -1,
            Func <bool> hasToBeCanceled = null
            )
        {
            if (maxSeconds <= -1)
            {
                maxSeconds = speedCurve.MaxTime;
            }

            var currentSpeed   = (float)ecosLoc.Speedstep;
            var maxSpeed       = speedCurve.MaxSpeed;
            var noOfSpeedsteps = ecosLoc.GetNumberOfSpeedsteps();
            var minSpeed       = GetMinSpeed(noOfSpeedsteps);
            var timeSteps      = (speedCurve.MaxTime / (float)maxSpeed) * 1000.0;

            await Task.Run(() =>
            {
                //
                // IMPORTANT NOTE:
                // do not slow down the locomotive completly
                // we still have to reach the fbIn, when reached
                // the train will stop right at this moment
                //

                var sw  = Stopwatch.StartNew();
                var idx = -1;
                for (var i = 0; i < speedCurve.Steps.Count - 1; ++i)
                {
                    var s0 = speedCurve.Steps[i];
                    var s1 = speedCurve.Steps[i + 1];
                    if (currentSpeed >= s0.Speed && currentSpeed < s1.Speed)
                    {
                        idx = i;
                        break;
                    }
                }

                if (idx == -1)
                {
                    idx = speedCurve.Steps.Count - 1;
                }

                for (var i = idx; i > minSpeed; --i)
                {
                    var nextSpeed = speedCurve.Steps[i];

                    //
                    // walltime reached
                    //
                    if (sw.ElapsedMilliseconds / 1000 > maxSeconds)
                    {
                        return;
                    }

                    Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, (int)nextSpeed.Speed);

                    __showSpeed((int)nextSpeed.Speed);

                    if (IsCanceled())
                    {
                        Ctx.GetClientHandler()?.LocomotiveChangeSpeedstep(ecosLoc, 0);

                        return;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            return;
                        }
                    }

                    if (__delayDecelerate((int)timeSteps, sw, maxSeconds, hasToBeCanceled))
                    {
                        return;
                    }

                    if (hasToBeCanceled != null)
                    {
                        if (hasToBeCanceled())
                        {
                            return;
                        }
                    }
                }
            }, CancelSource.Token);
        }
 private bool FilterDelegate(Locomotive item)
 {
     return
         (!filterFavorites || item.IsMyFavorite == filterFavorites) &&
         (filterType == LocomotiveType.All || item.Type == filterType) &&
         (filterListNumber == 0 ? true :
                     filterListNumber == 1 ? item.List1 :
                     filterListNumber == 2 ? item.List2 :
                     filterListNumber == 3 ? item.List3 :
                     false);
 }