Exemplo n.º 1
0
            protected void          StartPath(IHex start)
            {
                var path = new DirectedPath(start);

                OpenSet.Add(path.PathStep.Hex.Coords, path);
                Queue.Enqueue(0, path);
            }
        /// <summary>TODO</summary>
        /// <param name="board">Board on which this shortest-path search is taking place.</param>
        /// <param name="source">Source hex for this shortest-path search.</param>
        /// <param name="target">Target hex for this shortest-path search.</param>
        /// <param name="closedSet">Injected implementation of <see cref="ISet{HexCoords}"/>.</param>
        protected internal Pathfinder(INavigableBoard board, IHex source, IHex target, ISet <HexCoords> closedSet)
        {
            if (board == null)
            {
                throw new ArgumentNullException("board");
            }
            if (board.Landmarks == null)
            {
                throw new ArgumentNullException("board", "Member Landmarks must not be null");
            }
            if (closedSet == null)
            {
                throw new ArgumentNullException("closedSet");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            Board     = board;
            ClosedSet = closedSet;
            Source    = source;
            Target    = target;
        }
Exemplo n.º 3
0
 public IHex GetOppositeTile(IHex source, IHex target)
 {
     if (this.GetN(source).Equals(target))
     {
         return(this.GetN(target));
     }
     else if (this.GetNE(source).Equals(target))
     {
         return(this.GetNE(target));
     }
     else if (this.GetSE(source).Equals(target))
     {
         return(this.GetSE(target));
     }
     else if (this.GetS(source).Equals(target))
     {
         return(this.GetS(target));
     }
     else if (this.GetSW(source).Equals(target))
     {
         return(this.GetSW(target));
     }
     else if (this.GetNW(source).Equals(target))
     {
         return(this.GetNW(target));
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 4
0
        /// <summary>Returns a least-cost path from the hex <c>start</c> to the hex <c>goal.</c></summary>
        public static IDirectedPath GetDirectedPath(this IBoard <IHex> @this, IHex start, IHex goal)
        {
            if (@this == null)
            {
                throw new ArgumentNullException("this");
            }
            if (start == null)
            {
                throw new ArgumentNullException("start");
            }
            if (goal == null)
            {
                throw new ArgumentNullException("goal");
            }

            if (@this.IsPassable(start.Coords) && @this.IsPassable(goal.Coords))
            {
                return(goal.Coords.Range(start.Coords) > @this.RangeCutoff
              ? BidirectionalPathfinder.FindDirectedPathFwd(start, goal, @this)
              : UnidirectionalPathfinder.FindDirectedPathFwd(start, goal, @this));
            }
            else
            {
                return(default(IDirectedPath));
            }
        }
Exemplo n.º 5
0
 /// <inheritdoc/>
 public virtual int  GetDirectedCostToExit(IHex hex, Hexside hexsideExit)
 {
     //return hex==null ? -1
     //                 : this[hex.Coords].StepCost(hexsideExit);
     return(hex == null ? -1
                : hex.StepCost(hexsideExit));
 }
Exemplo n.º 6
0
 public IHex GetPushTile(IHex source, IHex target)
 {
     if (source != null && target != null)
     {
         if (source.IsTileN(target, 1))
         {
             return(target.GetN());
         }
         else if (source.IsTileNE(target, 1))
         {
             return(target.GetNE());
         }
         else if (source.IsTileSE(target, 1))
         {
             return(target.GetSE());
         }
         else if (source.IsTileS(target, 1))
         {
             return(target.GetS());
         }
         else if (source.IsTileSW(target, 1))
         {
             return(target.GetSW());
         }
         else if (source.IsTileNW(target, 1))
         {
             return(target.GetNW());
         }
     }
     return(null);
 }
Exemplo n.º 7
0
        public List <IHex> GetRaycastTiles(IHex source, IHex target, int dist)
        {
            var list = new List <IHex>();

            if (this.IsTileN(source, target, dist))
            {
                list = this.GetRayTilesViaDistN(source, dist);
            }
            else if (this.IsTileNE(source, target, dist))
            {
                list = this.GetRayTilesViaDistNE(source, dist);
            }
            else if (this.IsTileSE(source, target, dist))
            {
                list = this.GetRayTilesViaDistSE(source, dist);
            }
            else if (this.IsTileS(source, target, dist))
            {
                list = this.GetRayTilesViaDistS(source, dist);
            }
            else if (this.IsTileSW(source, target, dist))
            {
                list = this.GetRayTilesViaDistSW(source, dist);
            }
            else if (this.IsTileNW(source, target, dist))
            {
                list = this.GetRayTilesViaDistNW(source, dist);
            }

            return(list);
        }
        static void ExpandNode(this IBoard <IHex> board, StepCost directedStepCost,
                               BoardStorage <int> costs, Queue queue, IHex here, int key, Hexside hexside
                               )
        {
            var neighbourCoords = here.Coords.GetNeighbour(hexside);

            board[neighbourCoords].IfHasValueDo(neighbour => {
                var cost = directedStepCost(here, hexside);
                if (cost > 0 && costs[neighbourCoords] < 0)
                {
                    Trace($"   Enqueue {neighbourCoords}: {cost,4}");

                    queue.Enqueue(key + cost, neighbour);
                }
            });
            //if (neighbourHex != null) {
            //    var cost = directedStepCost(here, hexside);
            //    if (cost > 0  &&  costs[neighbourCoords] < 0) {

            //        Trace($"   Enqueue {neighbourCoords}: {cost,4}");

            //        queue.Enqueue(key + cost,neighbourHex);
            //    }
            //}
        }
Exemplo n.º 9
0
 // Common settings for both directions
 /// <param name="board">Board on which this path search is taking place.</param>
 /// <param name="start">Start hex for this half of the bidirectional path search.</param>
 /// <param name="goal">Goal hex for this this half of the bidirectional path search.</param>
 /// <param name="pathHalves"></param>
 protected DirectionalPathfinder(INavigableBoard <IHex> board, IHex start, IHex goal, IPathHalves pathHalves)
     : base(board, start, goal, pathHalves.ClosedSet)
 {
     PathHalves = pathHalves;
     OpenSet    = new Dictionary <HexCoords, IDirectedPath>();
     Queue      = new HotPriorityQueue <IDirectedPath>(0, 256);
 }
Exemplo n.º 10
0
        public override bool ProgramFirmware(string FilePath, Action <double> Progress)
        {
            try
            {
                IHex Hex = new IHex();
                Hex.load(FilePath);

                if (SearchHex(Hex, GetFirmwareSearchTokens()))
                {
                    Uploader UL = new Uploader();
                    UL.ProgressEvent += (d) => Progress(d);
                    UL.upload(_Session.Port, Hex);
                    return(true);
                }
                else
                {
                    ShowWrongFirmwareMessageBox();
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            const int IWindowWidth   = 85;
            const int IWindowsLength = 1024 + 32;

            //Format console
            Console.Title       = "C# Hex editor";
            Console.WindowWidth = IWindowWidth;
            Console.SetBufferSize(IWindowWidth, IWindowsLength);
            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.Clear();

            try
            {
                string sSw = null;                                                                  //String of select menu
                do
                {
                    IHex ih = null;                                                                 //Make interface

                    ShowMenu();
                    sSw = Console.ReadLine();                                                       //Get what user select
                    Console.Clear();

                    switch (sSw)
                    {
                    case "1":
                        ih = new ShowFile();
                        break;

                    case "2":
                        ih = new CompareFiles();
                        break;

                    case "0":
                        break;

                    default:
                        Console.WriteLine("You\'re select incorrect variant. For exit use 0");
                        break;
                    }
                    if (sSw == "1" || sSw == "2")
                    {
                        ih.SelectFiles();
                        ih.Show();
                    }

                    //End of while block
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }while (sSw != "0");                                                                 //While user select not 0
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
            }
        }
Exemplo n.º 12
0
 internal static IRgb ToColor(IHex item)
 {
     return(new Rgb {
         R = (double)Convert.ToInt32(item.R, 16),
         G = (double)Convert.ToInt32(item.G, 16),
         B = (double)Convert.ToInt32(item.B, 16)
     });
 }
Exemplo n.º 13
0
 protected void ChangeSpecialCost(IHex aUnit, int valueToChange)
 {
     aUnit.HexCost.SpecialPoints += valueToChange;
     if (aUnit.HexCost.SpecialPoints < 0)
     {
         aUnit.HexCost.SpecialPoints = 0;
     }
 }
Exemplo n.º 14
0
 protected void ChangeTalentCost(IHex aUnit, int valueToChange)
 {
     aUnit.HexCost.TalentPoints += valueToChange;
     if (aUnit.HexCost.TalentPoints < 0)
     {
         aUnit.HexCost.TalentPoints = 0;
     }
 }
        int  Estimate(IHex here, IHex there, int totalCost)
        {
            var estimate   = _heuristic(there.Coords) + totalCost;
            var preference = Preference(_start.Coords.Canon - there.Coords.Canon,
                                        _start.Coords.Canon - _goal.Coords.Canon);

            return((estimate << 16) + preference);
        }
Exemplo n.º 16
0
 protected void ChangeFaithCost(IHex aUnit, int valueToChange)
 {
     aUnit.HexCost.FaithPoints += valueToChange;
     if (aUnit.HexCost.FaithPoints < 0)
     {
         aUnit.HexCost.FaithPoints = 0;
     }
 }
Exemplo n.º 17
0
 protected void ChangeCommandCost(IHex aUnit, int valueToChange)
 {
     aUnit.HexCost.CommandPoints += valueToChange;
     if (aUnit.HexCost.CommandPoints < 0)
     {
         aUnit.HexCost.CommandPoints = 0;
     }
 }
Exemplo n.º 18
0
 /// <summary>Returns a least-cost path from this hex to the hex <c>goal.</c></summary>
 public static IDirectedPath GetDirectedPath(this IHex @this, IHex goal)
 {
     if (@this == null)
     {
         throw new ArgumentNullException("this");
     }
     return(@this.Board.GetDirectedPath(@this, goal));
 }
Exemplo n.º 19
0
        protected static void ExpectedValuesForKnownColor(IColorSpace knownColor, IHex expectedColor)
        {
            var target = knownColor.To <Hex>();

            Assert.IsTrue(CloseEnough(expectedColor.R, target.R), "(R)" + expectedColor.R + " != " + target.R);
            Assert.IsTrue(CloseEnough(expectedColor.G, target.G), "(G)" + expectedColor.G + " != " + target.G);
            Assert.IsTrue(CloseEnough(expectedColor.B, target.B), "(B)" + expectedColor.B + " != " + target.B);
        }
Exemplo n.º 20
0
 public HexLibrary(HexType hexType, OffsetCoordinatesType offsetCoordinatesType, float hexSize)
 {
     _hex = hexType switch
     {
         HexType.FlatTopped => new HexFlatTopped(offsetCoordinatesType, hexSize),
         HexType.PointyTopped => new HexPointyTopped(offsetCoordinatesType, hexSize),
         _ => throw new ArgumentOutOfRangeException(nameof(hexType), hexType, $"HexType {hexType} is not supported.")
     };
 }
        /// <summary>Returns an <c>IDirectedPath</c> for the optimal path from coordinates <c>start</c> to <c>goal</c>.</summary>
        /// <param name="start">Coordinates for the <c>last</c> step on the desired path.</param>
        /// <param name="goal">Coordinates for the <c>first</c> step on the desired path.</param>
        /// <param name="board">An object satisfying the interface <c>INavigableBoardFwd</c>.</param>
        /// <returns></returns>
        /// ///<remarks>Note that <c>heuristic</c> <b>must</b> be monotonic in order for the algorithm to perform properly.</remarks>
#pragma warning disable 1658, 1584
        /// <seealso cref="http://www.cs.trincoll.edu/~ram/cpsc352/notes/astar.html"/>
#pragma warning restore 1633, 1658, 1584
        public static IDirectedPath FindDirectedPathFwd(
          IHex start,
          IHex goal,
          IDirectedNavigableBoard board
        )
        {
            if (board == null) throw new ArgumentNullException("board");
            return FindDirectedPathFwd(start, goal, board.DirectedStepCost, board.Heuristic);
        }
 /// <summary>As <c>FindDirectedPathFwd</c>, except with the steps stacked in reverse.</summary>
 /// <remarks>
 /// The path steps are ordered in reverse as the forward half-path has been stacked
 /// onto the reverse half-path during post-processing, instead of the reverse.
 /// </remarks>
 /// <see cref="FindDirectedPathFwd"/>
 public static IDirectedPath FindDirectedPathRev(
     IHex start, IHex goal, IDirectedNavigableBoard board
     )
 {
     if (board == null)
     {
         throw new ArgumentNullException("board");
     }
     return(FindDirectedPath(start, goal, board.DirectedStepCost, board.Landmarks).PathRev);
 }
Exemplo n.º 23
0
 /// <summary>Returns the requested neighbours for this hex.</summary>
 /// <param name="this">TODO</param>
 /// <param name="here">TODO</param>
 /// <returns></returns>
 public static IEnumerable <NeighbourHex> GetNeighbourHexes(
     this INavigableBoard <IHex> @this, IHex here
     )
 {
     if (@this == null)
     {
         throw new ArgumentNullException("this");
     }
     return(@this.GetAllNeighbours(here).Where(n => n.Hex != null));
 }
Exemplo n.º 24
0
 public bool IsTileNW(IHex s, IHex t)
 {
     if (this.GetNW(s).Equals(t))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 25
0
 /// <summary>All neighbours of this hex, as an <see cref="IEnumerable {NeighbourHex}"/></summary>
 public static IEnumerable <NeighbourHex> GetAllNeighbours(
     this INavigableBoard <IHex> @this, IHex here
     )
 {
     if (@this == null)
     {
         throw new ArgumentNullException("this");
     }
     return(HexsideExtensions.HexsideList.Select(hexside =>
                                                 new NeighbourHex(@this[here.Coords.GetNeighbour(hexside)], hexside.Reversed())));
 }
Exemplo n.º 26
0
        public IHex GetRandomNearbyTile(int probes, IHex tile)
        {
            var currNeighbors = tile.GetAdjacent();

            for (int i = 0; i < probes; i++)
            {
                var random = ListUtil <IHex> .GetRandomElement(currNeighbors);

                currNeighbors = random.GetAdjacent();
            }
            return(ListUtil <IHex> .GetRandomElement(currNeighbors));
        }
Exemplo n.º 27
0
 public void AddTile(IHex t, IPathable navigator)
 {
     if (this._tiles.Count == 0)
     {
         this._score += navigator.GetTileTraversalCost(navigator.GetCurrentTile(), t);
     }
     else
     {
         this._score += navigator.GetTileTraversalCost(this._tiles[this._tiles.Count - 1], t);
     }
     this._tiles.Add(t);
 }
     /// <summary>Returns an <c>IDirectedPath</c> for the optimal path from coordinates <c>start</c> to <c>goal</c>.</summary>
     /// <param name="start">Coordinates for the <c>last</c> step on the desired path.</param>
     /// <param name="goal">Coordinates for the <c>first</c> step on the desired path.</param>
     /// <param name="board">An object satisfying the interface <c>INavigableBoardFwd</c>.</param>
     /// <returns></returns>
     /// ///<remarks>Note that <c>heuristic</c> <b>must</b> be monotonic in order for the algorithm to perform properly.</remarks>
 #pragma warning disable 1658, 1584
     /// <seealso cref="http://www.cs.trincoll.edu/~ram/cpsc352/notes/astar.html"/>
 #pragma warning restore 1633, 1658, 1584
     public static IDirectedPath FindDirectedPathFwd(
         IHex start,
         IHex goal,
         IDirectedNavigableBoard board
         )
     {
         if (board == null)
         {
             throw new ArgumentNullException("board");
         }
         return(FindDirectedPathFwd(start, goal, board.DirectedStepCost, board.Heuristic));
     }
Exemplo n.º 29
0
 public IHex GetNextTile(IHex t)
 {
     if (this._tiles.Contains(t))
     {
         int index = this._tiles.IndexOf(t) + 1;
         if (this._tiles.Count > index)
         {
             return(this._tiles[index]);
         }
     }
     return(null);
 }
Exemplo n.º 30
0
 /// <summary>Asynchronously returns a least-cost path from the hex <c>source</c> to the hex <c>target.</c></summary>
 public static Task <IDirectedPathCollection> GetDirectedPathAsync(
     this IHexBoard <IHex> @this, IHex source, IHex target, bool forceUnidirectional
     )
 {
     if (@this == null)
     {
         throw new ArgumentNullException("this");
     }
     return(Task.Run <IDirectedPathCollection>(
                () => @this.GetDirectedPath(source, target, forceUnidirectional)
                ));
 }
Exemplo n.º 31
0
        public int GetTileTraversalCost(IHex source, IHex goal)
        {
            double baseCost = this.GetTileTraversalCostHelper(source, goal);

            if (goal.GetHeight() > source.GetHeight())
            {
                return((int)(baseCost * (goal.GetHeight() - source.GetHeight())));
            }
            else
            {
                return((int)baseCost);
            }
        }
Exemplo n.º 32
0
		/// <summary>
		/// Upload the specified image_data.
		/// </summary>
		/// <param name='image_data'>
		/// Image_data to be uploaded.
		/// </param>
		public void upload (SerialPort on_port, IHex image_data)
		{
			progress (0);
			
			port = on_port;
			
			try {
				connect_and_sync ();
				upload_and_verify (image_data);
				cmdReboot ();
			} catch (Exception e) {
				if (port.IsOpen)
					port.Close ();
				throw e;
			}
		}
Exemplo n.º 33
0
		/// <summary>
		/// Upload the specified image_data.
		/// </summary>
		/// <param name='image_data'>
		/// Image_data to be uploaded.
		/// </param>
		public void upload (ICommsSerial on_port, IHex image_data, bool use_mavlink = false)
		{
			progress (0);
			
			port = on_port;
			
			try {
                connect_and_sync();
				upload_and_verify (image_data);
				cmdReboot ();
			} catch {
				if (port.IsOpen)
					port.Close ();
				throw;
			}
		}
        BidirectionalPathfinder(IHex start, IHex goal,
          LandmarkCollection landmarks, HashSet<HexCoords> closed, Func<double> getBestSoFar
        )
        {
            _start = start;
            _goal = goal;
            _getBestSoFar = getBestSoFar;
            _vectorGoal = goal.Coords.Canon - start.Coords.Canon;
            _open = new Dictionary<HexCoords, DirectedPath>();
            _closed = closed;
            _queue = new HotPriorityQueue<DirectedPath>(16);
            _landmark = landmarks
                    .OrderByDescending(l => l.HexDistance(goal.Coords) - l.HexDistance(start.Coords))
                    .FirstOrDefault();
            _heuristic = c => _landmark.HexDistance(c) - _landmark.HexDistance(start.Coords);

            var path = new DirectedPath(goal);
            _open.Add(goal.Coords, path);
            _queue.Enqueue(0, path);
        }
Exemplo n.º 35
0
Arquivo: Main.cs Projeto: cjswin/SiK
		public AppLogic ()
		{
			// Get the current configuration file.
			config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
		
			// Look for our settings and add/create them if missing
			if (config.Sections [config_name] == null) {
				config_section = new ConfigSection ();
				config.Sections.Add (config_name, config_section);
				config_section.SectionInformation.ForceSave = true;
				config.Save (ConfigurationSaveMode.Full);
			}
			config_section = config.GetSection (config_name) as ConfigSection;

			// Hook up main window events
			win = new MainWindow ();
			win.MonitorEvent += show_monitor;
			win.UploadEvent += do_upload;
			win.LogEvent += log;
			win.QuitEvent += at_exit;
			
			// restore the last path that we uploaded
			win.FileName = config_section.lastPath;
			
			// restore the last port that we opened
			win.PortName = config_section.lastPort;
			
			// Create the intelhex loader
			ihex = new IHex ();
			ihex.LogEvent += log;
			
			// And the uploader
			upl = new Uploader ();
			upl.LogEvent += log;
			upl.ProgressEvent += win.set_progress;
			
			// Emit some basic help
			log ("Select a serial port and a .hex file to be uploaded, then hit Upload.\n");
			
			win.Show ();
		}
Exemplo n.º 36
0
        public override void DefineCircum()
        {
            Circum = new IHex[6];
            Neighbors = new List<Hex>();
            int i = 0;

            foreach (var index in CircumIndices)
            {
                var hex = map.Get(index);
                if (hex)
                {
                    Neighbors.Add(hex);
                    Circum[i] = hex;
                }
                else
                {
                    Circum[i] = nihility.GetDefinedNull(index);
                }

                i++;
            }
        }
Exemplo n.º 37
0
 public HexVM(IHex HexModel, SettlerBoard board)
 {
     hexModel = HexModel;
     CalulateHexagonValues();
     // Calculate how much it needs to shift
     if (board.GameBoard.GetRange(0, 3).Contains(HexModel))
     {
         offsetX = b + s;
         int indexValue = board.GameBoard.IndexOf(HexModel);
         offsetX += indexValue * (h + s);
         offsetY = indexValue * r;
     }
     else if (board.GameBoard.GetRange(3,4).Contains(HexModel))
     {
         offsetX = s + h;
         int indexValue = board.GameBoard.IndexOf(HexModel) - 3;
         offsetX += indexValue * (h + s);
         offsetY = (indexValue + 1) * r;
     }
     else if (board.GameBoard.GetRange(7, 5).Contains(HexModel))
     {
         int indexValue = board.GameBoard.IndexOf(HexModel) - 7;
         offsetX += indexValue * (h + s);
         offsetY = (indexValue + 2) * r;
     }
     else if (board.GameBoard.GetRange(12, 4).Contains(HexModel))
     {
         int indexValue = board.GameBoard.IndexOf(HexModel) - 12;
         offsetX += indexValue * (h + s);
         offsetY = (indexValue + 4) * r;
     }
     else if (board.GameBoard.GetRange(16, 3).Contains(HexModel))
     {
         int indexValue = board.GameBoard.IndexOf(HexModel) - 16;
         offsetX += indexValue * (h + s);
         offsetY = (indexValue + 6) * r;
     }
 }
Exemplo n.º 38
0
        public void DefineCircum()
        {
            var nihility = GameServices.Get<Nihility>();
            var map = GameServices.Get<GameMap>();
            Circum = new IHex[6];

            for (int i = 0; i < CircumIndices.Length; i++)
            {
                var index = CircumIndices[i];
                IHex hexAround = nihility.Get(index);
                if (hexAround == null)
                {
                    hexAround = map.Get(index);
                    if (hexAround == null)
                    {
                        Circum[i] = nihility.GetUndefinedNull(index);
                        continue;
                    }
                }

                Circum[i] = hexAround;
            }
        }
 /// <summary>As <c>FindDirectedPathFwd</c>, except with the steps stacked in reverse.</summary>
 /// <remarks>
 /// The path steps are ordered in reverse as the forward half-path has been stacked 
 /// onto the reverse half-path during post-processing, instead of the reverse.
 /// </remarks>
 /// <see cref="FindDirectedPathFwd"/>
 public static IDirectedPath FindDirectedPathRev(
   IHex start, IHex goal, IDirectedNavigableBoard board
 )
 {
     if (board == null) throw new ArgumentNullException("board");
     return FindDirectedPath(start, goal, board.DirectedStepCost, board.Landmarks).PathRev;
 }
Exemplo n.º 40
0
        private void upload_and_verify(IHex image_data)
        {
            // erase the program area first
            log ("erasing program flash\n");
            cmdErase ();

            // progress fractions
            bytes_to_process = 0;
            foreach (byte[] bytes in image_data.Values) {
                bytes_to_process += bytes.Length;
            }
            bytes_to_process *= 2;		// once to program, once to verify
            bytes_processed = 0;

            // program the flash blocks
            log ("programming\n");
            foreach (KeyValuePair<UInt32, byte[]> kvp in image_data) {
                // move the program pointer to the base of this block
                cmdSetAddress (kvp.Key);
                log (string.Format ("prog 0x{0:X}/{1}\n", kvp.Key, kvp.Value.Length), 1);

                upload_block_multi (kvp.Value);
            }

            // and read them back to verify that they were programmed
            log ("verifying\n");
            foreach (KeyValuePair<UInt32, byte[]> kvp in image_data) {
                // move the program pointer to the base of this block
                cmdSetAddress (kvp.Key);
                log (string.Format ("verf 0x{0:X}/{1}\n", kvp.Key, kvp.Value.Length), 1);

                verify_block_multi (kvp.Value);
                bytes_processed += kvp.Value.GetLength (0);
                progress ((double)bytes_processed / bytes_to_process);
            }
            log ("Success\n");
        }
Exemplo n.º 41
0
		private void upload_and_verify (IHex image_data)
		{
            if (image_data.bankingDetected && ((byte)id & 0x80) != 0x80)
            {
                log("This Firmware requires banking support");
                throw new Exception("This Firmware requires banking support");
            }

            if ((((byte)id & 0x80) == 0x80))
            {
                this.banking = true;
                log("Using 24bit addresses");
            }
			
			// erase the program area first
			log ("erasing program flash\n");
			cmdErase ();
			
			// progress fractions
			bytes_to_process = 0;
			foreach (byte[] bytes in image_data.Values) {
				bytes_to_process += bytes.Length;
			}
			bytes_to_process *= 2;		// once to program, once to verify
			bytes_processed = 0;
			
			// program the flash blocks
			log ("programming\n");
			foreach (KeyValuePair<UInt32, byte[]> kvp in image_data) {
				// move the program pointer to the base of this block
				cmdSetAddress (kvp.Key);
				log (string.Format ("prog 0x{0:X}/{1}\n", kvp.Key, kvp.Value.Length), 1);

				upload_block_multi (kvp.Value);
			}
			
			// and read them back to verify that they were programmed
			log ("verifying\n");
			foreach (KeyValuePair<UInt32, byte[]> kvp in image_data) {
				// move the program pointer to the base of this block
				cmdSetAddress (kvp.Key);
				log (string.Format ("verf 0x{0:X}/{1}\n", kvp.Key, kvp.Value.Length), 1);
				
				verify_block_multi (kvp.Value);
				bytes_processed += kvp.Value.GetLength (0);
				progress ((double)bytes_processed / bytes_to_process);
			}
			log ("Success\n");
		}
Exemplo n.º 42
0
        private void UploadFW(bool custom = false)
        {
            ICommsSerial comPort = new SerialPort();

            var uploader = new Uploader();

            if (MainV2.comPort.BaseStream.IsOpen)
            {
                try
                {
                    getTelemPortWithRadio(ref comPort);

                    uploader.PROG_MULTI_MAX = 64;
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show("Error " + ex);
                }
            }

            try
            {
                comPort.PortName = MainV2.comPort.BaseStream.PortName;
                comPort.BaudRate = 115200;

                comPort.Open();
            }
            catch
            {
                CustomMessageBox.Show("Invalid ComPort or in use");
                return;
            }

            // prep what we are going to upload
            var iHex = new IHex();

            iHex.LogEvent += iHex_LogEvent;

            iHex.ProgressEvent += iHex_ProgressEvent;

            var bootloadermode = false;

            // attempt bootloader mode
            try
            {
                if (upload_xmodem(comPort))
                {
                    comPort.Close();
                    return;
                }

                comPort.BaudRate = 115200;

                uploader_ProgressEvent(0);
                uploader_LogEvent("Trying Bootloader Mode");

                uploader.port = comPort;
                uploader.connect_and_sync();

                uploader.ProgressEvent += uploader_ProgressEvent;
                uploader.LogEvent += uploader_LogEvent;

                uploader_LogEvent("In Bootloader Mode");
                bootloadermode = true;
            }
            catch (Exception ex1)
            {
                log.Error(ex1);

                // cleanup bootloader mode fail, and try firmware mode
                comPort.Close();
                if (MainV2.comPort.BaseStream.IsOpen)
                {
                    // default baud... guess
                    comPort.BaudRate = 57600;
                }
                else
                {
                    comPort.BaudRate = MainV2.comPort.BaseStream.BaudRate;
                }
                try
                {
                    comPort.Open();
                }
                catch
                {
                    CustomMessageBox.Show("Error opening port", "Error");
                    return;
                }

                uploader.ProgressEvent += uploader_ProgressEvent;
                uploader.LogEvent += uploader_LogEvent;

                uploader_LogEvent("Trying Firmware Mode");
                bootloadermode = false;
            }

            // check for either already bootloadermode, or if we can do a ATI to ID the firmware 
            if (bootloadermode || doConnect(comPort))
            {
                // put into bootloader mode/update mode
                if (!bootloadermode)
                {
                    try
                    {
                        comPort.Write("AT&UPDATE\r\n");
                        var left = comPort.ReadExisting();
                        log.Info(left);
                        Sleep(700);
                        comPort.BaudRate = 115200;
                    }
                    catch
                    {
                    }

                    if (upload_xmodem(comPort))
                    {
                        comPort.Close();
                        return;
                    }

                    comPort.BaudRate = 115200;
                }

                try
                {
                    // force sync after changing baudrate
                    uploader.connect_and_sync();
                }
                catch
                {
                    CustomMessageBox.Show("Failed to sync with Radio");
                    goto exit;
                }

                var device = Uploader.Board.FAILED;
                var freq = Uploader.Frequency.FAILED;

                // get the device type and frequency in the bootloader
                uploader.getDevice(ref device, ref freq);

                // get firmware for this device
                if (getFirmware(device, custom))
                {
                    // load the hex
                    try
                    {
                        iHex.load(firmwarefile);
                    }
                    catch
                    {
                        CustomMessageBox.Show("Bad Firmware File");
                        goto exit;
                    }

                    // upload the hex and verify
                    try
                    {
                        uploader.upload(comPort, iHex);
                    }
                    catch (Exception ex)
                    {
                        CustomMessageBox.Show("Upload Failed " + ex.Message);
                    }
                }
                else
                {
                    CustomMessageBox.Show("Failed to download new firmware");
                }
            }
            else
            {
                CustomMessageBox.Show("Failed to identify Radio");
            }

            exit:
            if (comPort.IsOpen)
                comPort.Close();
        }
        /// <summary>Returns an <c>IPath</c> for the optimal path from coordinates <c>start</c> to <c>goal</c>.</summary>
        /// <param name="start">Coordinates for the <c>last</c> step on the desired path.</param>
        /// <param name="goal">Coordinates for the <c>first</c> step on the desired path.</param>
        /// <param name="stepCost">Cost to extend path by hex at <c>coords</c> from hex at direction <c>hexside</c>.</param>
        /// <param name="landmarks"><c>LandmarkCollection</c> of landmarks available for heuristic calculation.</param>
        static PathHalves FindDirectedPath(
          IHex start, IHex goal,
          Func<IHex, Hexside, double> stepCost,
          LandmarkCollection landmarks
        )
        {
            if (start == null) throw new ArgumentNullException("start");
            if (goal == null) throw new ArgumentNullException("goal");
            if (stepCost == null) throw new ArgumentNullException("stepCost");
            if (landmarks == null) throw new ArgumentNullException("landmarks");

            var closed = new HashSet<HexCoords>();
            var pathHalves = new PathHalves();

            var pathfinderFwd = new PathfinderFwd(start, goal, stepCost, landmarks,
                                closed, pathHalves.SetBestSoFar, () => pathHalves.BestSoFar);
            var pathfinderRev = new PathfinderRev(start, goal, stepCost, landmarks,
                                closed, pathHalves.SetBestSoFar, () => pathHalves.BestSoFar);

            pathfinderFwd.Partner = pathfinderRev;
            var pathfinder = pathfinderRev.Partner
                                  = pathfinderFwd;
            while (!pathfinder.IsFinished()) pathfinder = pathfinder.Partner;

            return pathHalves;
        }
 int Estimate(IHex here, IHex there, double totalCost)
 {
     var estimate = _heuristic(there.Coords) + (int)totalCost;
     var preference = Preference(_start.Coords.Canon - there.Coords.Canon,
                                 _start.Coords.Canon - _goal.Coords.Canon);
     return (estimate << 16) + preference;
 }
            /// <summary>Create a new instance of <see cref="PathfinderRev"/>.</summary>
            /// <param name="start"></param>
            /// <param name="goal"></param>
            /// <param name="stepCost"></param>
            /// <param name="landmarks"></param>
            /// <param name="closed"></param>
            /// <param name="setBestSoFar"></param>
            /// <param name="getBestSoFar"></param>
            public PathfinderRev(IHex start, IHex goal, Func<IHex, Hexside, double> stepCost,
              LandmarkCollection landmarks, HashSet<HexCoords> closed,
              Action<DirectedPath, DirectedPath> setBestSoFar, Func<double> getBestSoFar
            )
                : base(goal, start, landmarks, closed, getBestSoFar)
            {
                _addStep = (path, there, hexside, cost) => path.AddStep(there, hexside.Reversed(), cost);
                _setBestSoFar = (self, partner) => setBestSoFar(partner, self);
                _stepCost = (here, hexside, there) => stepCost(here, hexside);

                //_search = "Rev";
            }
        /// <summary>Returns an <c>IPath</c> for the optimal path from coordinates <c>start</c> to <c>goal</c>.</summary>
        /// <param name="start">Coordinates for the <c>last</c> step on the desired path.</param>
        /// <param name="goal">Coordinates for the <c>first</c> step on the desired path.</param>
        /// <param name="stepCost">Cost to extend path by hex at <c>coords</c> from hex at direction <c>hexside</c>.</param>
        /// <param name="heuristic">Returns a monotonic (ie locally admissible) cost estimate from a range value.</param>
        /// <returns></returns>
        /// ///<remarks>Note that <c>heuristic</c> <b>must</b> be monotonic in order for the algorithm to perform properly.</remarks>
#pragma warning disable 1658, 1584
        /// <seealso cref="http://www.cs.trincoll.edu/~ram/cpsc352/notes/astar.html"/>
#pragma warning restore 1658, 1584
        public static IDirectedPath FindDirectedPathFwd(
          IHex start,
          IHex goal,
          Func<IHex, Hexside, double> stepCost,
          Func<int, int> heuristic
        )
        {
            if (start == null) throw new ArgumentNullException("start");
            if (goal == null) throw new ArgumentNullException("goal");
            if (stepCost == null) throw new ArgumentNullException("stepCost");

            var vectorGoal = goal.Coords.Canon - start.Coords.Canon;
            var closed = new HashSet<HexCoords>();
            var open = new HashSet<HexCoords>();
            var queue = new DictionaryPriorityQueue<double, DirectedPath>();

            queue.Enqueue(0, new DirectedPath(goal));

            HexKeyValuePair<double, DirectedPath> item;
            while (queue.TryDequeue(out item))
            {
                var path = item.Value;
                open.Add(path.PathStep.Hex.Coords);
                if (closed.Contains(path.PathStep.Hex.Coords)) continue;

                if (path.PathStep.Hex.Equals(start))
                {
                    return path;
                }

                closed.Add(path.PathStep.Hex.Coords);

                foreach (var neighbour in path.PathStep.Hex.GetNeighbourHexes()
                )
                {
                    if (!open.Contains(neighbour.Hex.Coords))
                    {
                        var cost = stepCost(neighbour.Hex, neighbour.HexsideExit);
                        if (cost > 0)
                        {
                            var newPath = path.AddStep(neighbour, cost);
                            var key = Estimate(heuristic, vectorGoal, start.Coords, neighbour.Hex.Coords,
                                            newPath.TotalCost);
                            queue.Enqueue(key, newPath);
                        }
                    }
                }
            }
            return null;
        }