private ICollection <(byte Screen, byte Index, string Name)> GetOsdSlotInfoWithDialog() { if (!CheckConnected()) { return(new List <(byte Screen, byte Index, string Name)>()); } ICollection <(byte Screen, byte Index, string Name)> result = null; var dialog = new ProgressReporterDialogue() { StartPosition = FormStartPosition.CenterScreen, Text = "Fetching Param Names" }; CancellationTokenSource cts = new CancellationTokenSource(); dialog.DoWork += (s) => { result = OsdTuningSlotGetter.LoadAll(1, cts.Token); }; dialog.doWorkArgs.CancelRequestChanged += (s, e) => { if (dialog.doWorkArgs.CancelRequested) { cts.Cancel(); } }; dialog.RunBackgroundOperationAsync(); return(result); }
private void BUT_MagCalibration_Click(object sender, EventArgs e) { if (!MainV2.comPort.BaseStream.IsOpen) { CustomMessageBox.Show("You are no longer connected to the board\n the wizard will now exit", "Error"); Wizard.instance.Close(); } MainV2.comPort.MAV.cs.ratesensors = 2; MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA3, MainV2.comPort.MAV.cs.ratesensors); MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.comPort.MAV.cs.ratesensors); MainV2.comPort.setParam("MAG_ENABLE", 1); CustomMessageBox.Show("Data will be collected for 60 seconds, Please click ok and move the apm around all axises"); ProgressReporterDialogue prd = new ProgressReporterDialogue(); Utilities.ThemeManager.ApplyThemeTo(prd); prd.DoWork += prd_DoWork; prd.RunBackgroundOperationAsync(); if (ans != null) { MagCalib.SaveOffsets(ans); } }
public void Open() { if (client.Client.Connected) { log.Info("udpserial socket already open"); return; } string dest = Port; dest = OnSettings("UDP_port", dest); if (System.Windows.Forms.DialogResult.Cancel == InputBox.Show("Listern Port", "Enter Local port (ensure remote end is already sending)", ref dest)) { return; } Port = dest; OnSettings("UDP_port", Port, true); ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue { StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen, Text = "Connecting Mavlink UDP" }; frmProgressReporter.DoWork += frmProgressReporter_DoWork; frmProgressReporter.UpdateProgressAndStatus(-1, "Connecting Mavlink UDP"); frmProgressReporter.RunBackgroundOperationAsync(); }
public static void updateCheckMain(ProgressReporterDialogue frmProgressReporter) { var t = Type.GetType("Mono.Runtime"); MONO = (t != null); try { if (dobeta) { CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["BetaUpdateLocationMD5"].ToString()); } else { CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["UpdateLocationMD5"].ToString()); } var process = new Process(); string exePath = Path.GetDirectoryName(Application.ExecutablePath); if (MONO) { process.StartInfo.FileName = "mono"; process.StartInfo.Arguments = " \"" + exePath + Path.DirectorySeparatorChar + "Updater.exe\"" + " \"" + Application.ExecutablePath + "\""; } else { process.StartInfo.FileName = exePath + Path.DirectorySeparatorChar + "Updater.exe"; process.StartInfo.Arguments = Application.ExecutablePath; } try { foreach (string newupdater in Directory.GetFiles(exePath, "Updater.exe*.new")) { File.Copy(newupdater, newupdater.Remove(newupdater.Length - 4), true); File.Delete(newupdater); } } catch (Exception ex) { log.Error("Exception during update", ex); } if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Starting Updater"); } log.Info("Starting new process: " + process.StartInfo.FileName + " with " + process.StartInfo.Arguments); process.Start(); log.Info("Quitting existing process"); frmProgressReporter.BeginInvoke((Action) delegate { Application.Exit(); }); } catch (Exception ex) { log.Error("Update Failed", ex); CustomMessageBox.Show("Update Failed " + ex.Message); } }
public static void DoUpdate() { if (Program.WindowsStoreApp) { CustomMessageBox.Show(Strings.Not_available_when_used_as_a_windows_store_app); return; } IProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue() { Text = "Check for Updates", StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen }; ThemeManager.ApplyThemeTo(frmProgressReporter); frmProgressReporter.DoWork += new DoWorkEventHandler(DoUpdateWorker_DoWork); frmProgressReporter.doWorkArgs.CancelRequestChanged += (sender, args) => { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; }; frmProgressReporter.doWorkArgs.ForceExit = true; frmProgressReporter.UpdateProgressAndStatus(-1, "Checking for Updates"); frmProgressReporter.RunBackgroundOperationAsync(); frmProgressReporter.Dispose(); }
static void GetNewFileZip(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir, string file) { // create dest dir string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } // get dest path string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file; DownloadStream ds = new DownloadStream(baseurl); ZipArchive zip = new ZipArchive(ds); var entry = zip.GetEntry((subdir.TrimStart('\\').Replace('\\', '/') + file)); if (entry == null) { Console.WriteLine("{0} {1}", file, baseurl); return; } entry.ExtractToFile(path + ".new", true); zip.Dispose(); ds.Dispose(); }
public int WizardValidate() { comport = CMB_port.Text; if (comport == "") { CustomMessageBox.Show("Please select a comport", "error"); return(0); } if (!fwdone) { pdr = new ProgressReporterDialogue(); pdr.DoWork += pdr_DoWork; ThemeManager.ApplyThemeTo(pdr); pdr.RunBackgroundOperationAsync(); if (pdr.doWorkArgs.CancelRequested || !string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage)) { return(0); } } if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.BaseStream.Close(); } MainV2.comPort.BaseStream.BaudRate = 115200; MainV2.comPort.BaseStream.PortName = comport; MainV2.comPort.Open(true); if (!MainV2.comPort.BaseStream.IsOpen) { return(0); } if (string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage)) { if (Wizard.config["fwtype"].ToString() == "copter") { // check if its a quad, and show the frame type screen return(1); } else { // skip the frame type screen as its not valid for anythine else return(2); } } return(0); }
internal void Firmware_Load(object sender, EventArgs e) { pdr = new ProgressReporterDialogue(); pdr.DoWork -= pdr_DoWork; pdr.DoWork += pdr_DoWork; ThemeManager.ApplyThemeTo(pdr); pdr.RunBackgroundOperationAsync(); }
private void BUT_MagCalibration_Click(object sender, EventArgs e) { CustomMessageBox.Show("Data will be collected for 60 seconds, Please click ok and move the apm around all axises"); ProgressReporterDialogue prd = new ProgressReporterDialogue(); Utilities.ThemeManager.ApplyThemeTo(prd); prd.DoWork += prd_DoWork; prd.RunBackgroundOperationAsync(); }
void UpdateFWList() { pdr = new ProgressReporterDialogue(); pdr.DoWork -= pdr_DoWork; pdr.DoWork += pdr_DoWork; ThemeManager.ApplyThemeTo(pdr); pdr.RunBackgroundOperationAsync(); }
private void BUT_MagCalibration_Click(object sender, EventArgs e) { CustomMessageBox.Show("Data will be collected for 60 seconds, Please click ok and move the apm around all axises"); ProgressReporterDialogue prd = new ProgressReporterDialogue(); Utilities.ThemeManager.ApplyThemeTo(prd); prd.DoWork += prd_DoWork; prd.RunBackgroundOperationAsync(); }
public static void DoUpdate() { ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue() { Text = "Check for Updates", StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen }; ThemeManager.ApplyThemeTo(frmProgressReporter); frmProgressReporter.DoWork += new ProgressReporterDialogue.DoWorkEventHandler(DoUpdateWorker_DoWork); frmProgressReporter.UpdateProgressAndStatus(-1, "Checking for Updates"); frmProgressReporter.RunBackgroundOperationAsync(); }
private void GetParameters(byte nodeID) { IProgressReporterDialogue prd = new ProgressReporterDialogue(); List <uavcan.uavcan_protocol_param_GetSet_res> paramlist = new List <uavcan.uavcan_protocol_param_GetSet_res>(); prd.doWorkArgs.ForceExit = true; prd.doWorkArgs.CancelRequestChanged += (sender2, args) => { prd.doWorkArgs.CancelAcknowledged = true; }; prd.DoWork += dialogue => { paramlist = can.GetParameters(nodeID); }; prd.UpdateProgressAndStatus(-1, Strings.GettingParams); prd.RunBackgroundOperationAsync(); if (!prd.doWorkArgs.CancelRequested) { new UAVCANParams(can, nodeID, paramlist).ShowUserControl(); } }
private void BUT_paramgen_Click(object sender, System.EventArgs e) { ProgressReporterDialogue prd = new ProgressReporterDialogue(); prd.DoWork += dialogue => { ParameterMetaDataParser.GetParameterInformation( ConfigurationManager.AppSettings["ParameterLocationsBleeding"] + ";" + ConfigurationManager.AppSettings["ParameterLocations"]); ParameterMetaDataRepositoryAPM.Reload(); }; prd.doWorkArgs.ForceExit = true; prd.RunBackgroundOperationAsync(); }
private void BUT_MagCalibration_Click(object sender, EventArgs e) { MainV2.comPort.MAV.cs.ratesensors = 2; MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA3, MainV2.comPort.MAV.cs.ratesensors); MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.comPort.MAV.cs.ratesensors); MainV2.comPort.setParam("MAG_ENABLE", 1); CustomMessageBox.Show("Data will be collected for 60 seconds, Please click ok and move the apm around all axises"); ProgressReporterDialogue prd = new ProgressReporterDialogue(); Utilities.ThemeManager.ApplyThemeTo(prd); prd.DoWork += prd_DoWork; prd.RunBackgroundOperationAsync(); }
void doUI(string inputfn, string outputfn, bool showui = true) { this.inputfn = inputfn; this.outputfn = outputfn; prd = new ProgressReporterDialogue(); prd.DoWork += prd_DoWork; prd.UpdateProgressAndStatus(-1, Strings.Converting_bin_to_log); this.convertstatus += BinaryLog_convertstatus; ThemeManager.ApplyThemeTo(prd); prd.RunBackgroundOperationAsync(); prd.Dispose(); }
public void Open() { if (client.Client.Connected) { log.Info("udpserial socket already open"); return; } ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue { StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen, Text = "Connecting Mavlink UDP" }; frmProgressReporter.DoWork += frmProgressReporter_DoWork; frmProgressReporter.UpdateProgressAndStatus(-1, "Connecting Mavlink UDP"); frmProgressReporter.RunBackgroundOperationAsync(); }
public static void DownloadGStreamer() { ProgressReporterDialogue prd = new ProgressReporterDialogue(); ThemeManager.ApplyThemeTo(prd); prd.DoWork += sender => { GStreamer.DownloadGStreamer(((i, s) => { prd.UpdateProgressAndStatus(i, s); if (prd.doWorkArgs.CancelRequested) { throw new Exception("User Request"); } })); }; prd.RunBackgroundOperationAsync(); GStreamer.gstlaunch = GStreamer.LookForGstreamer(); }
private void BUT_paramgen_Click(object sender, System.EventArgs e) { ProgressReporterDialogue prd = new ProgressReporterDialogue(); prd.DoWork += dialogue => { prd.UpdateProgressAndStatus(-1, "Downloading updated data"); ParameterMetaDataParser.GetParameterInformation( ConfigurationManager.AppSettings["ParameterLocationsBleeding"] + ";" + ConfigurationManager.AppSettings["ParameterLocations"] + ";" + "https://raw.githubusercontent.com/BeagleSystems/ardupilot/master/ArduPlane/Parameters.cpp;"); ParameterMetaDataRepositoryAPM.Reload(); }; prd.doWorkArgs.CancelRequestChanged += (sender2, args) => { prd.doWorkArgs.CancelAcknowledged = true; }; prd.doWorkArgs.ForceExit = true; prd.RunBackgroundOperationAsync(); }
private void BUT_paramgen_Click(object sender, System.EventArgs e) { ProgressReporterDialogue prd = new ProgressReporterDialogue(); prd.DoWork += dialogue => { prd.UpdateProgressAndStatus(-1, "Downloading updated data"); ParameterMetaDataParser.GetParameterInformation( ConfigurationManager.AppSettings["ParameterLocationsBleeding"] + ";" + ConfigurationManager.AppSettings["ParameterLocations"] + ";" + "https://raw.githubusercontent.com/ArduPilot/ardupilot/Copter-3.6/ArduCopter/Parameters.cpp;" + "https://raw.githubusercontent.com/ArduPilot/ardupilot/Copter-3.5/ArduCopter/Parameters.cpp;" + "https://raw.githubusercontent.com/ArduPilot/ardupilot/plane3.9/ArduCopter/Parameters.cpp;" + "https://raw.githubusercontent.com/ArduPilot/ardupilot/plane3.8/ArduCopter/Parameters.cpp;"); ParameterMetaDataRepositoryAPM.Reload(); }; prd.doWorkArgs.ForceExit = true; prd.RunBackgroundOperationAsync(); }
static void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url) { var baseurl = ConfigurationManager.AppSettings["UpdateLocation"]; 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")) continue; if (!MD5File(file, hash)) { log.Info("Newer File " + file); if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file); string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar; GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\','/'), subdir, Path.GetFileName(file)); } else { log.Info("Same File " + file); if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file); } } } }
public static void updateCheckMain(ProgressReporterDialogue frmProgressReporter) { try { CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["UpdateLocationMD5"].ToString()); var process = new Process(); string exePath = Path.GetDirectoryName(Application.ExecutablePath); if (MONO) { process.StartInfo.FileName = "mono"; process.StartInfo.Arguments = " \"" + exePath + Path.DirectorySeparatorChar + "Updater.exe\"" + " \"" + Application.ExecutablePath + "\""; } else { process.StartInfo.FileName = exePath + Path.DirectorySeparatorChar + "Updater.exe"; process.StartInfo.Arguments = Application.ExecutablePath; } try { foreach (string newupdater in Directory.GetFiles(exePath, "Updater.exe*.new")) { File.Copy(newupdater, newupdater.Remove(newupdater.Length - 4), true); File.Delete(newupdater); } } catch (Exception ex) { log.Error("Exception during update", ex); } if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus(-1, "Starting Updater"); log.Info("Starting new process: " + process.StartInfo.FileName + " with " + process.StartInfo.Arguments); process.Start(); log.Info("Quitting existing process"); try { // clean close MainV2.instance.BeginInvoke((MethodInvoker)delegate() { MainV2.instance.Close(); }); } catch (Exception ex) { log.Error(ex); Application.Exit(); } } catch (Exception ex) { log.Error("Update Failed", ex); CustomMessageBox.Show("Update Failed " + ex.Message); } }
public static void DoUpdate() { ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue() { Text = "Check for Updates", StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen }; ThemeManager.ApplyThemeTo(frmProgressReporter); frmProgressReporter.DoWork += new Controls.ProgressReporterDialogue.DoWorkEventHandler(DoUpdateWorker_DoWork); frmProgressReporter.UpdateProgressAndStatus(-1, "Checking for Updates"); frmProgressReporter.RunBackgroundOperationAsync(); }
private static bool updateCheck(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir) { bool update = false; List<string> files = new List<string>(); // Create a request using a URL that can receive a post. log.Info(baseurl); 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(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Regex regex = new Regex("href=\"([^\"]+)\"", RegexOptions.IgnoreCase); Uri baseuri = new Uri(baseurl, UriKind.Absolute); if (regex.IsMatch(responseFromServer)) { MatchCollection matchs = regex.Matches(responseFromServer); for (int i = 0; i < matchs.Count; i++) { if (matchs[i].Groups[1].Value.ToString().Contains("..")) continue; if (matchs[i].Groups[1].Value.ToString().Contains("http")) continue; if (matchs[i].Groups[1].Value.ToString().StartsWith("?")) continue; if (matchs[i].Groups[1].Value.ToString().ToLower().Contains(".etag")) continue; // { string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()); Uri newuri = new Uri(baseuri, url); files.Add(baseuri.MakeRelativeUri(newuri).ToString()); } // dirs if (matchs[i].Groups[1].Value.ToString().Contains("tree/master/")) { string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()) + "/"; Uri newuri = new Uri(baseuri, url); files.Add(baseuri.MakeRelativeUri(newuri).ToString()); } // files if (matchs[i].Groups[1].Value.ToString().Contains("blob/master/")) { string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()); Uri newuri = new Uri(baseuri, url); files.Add(System.Web.HttpUtility.UrlDecode(newuri.Segments[newuri.Segments.Length - 1])); } } } //Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); foreach (string file in files) { if (frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("Cancel"); } if (file.Equals("/") || file.Equals("") || file.StartsWith("../")) { continue; } if (file.EndsWith("/")) { update = updateCheck(frmProgressReporter, baseurl + file, subdir.Replace('/', Path.DirectorySeparatorChar) + file) && update; continue; } if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file); string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file; // baseurl = baseurl.Replace("//github.com", "//raw.github.com"); // baseurl = baseurl.Replace("/tree/", "/"); Exception fail = null; int attempt = 0; while (attempt < 2) { try { // Create a request using a URL that can receive a post. request = WebRequest.Create(baseurl + file); log.Info(baseurl + file + " "); // Set the Method property of the request to POST. request.Method = "GET"; ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Get the response. 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. bool updateThisFile = false; if (File.Exists(path)) { FileInfo fi = new FileInfo(path); //log.Info(response.Headers[HttpResponseHeader.ETag]); string CurrentEtag = ""; if (File.Exists(path + ".etag")) { using (Stream fs = File.OpenRead(path + ".etag")) { using (StreamReader sr = new StreamReader(fs)) { CurrentEtag = sr.ReadLine(); sr.Close(); } fs.Close(); } } log.Debug("New file Check: " + fi.Length + " vs " + response.ContentLength + " " + response.Headers[HttpResponseHeader.ETag] + " vs " + CurrentEtag); if (fi.Length != response.ContentLength || response.Headers[HttpResponseHeader.ETag] != CurrentEtag) { using (StreamWriter sw = new StreamWriter(path + ".etag.new")) { sw.WriteLine(response.Headers[HttpResponseHeader.ETag]); sw.Close(); } updateThisFile = true; log.Info("NEW FILE " + file); } } else { updateThisFile = true; log.Info("NEW FILE " + file); using (StreamWriter sw = new StreamWriter(path + ".etag.new")) { sw.WriteLine(response.Headers[HttpResponseHeader.ETag]); sw.Close(); } // get it } if (updateThisFile) { if (!update) { //DialogResult dr = MessageBox.Show("Update Found\n\nDo you wish to update now?", "Update Now", MessageBoxButtons.YesNo); //if (dr == DialogResult.Yes) { update = true; } //else { // return; } } if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file); // from head long bytes = response.ContentLength; long contlen = bytes; byte[] buf1 = new byte[4096]; using (FileStream fs = new FileStream(path + ".new", FileMode.Create)) { DateTime dt = DateTime.Now; //dataStream.ReadTimeout = 30000; while (dataStream.CanRead) { try { if (dt.Second != DateTime.Now.Second) { if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus((int)(((double)(contlen - bytes) / (double)contlen) * 100), "Getting " + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100).ToString("0.0") + "%"); //+ Math.Abs(bytes) + " bytes"); dt = DateTime.Now; } } catch { } log.Debug(file + " " + bytes); int len = dataStream.Read(buf1, 0, buf1.Length); if (len == 0) break; bytes -= len; fs.Write(buf1, 0, len); } fs.Close(); } } reader.Close(); //dataStream.Close(); response.Close(); } catch (Exception ex) { fail = ex; attempt++; update = false; continue; } // break if we have no exception break; } if (attempt == 2) { throw fail; } } //P.StartInfo.CreateNoWindow = true; //P.StartInfo.RedirectStandardOutput = true; return update; }
private void FirmwareUpdate(byte nodeID, bool beta = false) { ProgressReporterDialogue prd = new ProgressReporterDialogue(); uavcan.FileSendProgressArgs filesend = (id, file, percent) => { prd.UpdateProgressAndStatus((int)percent, id + " " + file); }; can.FileSendProgress += filesend; var devicename = can.GetNodeName(nodeID); var hwversion = double.Parse( can.NodeInfo[nodeID].hardware_version.major + "." + can.NodeInfo[nodeID].hardware_version.minor, CultureInfo.InvariantCulture); if (CustomMessageBox.Show("Do you want to search the internet for an update?", "Update", CustomMessageBox.MessageBoxButtons.YesNo) == CustomMessageBox.DialogResult.Yes) { var url = can.LookForUpdate(devicename, hwversion, beta); if (url != string.Empty) { try { var cancel = new CancellationTokenSource(); prd.DoWork += dialogue => { prd.UpdateProgressAndStatus(5, "Download FW"); var tempfile = Path.GetTempFileName(); Download.getFilefromNet(url, tempfile); uavcan.FileSendCompleteArgs file = (p, s) => { prd.UpdateProgressAndStatus(100, "File send complete"); }; uavcan.FileSendProgressArgs fileprog = (n, f, p) => { prd.UpdateProgressAndStatus((int)p, f); }; can.FileSendComplete += file; can.FileSendProgress += fileprog; try { can.Update(nodeID, devicename, hwversion, tempfile, cancel.Token); } catch (Exception) { throw; } finally { can.FileSendComplete -= file; can.FileSendProgress -= fileprog; } return; }; prd.btnCancel.Click += (sender, args) => { prd.doWorkArgs.CancelAcknowledged = true; cancel.Cancel(); }; prd.RunBackgroundOperationAsync(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } } else { CustomMessageBox.Show(Strings.UpdateNotFound, Strings.UpdateNotFound); } } else { FileDialog fd = new OpenFileDialog(); fd.RestoreDirectory = true; fd.Filter = "*.bin|*.bin"; var dia = fd.ShowDialog(); if (fd.CheckFileExists && dia == DialogResult.OK) { uavcan.FileSendCompleteArgs file = (p, s) => { prd.UpdateProgressAndStatus(100, "File send complete"); }; uavcan.FileSendProgressArgs fileprog = (n, f, p) => { prd.UpdateProgressAndStatus((int)p, f); }; can.FileSendComplete += file; can.FileSendProgress += fileprog; try { var cancel = new CancellationTokenSource(); prd.DoWork += dialogue => { can.Update(nodeID, devicename, 0, fd.FileName, cancel.Token); return; }; prd.btnCancel.Click += (sender, args) => { prd.doWorkArgs.CancelAcknowledged = true; cancel.Cancel(); }; prd.RunBackgroundOperationAsync(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } finally { can.FileSendComplete -= file; can.FileSendProgress -= fileprog; } } } can.FileSendProgress -= filesend; prd.Dispose(); }
public void startslcan(byte canport) { but_slcanmode1.Enabled = false; but_slcanmode2.Enabled = false; try { if (!MainV2.comPort.BaseStream.IsOpen) { if (CustomMessageBox.Show( "You are not currently connected via mavlink. Please make sure the device is already in slcan mode or this is the slcan serialport.", "SLCAN", CustomMessageBox.MessageBoxButtons.OKCancel) != CustomMessageBox.DialogResult.OK) { return; } } if (MainV2.comPort.BaseStream.IsOpen) { var cport = MainV2.comPort.MAV.param["CAN_SLCAN_CPORT"].Value; MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "CAN_SLCAN_CPORT", canport, true); if (cport == 0) { CustomMessageBox.Show("Reboot required" + " after setting CPORT. Please reboot!", Strings.ERROR); return; } MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "CAN_SLCAN_TIMOUT", 2, true); MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "CAN_P" + canport + "_DRIVER", 1); //MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "CAN_SLCAN_SERNUM", 0, true); // usb // blind send var paramname = "CAN_SLCAN_SERNUM"; var req = new MAVLink.mavlink_param_set_t { target_system = (byte)MainV2.comPort.sysidcurrent, target_component = (byte)MainV2.comPort.compidcurrent, param_type = (byte)MainV2.comPort .MAVlist[(byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent] .param_types[paramname], param_id = paramname.MakeBytesSize(16) }; MainV2.comPort.sendPacket(req, (byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent); MainV2.comPort.sendPacket(req, (byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent); } } catch { } { // grab the connected port var port = MainV2.comPort.BaseStream; // place an invalid port in its place if (port != null) { MainV2.comPort.BaseStream = new Comms.SerialPort() { PortName = port.PortName, BaudRate = port.BaudRate } } ; //check if we started from within mavlink - if not get settings from menu and create port if (port == null || !port.IsOpen) { port = new Comms.SerialPort() { PortName = MainV2._connectionControl.CMB_serialport.Text, BaudRate = int.Parse(MainV2._connectionControl.CMB_baudrate.Text) }; } if (can == null) { can = new uavcan(); } can.SourceNode = 127; can.NodeAdded += (id, msg) => { this.BeginInvoke((Action) delegate { allnodes.Add(new UAVCANModel() { ID = id, Name = "?", Health = msg.health.ToString(), Mode = msg.mode.ToString(), Uptime = TimeSpan.FromSeconds(msg.uptime_sec), VSC = msg.vendor_specific_status_code }); }); }; if (!port.IsOpen) { try { port.Open(); } catch (Exception e) { CustomMessageBox.Show(Strings.CheckPortSettingsOr); return; } } if (chk_log.Checked) { can.LogFile = Settings.Instance.LogDir + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".can"; } var prd = new ProgressReporterDialogue(); prd.UpdateProgressAndStatus(-1, "Trying to connect"); prd.DoWork += sender => can.StartSLCAN(port.BaseStream); prd.btnCancel.Click += (sender, args) => { prd.doWorkArgs.CancelAcknowledged = true; port.Close(); }; prd.RunBackgroundOperationAsync(); if (prd.doWorkArgs.CancelRequested || prd.doWorkArgs.ErrorMessage != null) { return; } can.SetupFileServer(); can.SetupDynamicNodeAllocator(); can.MessageReceived += (frame, msg, transferID) => { if (msg.GetType() == typeof(UAVCAN.uavcan.uavcan_protocol_NodeStatus)) { var ns = msg as UAVCAN.uavcan.uavcan_protocol_NodeStatus; var nodes = allnodes.Where((a) => a.ID == frame.SourceNode); if (nodes.Count() > 0 && nodes.First().Name == "?") { var statetracking = new UAVCAN.uavcan.statetracking(); // get node info UAVCAN.uavcan.uavcan_protocol_GetNodeInfo_req gnireq = new UAVCAN.uavcan.uavcan_protocol_GetNodeInfo_req() { }; gnireq.encode(UAVCAN.uavcan.uavcan_transmit_chunk_handler, statetracking); var slcan = can.PackageMessage(frame.SourceNode, 30, 0, gnireq); can.WriteToStream(slcan); } foreach (var item in nodes) { switch (ns.health) { case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_HEALTH_OK: item.Health = "OK"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_HEALTH_WARNING: item.Health = "WARNING"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_HEALTH_ERROR: item.Health = "ERROR"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_HEALTH_CRITICAL: item.Health = "CRITICAL"; break; } switch (ns.mode) { case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_MODE_OPERATIONAL: item.Mode = "OPERATIONAL"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_MODE_INITIALIZATION: item.Mode = "INITIALIZATION"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_MODE_MAINTENANCE: item.Mode = "MAINTENANCE"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_MODE_SOFTWARE_UPDATE: item.Mode = "SOFTWARE_UPDATE"; break; case (byte)UAVCAN.uavcan.UAVCAN_PROTOCOL_NODESTATUS_MODE_OFFLINE: item.Mode = "OFFLINE"; break; } item.Uptime = TimeSpan.FromSeconds(ns.uptime_sec); } _updatePending = true; this.BeginInvoke((Action) delegate { if (_updatePending) { _updatePending = false; uAVCANModelBindingSource.ResetBindings(false); } }); } else if (msg.GetType() == typeof(UAVCAN.uavcan.uavcan_protocol_GetNodeInfo_res)) { var gnires = msg as UAVCAN.uavcan.uavcan_protocol_GetNodeInfo_res; var nodes = allnodes.Where((a) => a.ID == frame.SourceNode); foreach (var item in nodes) { item.Name = ASCIIEncoding.ASCII.GetString(gnires.name, 0, gnires.name_len); item.HardwareVersion = gnires.hardware_version.major + "." + gnires.hardware_version.minor; item.SoftwareVersion = gnires.software_version.major + "." + gnires.software_version.minor + "." + gnires.software_version.vcs_commit.ToString("X"); item.SoftwareCRC = gnires.software_version.image_crc; item.HardwareUID = gnires.hardware_version.unique_id.Select(a => a.ToString("X2")).Aggregate((a, b) => { return(a + " " + b); }); item.RawMsg = gnires; item.VSC = gnires.status.vendor_specific_status_code; } _updatePending = true; this.BeginInvoke((Action) delegate { if (_updatePending) { _updatePending = false; uAVCANModelBindingSource.ResetBindings(false); } }); } else if (msg.GetType() == typeof(UAVCAN.uavcan.uavcan_protocol_debug_LogMessage)) { var debug = msg as UAVCAN.uavcan.uavcan_protocol_debug_LogMessage; this.BeginInvoke((Action) delegate() { DGDebug.Rows.Insert(0, new object[] { frame.SourceNode, debug.level.value, ASCIIEncoding.ASCII.GetString(debug.source, 0, debug.source_len), ASCIIEncoding.ASCII.GetString(debug.text, 0, debug.text_len) }); if (DGDebug.Rows.Count > 100) { DGDebug.Rows.RemoveAt(DGDebug.Rows.Count - 1); } }); } }; } } UAVCAN.uavcan can = new UAVCAN.uavcan();
static void GetNewFile(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir, string file) { // create dest dir string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } // get dest path string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file; Exception fail = null; int attempt = 0; // attempt to get file while (attempt < 2) { // check if user canceled if (frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("Cancel"); } try { string url = baseurl + file + "?" + new Random().Next(); // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create(url); log.Info("GetNewFile " + url); // Set the Method property of the request to GET. request.Method = "GET"; // Allow compressed content ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // tell server we allow compress content request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Get the response. using (WebResponse response = request.GetResponse()) { // Display the status. log.Info(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // update status if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Getting + file); } // from head long bytes = response.ContentLength; long contlen = bytes; byte[] buf1 = new byte[4096]; // if the file doesnt exist. just save it inplace string fn = path + ".new"; using (FileStream fs = new FileStream(fn, FileMode.Create)) { DateTime dt = DateTime.Now; while (dataStream.CanRead) { try { if (dt.Second != DateTime.Now.Second) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus( (int)(((double)(contlen - bytes) / (double)contlen) * 100), Strings.Getting + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100).ToString("0.0") + "%"); //+ Math.Abs(bytes) + " bytes"); } dt = DateTime.Now; } } catch { } log.Debug(file + " " + bytes); int len = dataStream.Read(buf1, 0, buf1.Length); if (len == 0) { break; } bytes -= len; fs.Write(buf1, 0, len); } } } } catch (Exception ex) { fail = ex; attempt++; continue; } // break if we have no exception break; } if (attempt == 2) { throw fail; } }
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); } } } } }
public void Open() { if (client.Client.Connected) { log.Info("udpserial socket already open"); return; } ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue { StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen, Text = "Connecting Mavlink UDP" }; frmProgressReporter.DoWork += frmProgressReporter_DoWork; frmProgressReporter.UpdateProgressAndStatus(-1, "Connecting Mavlink UDP"); frmProgressReporter.RunBackgroundOperationAsync(); }
static void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url) { var baseurl = ConfigurationManager.AppSettings["UpdateLocation"]; 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")) { continue; } if (!MD5File(file, hash)) { log.Info("Newer File " + file); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file); } string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar; GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir, Path.GetFileName(file)); } else { log.Info("Same File " + file); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file); } } } } }
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); } } } } }
private async void myDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { // Ignore clicks that are not on button cells. if (e.RowIndex < 0 || e.ColumnIndex != myDataGridView1.Columns["updateDataGridViewTextBoxColumn"].Index && e.ColumnIndex != myDataGridView1.Columns["Parameter"].Index) { return; } byte nodeID = (byte)myDataGridView1[iDDataGridViewTextBoxColumn.Index, e.RowIndex].Value; if (e.ColumnIndex == myDataGridView1.Columns["Parameter"].Index) { var paramlist = can.GetParameters(nodeID); new UAVCANParams(can, nodeID, paramlist).ShowUserControl(); } else if (e.ColumnIndex == myDataGridView1.Columns["updateDataGridViewTextBoxColumn"].Index) { ProgressReporterDialogue prd = new ProgressReporterDialogue(); uavcan.FileSendProgressArgs filesend = (id, file, percent) => { prd.UpdateProgressAndStatus((int)percent, id + " " + file); }; can.FileSendProgress += filesend; if (CustomMessageBox.Show("Do you want to search the internet for an update?", "Update", CustomMessageBox.MessageBoxButtons.YesNo) == CustomMessageBox.DialogResult.Yes) { var devicename = myDataGridView1[nameDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(); var hwversion = double.Parse(myDataGridView1[hardwareVersionDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(), CultureInfo.InvariantCulture); var url = can.LookForUpdate(devicename, hwversion); if (url != string.Empty) { try { prd.DoWork += dialogue => { var tempfile = Path.GetTempFileName(); Download.getFilefromNet(url, tempfile); can.Update(nodeID, devicename, hwversion, tempfile); return; }; prd.RunBackgroundOperationAsync(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } } else { CustomMessageBox.Show(Strings.UpdateNotFound, Strings.UpdateNotFound); } } else { FileDialog fd = new OpenFileDialog(); fd.RestoreDirectory = true; fd.Filter = "*-crc.bin|*-crc.bin"; var dia = fd.ShowDialog(); if (fd.CheckFileExists && dia == DialogResult.OK) { try { prd.DoWork += dialogue => { can.Update(nodeID, myDataGridView1[nameDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(), 0, fd.FileName); return; }; prd.RunBackgroundOperationAsync(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } } } can.FileSendProgress -= filesend; prd.Dispose(); } }
void BinaryLog_convertstatus(ProgressReporterDialogue prd, float progress) { prd.UpdateProgressAndStatus((int)progress, Strings.Converting_bin_to_log); }
private async void myDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { // Ignore clicks that are not on button cells. if (e.RowIndex < 0) { return; } try { byte nodeID = (byte)myDataGridView1[iDDataGridViewTextBoxColumn.Index, e.RowIndex].Value; if (e.ColumnIndex == myDataGridView1.Columns["Parameter"].Index) { IProgressReporterDialogue prd = new ProgressReporterDialogue(); List <uavcan.uavcan_protocol_param_GetSet_res> paramlist = new List <uavcan.uavcan_protocol_param_GetSet_res>(); prd.doWorkArgs.ForceExit = true; prd.doWorkArgs.CancelRequestChanged += (sender2, args) => { prd.doWorkArgs.CancelAcknowledged = true; }; prd.DoWork += dialogue => { paramlist = can.GetParameters(nodeID); }; prd.UpdateProgressAndStatus(-1, Strings.GettingParams); prd.RunBackgroundOperationAsync(); if (!prd.doWorkArgs.CancelRequested) { new UAVCANParams(can, nodeID, paramlist).ShowUserControl(); } } else if (e.ColumnIndex == myDataGridView1.Columns["Restart"].Index) { can.RestartNode(nodeID); } else if (e.ColumnIndex == myDataGridView1.Columns["updateDataGridViewTextBoxColumn"].Index) { ProgressReporterDialogue prd = new ProgressReporterDialogue(); uavcan.FileSendProgressArgs filesend = (id, file, percent) => { prd.UpdateProgressAndStatus((int)percent, id + " " + file); }; can.FileSendProgress += filesend; if (CustomMessageBox.Show("Do you want to search the internet for an update?", "Update", CustomMessageBox.MessageBoxButtons.YesNo) == CustomMessageBox.DialogResult.Yes) { var devicename = myDataGridView1[nameDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(); var hwversion = double.Parse( myDataGridView1[hardwareVersionDataGridViewTextBoxColumn.Index, e.RowIndex].Value .ToString(), CultureInfo.InvariantCulture); var usebeta = false; if (CustomMessageBox.Show("Do you want to search for a beta firmware? (not recommended)", "Update", CustomMessageBox.MessageBoxButtons.YesNo) == CustomMessageBox.DialogResult.Yes) { usebeta = true; } var url = can.LookForUpdate(devicename, hwversion, usebeta); if (url != string.Empty) { try { prd.DoWork += dialogue => { var tempfile = Path.GetTempFileName(); Download.getFilefromNet(url, tempfile); try { can.Update(nodeID, devicename, hwversion, tempfile); } catch (Exception ex) { throw; } return; }; prd.RunBackgroundOperationAsync(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } } else { CustomMessageBox.Show(Strings.UpdateNotFound, Strings.UpdateNotFound); } } else { FileDialog fd = new OpenFileDialog(); fd.RestoreDirectory = true; fd.Filter = "*.bin|*.bin"; var dia = fd.ShowDialog(); if (fd.CheckFileExists && dia == DialogResult.OK) { try { prd.DoWork += dialogue => { can.Update(nodeID, myDataGridView1[nameDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString(), 0, fd.FileName); return; }; prd.RunBackgroundOperationAsync(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } } } can.FileSendProgress -= filesend; prd.Dispose(); } } catch { } }
private static bool updateCheck(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir) { bool update = false; List <string> files = new List <string>(); // Create a request using a URL that can receive a post. log.Info(baseurl); 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 (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()) { // Open the stream using a StreamReader for easy access. using (StreamReader reader = new StreamReader(dataStream)) { // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Regex regex = new Regex("href=\"([^\"]+)\"", RegexOptions.IgnoreCase); Uri baseuri = new Uri(baseurl, UriKind.Absolute); if (regex.IsMatch(responseFromServer)) { MatchCollection matchs = regex.Matches(responseFromServer); for (int i = 0; i < matchs.Count; i++) { if (matchs[i].Groups[1].Value.ToString().Contains("..")) { continue; } if (matchs[i].Groups[1].Value.ToString().Contains("http")) { continue; } if (matchs[i].Groups[1].Value.ToString().StartsWith("?")) { continue; } if (matchs[i].Groups[1].Value.ToString().ToLower().Contains(".etag")) { continue; } // { string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()); Uri newuri = new Uri(baseuri, url); files.Add(baseuri.MakeRelativeUri(newuri).ToString()); } // dirs if (matchs[i].Groups[1].Value.ToString().Contains("tree/master/")) { string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()) + "/"; Uri newuri = new Uri(baseuri, url); files.Add(baseuri.MakeRelativeUri(newuri).ToString()); } // files if (matchs[i].Groups[1].Value.ToString().Contains("blob/master/")) { string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()); Uri newuri = new Uri(baseuri, url); files.Add( System.Web.HttpUtility.UrlDecode(newuri.Segments[newuri.Segments.Length - 1])); } } } //Console.WriteLine(responseFromServer); // Clean up the streams. } } } string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } foreach (string file in files) { if (frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("Cancel"); } if (file.Equals("/") || file.Equals("") || file.StartsWith("../")) { continue; } if (file.EndsWith("/")) { update = updateCheck(frmProgressReporter, baseurl + file, subdir.Replace('/', Path.DirectorySeparatorChar) + file) && update; continue; } if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file); } string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file; // baseurl = baseurl.Replace("//github.com", "//raw.github.com"); // baseurl = baseurl.Replace("/tree/", "/"); Exception fail = null; int attempt = 0; while (attempt < 2) { try { // Create a request using a URL that can receive a post. request = WebRequest.Create(baseurl + file); log.Info(baseurl + file + " "); // Set the Method property of the request to POST. request.Method = "GET"; ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Get the response. 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()) { // Open the stream using a StreamReader for easy access. bool updateThisFile = false; if (File.Exists(path)) { FileInfo fi = new FileInfo(path); //log.Info(response.Headers[HttpResponseHeader.ETag]); string CurrentEtag = ""; if (File.Exists(path + ".etag")) { using (Stream fs = File.OpenRead(path + ".etag")) { using (StreamReader sr = new StreamReader(fs)) { CurrentEtag = sr.ReadLine(); } } } log.Debug("New file Check: " + fi.Length + " vs " + response.ContentLength + " " + response.Headers[HttpResponseHeader.ETag] + " vs " + CurrentEtag); if (fi.Length != response.ContentLength || response.Headers[HttpResponseHeader.ETag] != CurrentEtag) { using (StreamWriter sw = new StreamWriter(path + ".etag.new")) { sw.WriteLine(response.Headers[HttpResponseHeader.ETag]); } updateThisFile = true; log.Info("NEW FILE " + file); } } else { updateThisFile = true; log.Info("NEW FILE " + file); using (StreamWriter sw = new StreamWriter(path + ".etag.new")) { sw.WriteLine(response.Headers[HttpResponseHeader.ETag]); } // get it } if (updateThisFile) { if (!update) { //DialogResult dr = MessageBox.Show("Update Found\n\nDo you wish to update now?", "Update Now", MessageBoxButtons.YesNo); //if (dr == DialogResult.Yes) { update = true; } //else { // return; } } if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file); } // from head long bytes = response.ContentLength; long contlen = bytes; byte[] buf1 = new byte[4096]; using (FileStream fs = new FileStream(path + ".new", FileMode.Create)) { DateTime dt = DateTime.Now; //dataStream.ReadTimeout = 30000; while (dataStream.CanRead) { try { if (dt.Second != DateTime.Now.Second) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus( (int)(((double)(contlen - bytes) / (double)contlen) * 100), "Getting " + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100).ToString ("0.0") + "%"); //+ Math.Abs(bytes) + " bytes"); } dt = DateTime.Now; } } catch { } log.Debug(file + " " + bytes); int len = dataStream.Read(buf1, 0, buf1.Length); if (len == 0) { break; } bytes -= len; fs.Write(buf1, 0, len); } } } } } } catch (Exception ex) { fail = ex; attempt++; update = false; continue; } // break if we have no exception break; } if (attempt == 2) { throw fail; } } //P.StartInfo.CreateNoWindow = true; //P.StartInfo.RedirectStandardOutput = true; return(update); }
public int WizardValidate() { comport = CMB_port.Text; if (comport == "") { CustomMessageBox.Show(Strings.SelectComport, Strings.ERROR); return(0); } if (!fwdone) { pdr = new ProgressReporterDialogue(); pdr.DoWork += pdr_DoWork; ThemeManager.ApplyThemeTo(pdr); pdr.RunBackgroundOperationAsync(); if (pdr.doWorkArgs.CancelRequested || !string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage)) { return(0); } } if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.BaseStream.Close(); } // setup for over usb MainV2.comPort.BaseStream.BaudRate = 115200; MainV2.comPort.BaseStream.PortName = comport; MainV2.comPort.Open(true); // try again if (!MainV2.comPort.BaseStream.IsOpen) { CustomMessageBox.Show("Error connecting. Please unplug, plug back in, wait 10 seconds, and click OK", "Try Again"); MainV2.comPort.Open(true); } if (!MainV2.comPort.BaseStream.IsOpen) { return(0); } if (string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage)) { if (Wizard.config["fwtype"].ToString() == "copter") { // check if its a quad, and show the frame type screen return(1); } if (Wizard.config["fwtype"].ToString() == "rover") { // check if its a rover, and show the compass cal screen - skip accel return(3); } else { // skip the frame type screen as its not valid for anythine else return(2); } } return(0); }
static void GetNewFile(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir, string file) { // create dest dir string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // get dest path string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file; Exception fail = null; int attempt = 0; // attempt to get file while (attempt < 2) { // check if user canceled if (frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("Cancel"); } try { // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create(baseurl + file); log.Info("get "+baseurl + file + " "); // Set the Method property of the request to GET. request.Method = "GET"; // Allow compressed content ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // tell server we allow compress content request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Get the response. WebResponse response = request.GetResponse(); // Display the status. log.Info(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // update status if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file); // from head long bytes = response.ContentLength; long contlen = bytes; byte[] buf1 = new byte[4096]; using (FileStream fs = new FileStream(path + ".new", FileMode.Create)) { DateTime dt = DateTime.Now; while (dataStream.CanRead) { try { if (dt.Second != DateTime.Now.Second) { if (frmProgressReporter != null) frmProgressReporter.UpdateProgressAndStatus((int)(((double)(contlen - bytes) / (double)contlen) * 100), "Getting " + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100).ToString("0.0") + "%"); //+ Math.Abs(bytes) + " bytes"); dt = DateTime.Now; } } catch { } log.Debug(file + " " + bytes); int len = dataStream.Read(buf1, 0, buf1.Length); if (len == 0) break; bytes -= len; fs.Write(buf1, 0, len); } fs.Close(); } response.Close(); } catch (Exception ex) { fail = ex; attempt++; continue; } // break if we have no exception break; } if (attempt == 2) { throw fail; } }