//Load custom firmware (old CTRL+C shortcut) private void Custom_firmware_label_Click(object sender, EventArgs e) { var fd = new OpenFileDialog { Filter = "Firmware (*.hex;*.px4)|*.hex;*.px4" }; if (Directory.Exists(custom_fw_dir)) { fd.InitialDirectory = custom_fw_dir; } fd.ShowDialog(); if (File.Exists(fd.FileName)) { custom_fw_dir = Path.GetDirectoryName(fd.FileName); fw.Progress -= fw_Progress; fw.Progress += fw_Progress1; BoardDetect.boards boardtype = BoardDetect.boards.none; try { boardtype = BoardDetect.DetectBoard(MainV2.comPortName); } catch { CustomMessageBox.Show("Can not connect to com port and detect board type", "Error"); return; } fw.UploadFlash(MainV2.comPortName, fd.FileName, boardtype); } }
/// <summary> /// upload to vrbrain standalone /// </summary> /// <param name="filename"></param> public bool UploadVRBRAIN(string filename) { px4uploader.Uploader up; updateProgress(0, "Reading Hex File"); px4uploader.Firmware fw; try { fw = px4uploader.Firmware.ProcessFirmware(filename); } catch (Exception ex) { CustomMessageBox.Show(Strings.ErrorFirmwareFile + "\n\n" + ex.ToString(), Strings.ERROR); return(false); } try { // check if we are seeing heartbeats MainV2.comPort.BaseStream.Open(); MainV2.comPort.giveComport = true; BoardDetect.boards board = BoardDetect.DetectBoard(MainV2.comPortName); if (MainV2.comPort.getHeartBeat().Length > 0) { MainV2.comPort.doReboot(true); MainV2.comPort.Close(); //specific action for VRBRAIN4 board that needs to be manually disconnected before uploading if (board == BoardDetect.boards.vrbrainv40) { CustomMessageBox.Show("VRBRAIN 4 detected. Please unplug the board, and then press OK and plug back in.\n"); } } else { MainV2.comPort.BaseStream.Close(); CustomMessageBox.Show("Please unplug the board, and then press OK and plug back in.\nMission Planner will look for 30 seconds to find the board"); } } catch (Exception ex) { log.Error(ex); CustomMessageBox.Show("Please unplug the board, and then press OK and plug back in.\nMission Planner will look for 30 seconds to find the board"); } DateTime DEADLINE = DateTime.Now.AddSeconds(30); updateProgress(0, "Scanning comports"); while (DateTime.Now < DEADLINE) { string[] allports = SerialPort.GetPortNames(); foreach (string port in allports) { log.Info(DateTime.Now.Millisecond + " Trying Port " + port); updateProgress(-1, "Connecting"); try { up = new px4uploader.Uploader(port, 115200); } catch (Exception ex) { //System.Threading.Thread.Sleep(50); Console.WriteLine(ex.Message); continue; } try { up.identify(); updateProgress(-1, "Identify"); log.InfoFormat("Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}", up.board_type, up.board_rev, up.bl_rev, up.fw_maxsize, port); } catch (Exception) { Console.WriteLine("Not There.."); //Console.WriteLine(ex.Message); up.close(); continue; } up.skipotp = true; try { up.currentChecksum(fw); } catch { up.__reboot(); up.close(); CustomMessageBox.Show("No need to upload. already on the board"); return(true); } try { up.ProgressEvent += new px4uploader.Uploader.ProgressEventHandler(up_ProgressEvent); up.LogEvent += new px4uploader.Uploader.LogEventHandler(up_LogEvent); updateProgress(0, "Upload"); up.upload(fw); updateProgress(100, "Upload Done"); } catch (Exception ex) { updateProgress(0, "ERROR: " + ex.Message); log.Info(ex); Console.WriteLine(ex.ToString()); return(false); } finally { up.close(); } if (up.board_type == 1140 || up.board_type == 1145 || up.board_type == 1150 || up.board_type == 1151 || up.board_type == 1152 || up.board_type == 1210 || up.board_type == 1351 || up.board_type == 1352 || up.board_type == 1411 || up.board_type == 1520) {//VR boards have no tone alarm if (up.board_type == 1140) { CustomMessageBox.Show("Upload complete! Please unplug and reconnect board."); } else { CustomMessageBox.Show("Upload complete!"); } } else { // wait for IO firmware upgrade and boot to a mavlink state CustomMessageBox.Show("Please wait for the musical tones to finish before clicking OK"); } return(true); } } updateProgress(0, "ERROR: No Response from board"); return(false); }
/// <summary> /// upload to px4 standalone /// </summary> /// <param name="filename"></param> public bool UploadPX4(string filename) { Uploader up; updateProgress(0, "Reading Hex File"); px4uploader.Firmware fw; try { fw = px4uploader.Firmware.ProcessFirmware(filename); } catch (Exception ex) { CustomMessageBox.Show(Strings.ErrorFirmwareFile + "\n\n" + ex.ToString(), Strings.ERROR); return(false); } try { // check if we are seeing heartbeats MainV2.comPort.BaseStream.Open(); MainV2.comPort.giveComport = true; BoardDetect.boards board = BoardDetect.DetectBoard(MainV2.comPortName); if (MainV2.comPort.getHeartBeat().Length > 0) { MainV2.comPort.doReboot(true); MainV2.comPort.Close(); //specific action for VRBRAIN4 board that needs to be manually disconnected before uploading if (board == BoardDetect.boards.vrbrainv40) { CustomMessageBox.Show("VRBRAIN 4 detected. Please unplug the board then press OK and plug back in.\n"); } } else { MainV2.comPort.BaseStream.Close(); CustomMessageBox.Show("Please unplug the board, and then press OK and plug back in.\nMission Planner will look for 30 seconds to find the board"); } } catch (Exception ex) { log.Error(ex); CustomMessageBox.Show("Please unplug the board, and then press OK and plug back in.\nMission Planner will look for 30 seconds to find the board"); } DateTime DEADLINE = DateTime.Now.AddSeconds(30); updateProgress(0, "Scanning comports"); while (DateTime.Now < DEADLINE) { string[] allports = SerialPort.GetPortNames(); foreach (string port in allports) { log.Info(DateTime.Now.Millisecond + " Trying Port " + port); updateProgress(-1, "Connecting"); try { up = new Uploader(port, 115200); } catch (Exception ex) { //System.Threading.Thread.Sleep(50); Console.WriteLine(ex.Message); continue; } try { up.identify(); updateProgress(-1, "Identify"); log.InfoFormat("Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}", up.board_type, up.board_rev, up.bl_rev, up.fw_maxsize, port); up.ProgressEvent += new Uploader.ProgressEventHandler(up_ProgressEvent); up.LogEvent += new Uploader.LogEventHandler(up_LogEvent); } catch (Exception) { Console.WriteLine("Not There.."); //Console.WriteLine(ex.Message); up.close(); continue; } // test if pausing here stops - System.TimeoutException: The write timed out. System.Threading.Thread.Sleep(500); try { up.verifyotp(); if (up.libre) { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "libre", ""); } else { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "Pass", ""); } } catch (Org.BouncyCastle.Security.InvalidKeyException ex) { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "InvalidKeyException", ""); log.Error(ex); CustomMessageBox.Show("You are using unsupported hardware.\nThis board does not contain a valid certificate of authenticity.\nPlease contact your hardware vendor about signing your hardware.", "Invalid Cert"); up.skipotp = true; } catch (FormatException ex) { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "FormatException", ""); log.Error(ex); CustomMessageBox.Show("You are using unsupported hardware.\nThis board does not contain a valid certificate of authenticity.\nPlease contact your hardware vendor about signing your hardware.", "Invalid Cert"); up.skipotp = true; } catch (IOException ex) { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "IOException", ""); log.Error(ex); CustomMessageBox.Show("lost communication with the board.", "lost comms"); up.close(); return(false); } catch (TimeoutException ex) { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "TimeoutException", ""); log.Error(ex); CustomMessageBox.Show("lost communication with the board.", "lost comms"); up.close(); return(false); } catch (Exception ex) { MissionPlanner.Utilities.Tracking.AddEvent("FWUpload", "verifyotp", "Exception", ""); log.Error(ex); CustomMessageBox.Show("lost communication with the board. " + ex.ToString(), "lost comms"); up.close(); return(false); } try { up.currentChecksum(fw); } catch (IOException ex) { log.Error(ex); CustomMessageBox.Show("lost communication with the board.", "lost comms"); up.close(); return(false); } catch { up.__reboot(); up.close(); CustomMessageBox.Show("No need to upload. already on the board"); return(true); } try { updateProgress(0, "Upload"); up.upload(fw); updateProgress(100, "Upload Done"); } catch (Exception ex) { updateProgress(0, "ERROR: " + ex.Message); log.Info(ex); Console.WriteLine(ex.ToString()); return(false); } finally { up.close(); } // wait for IO firmware upgrade and boot to a mavlink state CustomMessageBox.Show("Please wait for the musical tones to finish before clicking OK"); return(true); } } updateProgress(0, "ERROR: No Response from board"); return(false); }
/// <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("This board has been retired, Mission Planner this will upload the last available version to your board", "Note"); } } if (historyhash != "") { baseurl = getUrl(historyhash, baseurl); } // update to use mirror url Localizations.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)); }
/// <summary> /// upload to arduino standalone /// </summary> /// <param name="filename"></param> /// <param name="board"></param> public bool UploadFlash(string comport, string filename, BoardDetect.boards board) { if (board == BoardDetect.boards.px4 || board == BoardDetect.boards.px4v2) { try { return(UploadPX4(filename)); } catch (MissingFieldException) { CustomMessageBox.Show("Please update, your install is currupt", Strings.ERROR); return(false); } } if (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) { return(UploadVRBRAIN(filename)); } byte[] FLASH = new byte[1]; try { updateProgress(0, Strings.ReadingHexFile); using (StreamReader sr = new StreamReader(filename)) { FLASH = readIntelHEXv2(sr); } log.InfoFormat("\n\nSize: {0}\n\n", FLASH.Length); } catch (Exception ex) { updateProgress(0, Strings.FailedReadHEX); CustomMessageBox.Show(Strings.FailedToReadHex + ex.Message); return(false); } IArduinoComms port = new ArduinoSTK(); if (board == BoardDetect.boards.b1280) { if (FLASH.Length > 126976) { CustomMessageBox.Show("Firmware is to big for a 1280, Please upgrade your hardware!!"); return(false); } //port = new ArduinoSTK(); port.BaudRate = 57600; } else if (board == BoardDetect.boards.b2560 || board == BoardDetect.boards.b2560v2) { port = new ArduinoSTKv2 { BaudRate = 115200 }; } port.DataBits = 8; port.StopBits = System.IO.Ports.StopBits.One; port.Parity = System.IO.Ports.Parity.None; port.DtrEnable = true; try { port.PortName = comport; port.Open(); if (port.connectAP()) { log.Info("starting"); updateProgress(0, String.Format(Strings.UploadingBytesToBoard, FLASH.Length) + board); // this is enough to make ap_var reset //port.upload(new byte[256], 0, 2, 0); port.Progress += updateProgress; if (!port.uploadflash(FLASH, 0, FLASH.Length, 0)) { if (port.IsOpen) { port.Close(); } throw new Exception("Upload failed. Lost sync. Try Arduino!!"); } port.Progress -= updateProgress; updateProgress(100, Strings.UploadComplete); log.Info("Uploaded"); int start = 0; short length = 0x100; byte[] flashverify = new byte[FLASH.Length + 256]; updateProgress(0, Strings.VerifyFirmware); while (start < FLASH.Length) { updateProgress((int)((start / (float)FLASH.Length) * 100), Strings.VerifyFirmware); port.setaddress(start); //log.Info("Downloading " + length + " at " + start); port.downloadflash(length).CopyTo(flashverify, start); start += length; } for (int s = 0; s < FLASH.Length; s++) { if (FLASH[s] != flashverify[s]) { CustomMessageBox.Show(String.Format(Strings.UploadSucceededButVerifyFailed, FLASH[s].ToString("X"), flashverify[s].ToString("X")) + s); port.Close(); return(false); } } updateProgress(100, Strings.VerifyComplete); } else { updateProgress(0, Strings.FailedUpload); CustomMessageBox.Show(Strings.CommunicationErrorNoConnection); } port.Close(); try { ((SerialPort)port).Open(); } catch { } //CustomMessageBox.Show("1. If you are updating your firmware from a previous version, please verify your parameters are appropriate for the new version.\n2. Please ensure your accelerometer is calibrated after installing or re-calibrated after updating the firmware."); try { ((SerialPort)port).Close(); } catch { } updateProgress(100, Strings.Done); } catch (Exception ex) { updateProgress(0, Strings.FailedUpload); CustomMessageBox.Show(Strings.CheckPortSettingsOr + ex); try { port.Close(); } catch { } return(false); } MainV2.comPort.giveComport = false; return(true); }
/// <summary> /// return the software id from eeprom /// </summary> /// <param name="comport">Port</param> /// <param name="version">Board type</param> /// <returns></returns> public static int decodeApVar(string comport, BoardDetect.boards version) { IArduinoComms port = new ArduinoSTK(); if (version == boards.b1280) { port = new ArduinoSTK(); port.BaudRate = 57600; } else if (version == boards.b2560 || version == boards.b2560v2) { port = new ArduinoSTKv2(); port.BaudRate = 115200; } else { return(-1); } port.PortName = comport; port.DtrEnable = true; port.Open(); port.connectAP(); byte[] buffer = port.download(1024 * 4); port.Close(); if (buffer[0] != 'A' && buffer[0] != 'P' || buffer[1] != 'P' && buffer[1] != 'A') // this is the apvar header { return(-1); } else { if (buffer[0] == 'A' && buffer[1] == 'P' && buffer[2] == 2) { // apvar header and version int pos = 4; byte key = 0; while (pos < (1024 * 4)) { int size = buffer[pos] & 63; pos++; key = buffer[pos]; pos++; log.InfoFormat("{0:X4}: key {1} size {2}\n ", pos - 2, key, size + 1); if (key == 0xff) { log.InfoFormat("end sentinal at {0}", pos - 2); break; } if (key == 0) { //Array.Reverse(buffer, pos, 2); return(BitConverter.ToUInt16(buffer, pos)); } for (int i = 0; i <= size; i++) { Console.Write(" {0:X2}", buffer[pos]); pos++; } } } if (buffer[0] == 'P' && buffer[1] == 'A' && buffer[2] == 5) // ap param { int pos = 4; byte key = 0; while (pos < (1024 * 4)) { key = buffer[pos]; pos++; int group = buffer[pos]; pos++; int type = buffer[pos]; pos++; int size = type_size((ap_var_type)Enum.Parse(typeof(ap_var_type), type.ToString())); Console.Write("{0:X4}: type {1} ({2}) key {3} group {4} size {5}\n ", pos - 2, type, type_names[type], key, group, size); if (key == 0xff) { log.InfoFormat("end sentinal at {0}", pos - 2); break; } if (key == 0) { //Array.Reverse(buffer, pos, 2); return(BitConverter.ToUInt16(buffer, pos)); } for (int i = 0; i < size; i++) { Console.Write(" {0:X2}", buffer[pos]); pos++; } } } if (buffer[0] == 'P' && buffer[1] == 'A' && buffer[2] == 6) // ap param { int pos = 4; byte key = 0; while (pos < (1024 * 4)) { key = buffer[pos]; pos++; if (key == 0xff) { log.InfoFormat("end sentinal at {0}", pos - 1); break; } int type = buffer[pos] & 0x3f; // 6 bits uint group = BitConverter.ToUInt32(buffer, pos); //((byte)(buffer[pos]) >> 6) | ((byte)(buffer[pos + 1]) << 8) | ((byte)(buffer[pos + 2]) << 16); // 18 bits group = (group >> 6) & 0x3ffff; pos++; pos++; pos++; int size = BoardDetect.type_size((BoardDetect.ap_var_type)Enum.Parse(typeof(BoardDetect.ap_var_type), type.ToString())); Console.Write("{0:X4}: type {1} ({2}) key {3} group_element {4} size {5} value ", pos - 4, type, BoardDetect.type_names[type], key, group, size); if (key == 0) { //Array.Reverse(buffer, pos, 2); return(BitConverter.ToUInt16(buffer, pos)); } for (int i = 0; i < size; i++) { Console.Write(" {0:X2}", buffer[pos]); pos++; } Console.WriteLine(); } } } return(-1); }
/// <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, "Detecting Board Version"); board = BoardDetect.DetectBoard(comport); if (board == BoardDetect.boards.none) { CustomMessageBox.Show("Cant detect your Board version. Please check your cabling"); 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.vrherov10) { try { apmformat_version = BoardDetect.decodeApVar(comport, board); } catch { } if (apmformat_version != -1 && apmformat_version != temp.k_format_version) { if (DialogResult.No == CustomMessageBox.Show("Epprom changed, all your setting will be lost during the update,\nDo you wish to continue?", "Epprom format changed (" + apmformat_version + " vs " + temp.k_format_version + ")", MessageBoxButtons.YesNo)) { CustomMessageBox.Show("Please connect and backup your config in the configuration tab."); return(false); } } } log.Info("Detected a " + board); updateProgress(-1, "Detected a " + 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.vrherov10) { baseurl = temp.urlvrherov10.ToString(); } else { CustomMessageBox.Show("Invalid Board Type"); return(false); } if (historyhash != "") { baseurl = getUrl(historyhash, 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, "Downloading from Internet"); dataStream.ReadTimeout = 30000; while (dataStream.CanRead) { try { updateProgress(50, "Downloading from Internet"); } 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, "Downloaded from Internet"); log.Info("Downloaded"); } catch (Exception ex) { updateProgress(50, "Failed download"); 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)); }
/// <summary> /// upload to arduino standalone /// </summary> /// <param name="filename"></param> /// <param name="board"></param> public bool UploadFlash(string comport, string filename, BoardDetect.boards board) { if (board == BoardDetect.boards.px4 || board == BoardDetect.boards.px4v2) { return(UploadPX4(filename)); } byte[] FLASH = new byte[1]; StreamReader sr = null; try { updateProgress(0, "Reading Hex File"); sr = new StreamReader(filename); FLASH = readIntelHEXv2(sr); sr.Close(); log.InfoFormat("\n\nSize: {0}\n\n", FLASH.Length); } catch (Exception ex) { if (sr != null) { sr.Dispose(); } updateProgress(0, "Failed read HEX"); CustomMessageBox.Show("Failed to read firmware.hex : " + ex.Message); return(false); } IArduinoComms port = new ArduinoSTK(); if (board == BoardDetect.boards.b1280) { if (FLASH.Length > 126976) { CustomMessageBox.Show("Firmware is to big for a 1280, Please upgrade your hardware!!"); return(false); } //port = new ArduinoSTK(); port.BaudRate = 57600; } else if (board == BoardDetect.boards.b2560 || board == BoardDetect.boards.b2560v2) { port = new ArduinoSTKv2 { BaudRate = 115200 }; } port.DataBits = 8; port.StopBits = System.IO.Ports.StopBits.One; port.Parity = System.IO.Ports.Parity.None; port.DtrEnable = true; try { port.PortName = comport; port.Open(); if (port.connectAP()) { log.Info("starting"); updateProgress(0, "Uploading " + FLASH.Length + " bytes to Board: " + board); // this is enough to make ap_var reset //port.upload(new byte[256], 0, 2, 0); port.Progress += updateProgress; if (!port.uploadflash(FLASH, 0, FLASH.Length, 0)) { if (port.IsOpen) { port.Close(); } throw new Exception("Upload failed. Lost sync. Try Arduino!!"); } port.Progress -= updateProgress; updateProgress(100, "Upload Complete"); log.Info("Uploaded"); int start = 0; short length = 0x100; byte[] flashverify = new byte[FLASH.Length + 256]; updateProgress(0, "Verify Firmware"); while (start < FLASH.Length) { updateProgress((int)((start / (float)FLASH.Length) * 100), "Verify Firmware"); port.setaddress(start); log.Info("Downloading " + length + " at " + start); port.downloadflash(length).CopyTo(flashverify, start); start += length; } for (int s = 0; s < FLASH.Length; s++) { if (FLASH[s] != flashverify[s]) { CustomMessageBox.Show("Upload succeeded, but verify failed: exp " + FLASH[s].ToString("X") + " got " + flashverify[s].ToString("X") + " at " + s); port.Close(); return(false); } } updateProgress(100, "Verify Complete"); } else { updateProgress(0, "Failed upload"); CustomMessageBox.Show("Communication Error - no connection"); } port.Close(); try { ((SerialPort)port).Open(); } catch { } //CustomMessageBox.Show("1. If you are updating your firmware from a previous version, please verify your parameters are appropriate for the new version.\n2. Please ensure your accelerometer is calibrated after installing or re-calibrated after updating the firmware."); try { ((SerialPort)port).Close(); } catch { } updateProgress(100, "Done"); } catch (Exception ex) { updateProgress(0, "Failed upload"); CustomMessageBox.Show("Check port settings or Port in use? " + ex); try { port.Close(); } catch { } return(false); } MainV2.comPort.giveComport = false; return(true); }
/// <summary> /// upload to px4 standalone /// </summary> /// <param name="filename"></param> public bool UploadPX4(string filename) { Uploader up; updateProgress(0, "Reading Hex File"); px4uploader.Firmware fw; try { fw = px4uploader.Firmware.ProcessFirmware(filename); } catch (Exception ex) { CustomMessageBox.Show(Strings.ErrorFirmwareFile + "\n\n" + ex.ToString(), Strings.ERROR); return(false); } try { // check if we are seeing heartbeats MainV2.comPort.BaseStream.Open(); MainV2.comPort.giveComport = true; BoardDetect.boards board = BoardDetect.DetectBoard(MainV2.comPortName); if (MainV2.comPort.getHeartBeat().Length > 0) { MainV2.comPort.doReboot(true); MainV2.comPort.Close(); //specific action for VRBRAIN4 board that needs to be manually disconnected before uploading if (board == BoardDetect.boards.vrbrainv40) { CustomMessageBox.Show("VRBRAIN 4 detected. Please unplug the board then press OK and plug back in.\n"); } } else { MainV2.comPort.BaseStream.Close(); CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd); } } catch (Exception ex) { log.Error(ex); CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd); } DateTime DEADLINE = DateTime.Now.AddSeconds(30); updateProgress(0, "Scanning comports"); while (DateTime.Now < DEADLINE) { string[] allports = SerialPort.GetPortNames(); foreach (string port in allports) { log.Info(DateTime.Now.Millisecond + " Trying Port " + port); updateProgress(-1, "Connecting"); try { up = new Uploader(port, 115200); } catch (Exception ex) { //System.Threading.Thread.Sleep(50); Console.WriteLine(ex.Message); continue; } try { up.identify(); updateProgress(-1, "Identify"); log.InfoFormat("Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}", up.board_type, up.board_rev, up.bl_rev, up.fw_maxsize, port); up.ProgressEvent += new Uploader.ProgressEventHandler(up_ProgressEvent); up.LogEvent += new Uploader.LogEventHandler(up_LogEvent); } catch (Exception) { Console.WriteLine("Not There.."); //Console.WriteLine(ex.Message); up.close(); continue; } // test if pausing here stops - System.TimeoutException: The write timed out. System.Threading.Thread.Sleep(500); try { up.currentChecksum(fw); } catch (IOException ex) { log.Error(ex); CustomMessageBox.Show("lost communication with the board.", "lost comms"); up.close(); return(false); } catch { up.__reboot(); up.close(); CustomMessageBox.Show(Strings.NoNeedToUpload); return(true); } try { updateProgress(0, "Upload"); up.upload(fw); updateProgress(100, "Upload Done"); } catch (Exception ex) { updateProgress(0, "ERROR: " + ex.Message); log.Info(ex); Console.WriteLine(ex.ToString()); return(false); } finally { up.close(); } // wait for IO firmware upgrade and boot to a mavlink state CustomMessageBox.Show(Strings.PleaseWaitForTheMusicalTones); return(true); } } updateProgress(0, "ERROR: No Response from board"); return(false); }
/// <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)); }