Ejemplo n.º 1
0
        /// <summary>
        /// Get fw version from firmeware.diydrones.com
        /// </summary>
        /// <param name="fwurl"></param>
        /// <returns></returns>
        void getAPMVersion(object tempin)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = L10N.ConfigLang;

            try
            {
                software temp = (software)tempin;

                string baseurl = temp.urlpx4v2;

                if (baseurl == "")
                {
                    return;
                }

                L10N.ReplaceMirrorUrl(ref baseurl);

                Uri url = new Uri(new Uri(baseurl), "git-version.txt");

                log.Info("Get url " + url.ToString());

                updateProgress(-1, Strings.GettingFWVersion);

                WebRequest  wr    = WebRequest.Create(url);
                WebResponse wresp = wr.GetResponse();

                StreamReader sr = new StreamReader(wresp.GetResponseStream());

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    if (line.Contains("APMVERSION:"))
                    {
                        log.Info(line);

                        // get index
                        var index = softwares.IndexOf(temp);
                        // get item to modify
                        var item = softwares[index];
                        // change name
                        item.name = line.Substring(line.IndexOf(':') + 2);
                        // save back to list
                        softwares[index] = item;

                        return;
                    }
                }

                log.Info("no answer");
            }
            catch (Exception ex) { log.Error(ex); }
            finally
            {
                lock (this)
                {
                    ingetapmversion--;
                }
            }
        }
Ejemplo n.º 2
0
        static void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url)
        {
            var baseurl = ConfigurationManager.AppSettings["UpdateLocation"];

            if (dobeta)
            {
                baseurl = ConfigurationManager.AppSettings["BetaUpdateLocation"];
            }

            L10N.ReplaceMirrorUrl(ref baseurl);

            WebRequest request = WebRequest.Create(url);

            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the request stream.
            Stream dataStream; //= request.GetRequestStream();
            // Get the response.
            WebResponse response = request.GetResponse();

            // Display the status.
            log.Info(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            Regex regex = new Regex(@"([^\s]+)\s+upgrade/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                MatchCollection matchs = regex.Matches(responseFromServer);
                for (int i = 0; i < matchs.Count; i++)
                {
                    string hash = matchs[i].Groups[1].Value.ToString();
                    string file = matchs[i].Groups[2].Value.ToString();

                    if (file.ToLower().EndsWith(".etag"))
                    {
                        try
                        {
                            // remove all etags
                            File.Delete(file);
                        }
                        catch
                        {
                        }
                        continue;
                    }

                    // check if existing matchs hash
                    if (!MD5File(file, hash))
                    {
                        log.Info("Newer File " + file);

                        // check is we have already downloaded and matchs hash
                        if (!MD5File(file + ".new", hash))
                        {
                            if (frmProgressReporter != null)
                            {
                                frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Getting + file);
                            }

                            string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar;

                            GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir,
                                       Path.GetFileName(file));

                            // check the new downloaded file matchs hash
                            if (!MD5File(file + ".new", hash))
                            {
                                throw new Exception("File downloaded does not match hash: " + file);
                            }
                        }
                        else
                        {
                            log.Info("already got new File " + file);
                        }
                    }
                    else
                    {
                        log.Info("Same File " + file);

                        if (frmProgressReporter != null)
                        {
                            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file);
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        static void CheckMD5(IProgressReporterDialogue frmProgressReporter, string md5url, string baseurl)
        {
            L10N.ReplaceMirrorUrl(ref baseurl);

            string responseFromServer = "";

            WebRequest request = WebRequest.Create(md5url);

            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the response.
            // Get the stream containing content returned by the server.
            // Open the stream using a StreamReader for easy access.
            using (WebResponse response = request.GetResponse())
                using (Stream dataStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        // Display the status.
                        log.Info(((HttpWebResponse)response).StatusDescription);
                        // Read the content.
                        responseFromServer = reader.ReadToEnd();
                    }

            Regex regex = new Regex(@"([^\s]+)\s+[^/]+/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                // background md5
                List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >();

                if (frmProgressReporter != null)
                {
                    frmProgressReporter.UpdateProgressAndStatus(-1, "Hashing Files");
                }

                // hash everything
                MatchCollection matchs = regex.Matches(responseFromServer);
                for (int i = 0; i < matchs.Count; i++)
                {
                    string hash = matchs[i].Groups[1].Value.ToString();
                    string file = matchs[i].Groups[2].Value.ToString();

                    Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash));

                    tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch));
                }

                // get count and wait for all hashing to be done
                int count = tasklist.Count(a =>
                {
                    a.Item3.Wait();
                    return(!a.Item3.Result);
                });

                // parallel download
                ParallelOptions opt = new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 3
                };

                int done = 0;

                Parallel.ForEach(tasklist, opt, task =>
                                 //foreach (var task in tasklist)
                {
                    string file = task.Item1;
                    string hash = task.Item2;
                    // check if existing matchs hash
                    task.Item3.Wait();
                    bool match = task.Item3.Result;

                    if (!match)
                    {
                        done++;
                        log.Info("Newer File " + file);

                        // check is we have already downloaded and matchs hash
                        if (!MD5File(file + ".new", hash))
                        {
                            if (frmProgressReporter != null)
                            {
                                frmProgressReporter.UpdateProgressAndStatus((int)((done / (double)count) * 100),
                                                                            Strings.Getting + file + "\n" + done + " of " + count + " of total " +
                                                                            tasklist.Count);
                            }

                            string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar;

                            subdir = subdir.Replace("" + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar,
                                                    "" + Path.DirectorySeparatorChar);

                            if (baseurl.ToLower().Contains(".zip"))
                            {
                                GetNewFileZip(frmProgressReporter, baseurl, subdir,
                                              Path.GetFileName(file));
                            }
                            else
                            {
                                GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir,
                                           Path.GetFileName(file));
                            }

                            // check the new downloaded file matchs hash
                            if (!MD5File(file + ".new", hash))
                            {
                                throw new Exception("File downloaded does not match hash: " + file);
                            }
                        }
                        else
                        {
                            log.Info("already got new File " + file);
                        }
                    }
                    else
                    {
                        log.Info("Same File " + file);

                        if (frmProgressReporter != null)
                        {
                            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file);
                        }
                    }
                });
            }
        }
Ejemplo n.º 4
0
        public static void CheckForUpdate(bool NotifyNoUpdate = false)
        {
            if (Program.WindowsStoreApp)
            {
                return;
            }

            var baseurl = ConfigurationManager.AppSettings["UpdateLocationVersion"];

            if (dobeta)
            {
                baseurl = ConfigurationManager.AppSettings["BetaUpdateLocationVersion"];
            }

            if (baseurl == "")
            {
                return;
            }

            string path = Path.GetDirectoryName(Application.ExecutablePath);

            path = path + Path.DirectorySeparatorChar + "version.txt";

            ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(
                    (sender, certificate, chain, policyErrors) => { return(true); });

            log.Debug(path);

            // Create a request using a URL that can receive a post.
            string requestUriString = baseurl + Path.GetFileName(path);

            L10N.ReplaceMirrorUrl(ref requestUriString);

            log.Info("Checking for update at: " + requestUriString);
            var webRequest = WebRequest.Create(requestUriString);

            webRequest.Timeout = 5000;

            // Set the Method property of the request to POST.
            webRequest.Method = "GET";

            // ((HttpWebRequest)webRequest).IfModifiedSince = File.GetLastWriteTimeUtc(path);

            bool updateFound = false;

            // Get the response.
            using (var response = webRequest.GetResponse())
            {
                // Display the status.
                log.Debug("Response status: " + ((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.

                if (File.Exists(path))
                {
                    var fi = new FileInfo(path);

                    Version LocalVersion = new Version();
                    Version WebVersion   = new Version();

                    if (File.Exists(path))
                    {
                        using (Stream fs = File.OpenRead(path))
                        {
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                LocalVersion = new Version(sr.ReadLine());
                            }
                        }
                    }

                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        WebVersion = new Version(sr.ReadLine());
                    }

                    log.Info("New file Check: local " + LocalVersion + " vs Remote " + WebVersion);

                    if (LocalVersion < WebVersion)
                    {
                        updateFound = true;
                    }
                }
                else
                {
                    updateFound = true;
                    log.Info("File does not exist: Getting " + path);
                    // get it
                }
            }

            if (updateFound)
            {
                // do the update in the main thread
                MainV2.instance.Invoke((MethodInvoker) delegate
                {
                    string extra = "";

                    if (dobeta)
                    {
                        extra = "BETA ";
                    }

                    DialogResult dr = DialogResult.Cancel;


                    dr = CustomMessageBox.Show(
                        extra + Strings.UpdateFound + " [link;" + baseurl + "/ChangeLog.txt;ChangeLog]",
                        Strings.UpdateNow, MessageBoxButtons.YesNo);

                    if (dr == DialogResult.Yes)
                    {
                        DoUpdate();
                    }
                    else
                    {
                        return;
                    }
                });
            }
            else if (NotifyNoUpdate)
            {
                CustomMessageBox.Show(Strings.UpdateNotFound);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Do full update - get firmware from internet
        /// </summary>
        /// <param name="temp"></param>
        /// <param name="historyhash"></param>
        public bool update(string comport, software temp, string historyhash)
        {
            BoardDetect.boards board = BoardDetect.boards.none;

            try
            {
                updateProgress(-1, Strings.DetectingBoardVersion);

                board = BoardDetect.DetectBoard(comport);

                if (board == BoardDetect.boards.none)
                {
                    CustomMessageBox.Show(Strings.CantDetectBoardVersion);
                    return(false);
                }

                int apmformat_version = -1; // fail continue

                if (board != BoardDetect.boards.px4 && board != BoardDetect.boards.px4v2 && board != BoardDetect.boards.vrbrainv40 && board != BoardDetect.boards.vrbrainv45 && board != BoardDetect.boards.vrbrainv50 && board != BoardDetect.boards.vrbrainv51 && board != BoardDetect.boards.vrbrainv52 && board != BoardDetect.boards.vrherov10 && board != BoardDetect.boards.vrubrainv51 && board != BoardDetect.boards.vrubrainv52 && board != BoardDetect.boards.vrgimbalv20 && board != BoardDetect.boards.vrugimbalv11)
                {
                    try
                    {
                        apmformat_version = BoardDetect.decodeApVar(comport, board);
                    }
                    catch { }

                    if (apmformat_version != -1 && apmformat_version != temp.k_format_version)
                    {
                        if (DialogResult.No == CustomMessageBox.Show(Strings.EppromChanged, String.Format(Strings.EppromFormatChanged, apmformat_version, temp.k_format_version), MessageBoxButtons.YesNo))
                        {
                            CustomMessageBox.Show(Strings.PleaseConnectAndBackupConfig);
                            return(false);
                        }
                    }
                }


                log.Info("Detected a " + board);

                updateProgress(-1, Strings.DetectedA + board);

                string baseurl = "";
                if (board == BoardDetect.boards.b2560)
                {
                    baseurl = temp.url2560.ToString();
                }
                else if (board == BoardDetect.boards.b1280)
                {
                    baseurl = temp.url.ToString();
                }
                else if (board == BoardDetect.boards.b2560v2)
                {
                    baseurl = temp.url2560_2.ToString();
                }
                else if (board == BoardDetect.boards.px4)
                {
                    baseurl = temp.urlpx4v1.ToString();
                }
                else if (board == BoardDetect.boards.px4v2)
                {
                    baseurl = temp.urlpx4v2.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv40)
                {
                    baseurl = temp.urlvrbrainv40.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv45)
                {
                    baseurl = temp.urlvrbrainv45.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv50)
                {
                    baseurl = temp.urlvrbrainv50.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv51)
                {
                    baseurl = temp.urlvrbrainv51.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv52)
                {
                    baseurl = temp.urlvrbrainv52.ToString();
                }
                else if (board == BoardDetect.boards.vrherov10)
                {
                    baseurl = temp.urlvrherov10.ToString();
                }
                else if (board == BoardDetect.boards.vrubrainv51)
                {
                    baseurl = temp.urlvrubrainv51.ToString();
                }
                else if (board == BoardDetect.boards.vrubrainv52)
                {
                    baseurl = temp.urlvrubrainv52.ToString();
                }
                else if (board == BoardDetect.boards.vrgimbalv20)
                {
                    baseurl = temp.urlvrgimbalv20.ToString();
                }
                else if (board == BoardDetect.boards.vrugimbalv11)
                {
                    baseurl = temp.urlvrugimbalv11.ToString();
                }
                else
                {
                    CustomMessageBox.Show(Strings.InvalidBoardType);
                    return(false);
                }

                if (board < BoardDetect.boards.px4)
                {
                    if (temp.name.ToLower().Contains("arducopter"))
                    {
                        CustomMessageBox.Show(Strings.ThisBoardHasBeenRetired, Strings.Note);
                    }
                }

                if (historyhash != "")
                {
                    baseurl = getUrl(historyhash, baseurl);
                }

                // update to use mirror url
                L10N.ReplaceMirrorUrl(ref baseurl);

                log.Info("Using " + baseurl);

                // Create a request using a URL that can receive a post.
                WebRequest request = WebRequest.Create(baseurl);
                request.Timeout = 10000;
                // Set the Method property of the request to POST.
                request.Method = "GET";
                // Get the request stream.
                Stream dataStream; //= request.GetRequestStream();
                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                log.Info(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();

                long bytes   = response.ContentLength;
                long contlen = bytes;

                byte[] buf1 = new byte[1024];

                FileStream fs = new FileStream(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", FileMode.Create);

                updateProgress(0, Strings.DownloadingFromInternet);

                dataStream.ReadTimeout = 30000;

                while (dataStream.CanRead)
                {
                    try
                    {
                        updateProgress(50, Strings.DownloadingFromInternet);
                    }
                    catch { }
                    int len = dataStream.Read(buf1, 0, 1024);
                    if (len == 0)
                    {
                        break;
                    }
                    bytes -= len;
                    fs.Write(buf1, 0, len);
                }

                fs.Close();
                dataStream.Close();
                response.Close();

                updateProgress(100, Strings.DownloadedFromInternet);
                log.Info("Downloaded");
            }
            catch (Exception ex)
            {
                updateProgress(50, Strings.FailedDownload);
                CustomMessageBox.Show("Failed to download new firmware : " + ex.ToString());
                return(false);
            }

            MissionPlanner.Utilities.Tracking.AddFW(temp.name, board.ToString());

            return(UploadFlash(comport, Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", board));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Load xml from internet based on firmwareurl, and return softwarelist
        /// </summary>
        /// <returns></returns>
        public List <software> getFWList(string firmwareurl = "")
        {
            if (firmwareurl == "")
            {
                firmwareurl = this.firmwareurl;
            }

            // mirror support
            L10N.ReplaceMirrorUrl(ref firmwareurl);

            log.Info("getFWList");

            string url              = "";
            string url2560          = "";
            string url2560_2        = "";
            string px4              = "";
            string px4v2            = "";
            string vrbrainv40       = "";
            string vrbrainv45       = "";
            string vrbrainv50       = "";
            string vrbrainv51       = "";
            string vrbrainv52       = "";
            string vrherov10        = "";
            string vrubrainv51      = "";
            string vrubrainv52      = "";
            string vrgimbalv20      = "";
            string vrugimbalv11     = "";
            string name             = "";
            string desc             = "";
            int    k_format_version = 0;

            softwares.Clear();

            software temp = new software();

            // this is for mono to a ssl server
            //ServicePointManager.CertificatePolicy = new NoCheckCertificatePolicy();
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender1, certificate, chain, policyErrors) => { return(true); });

            updateProgress(-1, Strings.GettingFWList);

            try
            {
                log.Info("url: " + firmwareurl);
                using (XmlTextReader xmlreader = new XmlTextReader(firmwareurl))
                {
                    while (xmlreader.Read())
                    {
                        xmlreader.MoveToElement();
                        switch (xmlreader.Name)
                        {
                        case "url":
                            url = xmlreader.ReadString();
                            break;

                        case "url2560":
                            url2560 = xmlreader.ReadString();
                            break;

                        case "url2560-2":
                            url2560_2 = xmlreader.ReadString();
                            break;

                        case "urlpx4":
                            px4 = xmlreader.ReadString();
                            break;

                        case "urlpx4v2":
                            px4v2 = xmlreader.ReadString();
                            break;

                        case "urlvrbrainv40":
                            vrbrainv40 = xmlreader.ReadString();
                            break;

                        case "urlvrbrainv45":
                            vrbrainv45 = xmlreader.ReadString();
                            break;

                        case "urlvrbrainv50":
                            vrbrainv50 = xmlreader.ReadString();
                            break;

                        case "urlvrbrainv51":
                            vrbrainv51 = xmlreader.ReadString();
                            break;

                        case "urlvrbrainv52":
                            vrbrainv52 = xmlreader.ReadString();
                            break;

                        case "urlvrherov10":
                            vrherov10 = xmlreader.ReadString();
                            break;

                        case "urlvrubrainv51":
                            vrubrainv51 = xmlreader.ReadString();
                            break;

                        case "urlvrubrainv52":
                            vrubrainv52 = xmlreader.ReadString();
                            break;

                        case "urlvrgimbalv20":
                            vrgimbalv20 = xmlreader.ReadString();
                            break;

                        case "urlvrugimbalv11":
                            vrugimbalv11 = xmlreader.ReadString();
                            break;

                        case "name":
                            name = xmlreader.ReadString();
                            break;

                        case "format_version":
                            k_format_version = int.Parse(xmlreader.ReadString());
                            break;

                        case "desc":
                            desc = xmlreader.ReadString();
                            break;

                        case "Firmware":
                            if (!name.Equals("") && !desc.Equals("Please Update"))
                            {
                                temp.desc             = desc.Trim();
                                temp.name             = name;
                                temp.url              = url;
                                temp.url2560          = url2560;
                                temp.url2560_2        = url2560_2;
                                temp.urlpx4v1         = px4;
                                temp.urlpx4v2         = px4v2;
                                temp.urlvrbrainv40    = vrbrainv40;
                                temp.urlvrbrainv45    = vrbrainv45;
                                temp.urlvrbrainv50    = vrbrainv50;
                                temp.urlvrbrainv51    = vrbrainv51;
                                temp.urlvrbrainv52    = vrbrainv52;
                                temp.urlvrherov10     = vrherov10;
                                temp.urlvrubrainv51   = vrubrainv51;
                                temp.urlvrubrainv52   = vrubrainv52;
                                temp.urlvrgimbalv20   = vrgimbalv20;
                                temp.urlvrugimbalv11  = vrugimbalv11;
                                temp.k_format_version = k_format_version;

                                try
                                {
                                    try
                                    {
                                        if (!url2560.Contains("github"))
                                        {
                                            //name =

                                            lock (this)
                                            {
                                                ingetapmversion++;
                                            }

                                            System.Threading.ThreadPool.QueueUserWorkItem(getAPMVersion, temp);

                                            //if (name != "")
                                            //temp.name = name;
                                        }
                                    }
                                    catch { }
                                }
                                catch { }     // just in case

                                softwares.Add(temp);
                            }
                            url              = "";
                            url2560          = "";
                            url2560_2        = "";
                            px4              = "";
                            px4v2            = "";
                            vrbrainv40       = "";
                            vrbrainv45       = "";
                            vrbrainv50       = "";
                            vrbrainv51       = "";
                            vrbrainv52       = "";
                            vrherov10        = "";
                            vrubrainv51      = "";
                            vrubrainv52      = "";
                            vrgimbalv20      = "";
                            vrugimbalv11     = "";
                            name             = "";
                            desc             = "";
                            k_format_version = 0;
                            temp             = new software();
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                //CustomMessageBox.Show("Failed to get Firmware List : " + ex.Message);
                throw;
            }

            while (ingetapmversion > 0)
            {
                System.Threading.Thread.Sleep(100);
            }

            log.Info("load done");

            updateProgress(-1, Strings.ReceivedList);

            return(softwares);
        }
Ejemplo n.º 7
0
        static void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url)
        {
            var baseurl = ConfigurationManager.AppSettings["UpdateLocation"];

            if (dobeta)
            {
                baseurl = ConfigurationManager.AppSettings["BetaUpdateLocation"];
            }

            L10N.ReplaceMirrorUrl(ref baseurl);

            string responseFromServer = "";

            WebRequest request = WebRequest.Create(url);

            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the response.
            // Get the stream containing content returned by the server.
            // Open the stream using a StreamReader for easy access.
            using (WebResponse response = request.GetResponse())
                using (Stream dataStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        // Display the status.
                        log.Info(((HttpWebResponse)response).StatusDescription);
                        // Read the content.
                        responseFromServer = reader.ReadToEnd();
                    }

            Regex regex = new Regex(@"([^\s]+)\s+upgrade/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >();

                MatchCollection matchs = regex.Matches(responseFromServer);
                for (int i = 0; i < matchs.Count; i++)
                {
                    string hash = matchs[i].Groups[1].Value.ToString();
                    string file = matchs[i].Groups[2].Value.ToString();

                    Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash));

                    tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch));
                }

                foreach (var task in tasklist)
                {
                    string file = task.Item1;
                    string hash = task.Item2;
                    // check if existing matchs hash
                    task.Item3.Wait();
                    bool match = task.Item3.Result;

                    if (!match)
                    {
                        log.Info("Newer File " + file);

                        // check is we have already downloaded and matchs hash
                        if (!MD5File(file + ".new", hash))
                        {
                            if (frmProgressReporter != null)
                            {
                                frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Getting + file);
                            }

                            string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar;

                            GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir,
                                       Path.GetFileName(file));

                            // check the new downloaded file matchs hash
                            if (!MD5File(file + ".new", hash))
                            {
                                throw new Exception("File downloaded does not match hash: " + file);
                            }
                        }
                        else
                        {
                            log.Info("already got new File " + file);
                        }
                    }
                    else
                    {
                        log.Info("Same File " + file);

                        if (frmProgressReporter != null)
                        {
                            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file);
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Do full update - get firmware from internet
        /// </summary>
        /// <param name="temp"></param>
        /// <param name="historyhash"></param>
        public bool update(string comport, software temp, string historyhash)
        {
            BoardDetect.boards board = BoardDetect.boards.none;

            try
            {
                updateProgress(-1, Strings.DetectingBoardVersion);

                board = BoardDetect.DetectBoard(comport);

                if (board == BoardDetect.boards.none)
                {
                    CustomMessageBox.Show(Strings.CantDetectBoardVersion);
                    return(false);
                }

                log.Info("Detected a " + board);

                updateProgress(-1, Strings.DetectedA + board);

                string baseurl = "";
                if (board == BoardDetect.boards.b2560)
                {
                    baseurl = temp.url2560.ToString();
                }
                else if (board == BoardDetect.boards.b1280)
                {
                    baseurl = temp.url.ToString();
                }
                else if (board == BoardDetect.boards.b2560v2)
                {
                    baseurl = temp.url2560_2.ToString();
                }
                else if (board == BoardDetect.boards.px4)
                {
                    baseurl = temp.urlpx4v1.ToString();
                }
                else if (board == BoardDetect.boards.px4v2)
                {
                    baseurl = temp.urlpx4v2.ToString();
                }
                else if (board == BoardDetect.boards.px4v4)
                {
                    baseurl = temp.urlpx4v4.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv40)
                {
                    baseurl = temp.urlvrbrainv40.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv45)
                {
                    baseurl = temp.urlvrbrainv45.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv50)
                {
                    baseurl = temp.urlvrbrainv50.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv51)
                {
                    baseurl = temp.urlvrbrainv51.ToString();
                }
                else if (board == BoardDetect.boards.vrbrainv52)
                {
                    baseurl = temp.urlvrbrainv52.ToString();
                }
                else if (board == BoardDetect.boards.vrcorev10)
                {
                    baseurl = temp.urlvrcorev10.ToString();
                }
                else if (board == BoardDetect.boards.vrubrainv51)
                {
                    baseurl = temp.urlvrubrainv51.ToString();
                }
                else if (board == BoardDetect.boards.vrubrainv52)
                {
                    baseurl = temp.urlvrubrainv52.ToString();
                }
                else
                {
                    CustomMessageBox.Show(Strings.InvalidBoardType);
                    return(false);
                }

                if (board < BoardDetect.boards.px4)
                {
                    if (temp.name.ToLower().Contains("arducopter"))
                    {
                        CustomMessageBox.Show(Strings.ThisBoardHasBeenRetired, Strings.Note);
                    }
                }

                if (historyhash != "")
                {
                    baseurl = getUrl(historyhash, baseurl);
                }

                // update to use mirror url
                L10N.ReplaceMirrorUrl(ref baseurl);

                log.Info("Using " + baseurl);

                // Create a request using a URL that can receive a post.
                WebRequest request = WebRequest.Create(baseurl);
                request.Timeout = 10000;
                // Set the Method property of the request to POST.
                request.Method = "GET";
                // Get the request stream.
                Stream dataStream; //= request.GetRequestStream();
                // Get the response (using statement is exception safe)
                using (WebResponse response = request.GetResponse())
                {
                    // Display the status.
                    log.Info(((HttpWebResponse)response).StatusDescription);
                    // Get the stream containing content returned by the server.
                    using (dataStream = response.GetResponseStream())
                    {
                        long bytes   = response.ContentLength;
                        long contlen = bytes;

                        byte[] buf1 = new byte[1024];

                        using (FileStream fs = new FileStream(
                                   Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar +
                                   @"firmware.hex", FileMode.Create))
                        {
                            updateProgress(0, Strings.DownloadingFromInternet);

                            long length   = response.ContentLength;
                            long progress = 0;
                            dataStream.ReadTimeout = 30000;

                            while (dataStream.CanRead)
                            {
                                try
                                {
                                    updateProgress(length == 0 ? 50 : (int)((progress * 100) / length), Strings.DownloadingFromInternet);
                                }
                                catch
                                {
                                }
                                int len = dataStream.Read(buf1, 0, 1024);
                                if (len == 0)
                                {
                                    break;
                                }
                                progress += len;
                                bytes    -= len;
                                fs.Write(buf1, 0, len);
                            }

                            fs.Close();
                        }
                        dataStream.Close();
                    }
                    response.Close();
                }

                updateProgress(100, Strings.DownloadedFromInternet);
                log.Info("Downloaded");
            }
            catch (Exception ex)
            {
                updateProgress(50, Strings.FailedDownload);
                CustomMessageBox.Show("Failed to download new firmware : " + ex.ToString());
                return(false);
            }

            MissionPlanner.Utilities.Tracking.AddFW(temp.name, board.ToString());

            return(UploadFlash(comport,
                               Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", board));
        }