private static void LogInfo(string content, WriteType type) { if (_canWriteLog == false) { return; } if (_sw == null) { throw new ArgumentNullException(); } string title = null; if (type == WriteType.Warning) { title = "[Warning]"; } else if (type == WriteType.Error) { title = "[Error]"; } else { title = "[Operate]"; } DateTime now = DateTime.Now; _sw.WriteLine("{0}{1} {2}", title, now.ToString("yyyy-MM-dd HH:mm:ss.fff"), content); _sw.Flush(); }
public CKernelWriter(Vehicle vehicle, Protocol protocol, WriteType writeType, ILogger logger) { this.vehicle = vehicle; this.protocol = protocol; this.writeType = writeType; this.logger = logger; }
private void writeGetterSetter(StreamWriter sw, List <Struct> cstructs, WriteType t) { foreach (Struct cstruct in cstructs) { if (t == WriteType.get) { writeFunctionGetter(sw, cstruct, false, cstructs); } else { writeFunctionSetter(sw, cstruct, false, cstructs); } } sw.WriteLine(); foreach (Struct cstruct in cstructs) { if (t == WriteType.get) { writeFunctionGetter(sw, cstruct, true, cstructs); sw.WriteLine(); } else { writeFunctionSetter(sw, cstruct, true, cstructs); sw.WriteLine(); } } }
private static void SetConsoleColorFromType(WriteType writeType) { switch (writeType) { case WriteType.Log: SysCon.ForegroundColor = ConsoleColor.Gray; break; case WriteType.Error: SysCon.ForegroundColor = ConsoleColor.Red; break; case WriteType.Warning: SysCon.ForegroundColor = ConsoleColor.Yellow; break; case WriteType.DB: SysCon.ForegroundColor = ConsoleColor.Magenta; break; case WriteType.CMD: SysCon.ForegroundColor = ConsoleColor.Green; break; case WriteType.System: SysCon.ForegroundColor = ConsoleColor.Cyan; break; default: SysCon.ForegroundColor = ConsoleColor.White; break; } }
/// <summary> /// Compare the two operating system IDs, report on the ramifications, set a flag if the write should be halted. /// </summary> public static void ReportOperatingSystems(UInt32 fileOs, UInt32 pcmOs, WriteType writeType, ILogger logger, out bool shouldHalt) { shouldHalt = false; if (fileOs == pcmOs) { logger.AddUserMessage("PCM and image file are both operating system " + fileOs); } else { if ((writeType == WriteType.OsPlusCalibrationPlusBoot) || (writeType == WriteType.Full)) { logger.AddUserMessage("Changing PCM to operating system " + fileOs); } else if (writeType == WriteType.TestWrite) { logger.AddUserMessage("PCM and image file are different operating systems."); logger.AddUserMessage("But we'll ignore that because this is just a test write."); } else { logger.AddUserMessage("Flashing this file could render your PCM unusable."); shouldHalt = true; } } }
public static void WriteOnly(string outFileName, List <string> content, WriteType type = WriteType.TEXT) { if (string.IsNullOrEmpty(CDNResourceMoveConfig.Instance().logOutPath) || !Directory.Exists(CDNResourceMoveConfig.Instance().logOutPath)) { Debug.LogError("write error !:" + CDNResourceMoveConfig.Instance().logOutPath); return; } string outputPath = CDNResourceMoveConfig.Instance().logOutPath + "/" + outFileName; string dir = Path.GetDirectoryName(outputPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (type == WriteType.EXCEL) { ExcelIns ei = ExcelManager.GetExcel(outputPath + ".xls"); ei.WriteSimpleList(content); //ei.GetWorkSheet(); } else { outputPath = outputPath + ".txt"; if (!File.Exists(outputPath)) { FileStream fs1 = new FileStream(outputPath, FileMode.Create, FileAccess.Write);//创建写入文件 fs1.Close(); } System.IO.File.WriteAllLines(outputPath, content.ToArray()); } }
static void WriteMessage(string message = default, WriteType type = WriteType.Information, bool inline = false) { switch (type) { case WriteType.Information: ForegroundColor = ConsoleColor.Cyan; Write("[情報] "); break; case WriteType.Warning: ForegroundColor = ConsoleColor.Yellow; Write("[注意] "); break; case WriteType.Error: ForegroundColor = ConsoleColor.Red; Write("[警告] "); break; case WriteType.Memo: ForegroundColor = ConsoleColor.DarkBlue; Write("[メモ] "); break; case WriteType.Success: ForegroundColor = ConsoleColor.Green; Write("[成功] "); break; case WriteType.Failure: ForegroundColor = ConsoleColor.DarkRed; Write("[失敗] "); break; case WriteType.Input: ForegroundColor = ConsoleColor.DarkGray; Write("[入力] "); break; case WriteType.Select: ForegroundColor = ConsoleColor.DarkMagenta; Write("[選択] "); break; } if (message is string) { if (inline) { Write(message); } else { WriteLine(message); } } ResetColor(); }
public void Write(IDictionary <TMeta, TSet> items, WriteType writeType = WriteType.Update) { foreach (KeyValuePair <TMeta, TSet> item in items) { TSession session = GetOrCreate(item.Key); session.Write(item.Value, writeType); } }
public static void Display(string theText, WriteType outputMethod) { switch (outputMethod) { case WriteType.ToFile: WriteToFile(theText); break; case WriteType.ToScreen: WriteToScreen(theText); break; } }
/// <summary> /// Write the Lines to Library /// </summary> /// <param name="type">Write Type</param> protected virtual void WriteLines(WriteType type) { ////check if a nuclide is selected //if (matchedNuclidesGrid.SelectedRows.Count <= 0) // return; try { //get the nuclides to write to the library DataRow nuc = SelectedNuclide.Row; bool isPhotoPeak = (string)nuc["NAME"] != "S.E." && (string)nuc["NAME"] != "D.E." && !((string)nuc["NAME"]).Contains("Sum"); //check if the nuclide has a half-life that is too long if (nuc["HALF_LIFE_UNIT"].ToString().Equals("y") && (double)nuc["HALF_LIFE"] / (31557600 * 1E6) > Int32.MaxValue) { throw new ArgumentException($"The Half-life for " + (string)nuc["NAME"] + " is too large to be supported. It will not be added to the library"); } //get the lines to write to the library if (isPhotoPeak) { DataTable writeLines; switch (type) { case WriteType.All: writeLines = Lines.ToTable(); break; case WriteType.Matched: writeLines = Lines.ToTable().Select("MATCHED = True").CopyToDataTable(); break; case WriteType.Selected: writeLines = matches.Lines.Clone(); foreach (DataRowView line in SelectedLines) { writeLines.ImportRow(line.Row); } break; default: writeLines = matches.Lines.Select().CopyToDataTable(); break; } //write the nuclides to the library libGen.WriteNuclide(nuc, writeLines, CombineLinesCallback); } //set the persistent matches matches.SetPersistentMatches(); } catch (Exception ex) { DialogViewModel dialogViewModel = new DialogViewModel($"There was an exeption while writing to the library:\n {ex.Message}", "Library Exception", true); dialogService.ShowDialog(dialogViewModel); } }
/// <summary> /// Write an index row of key pair of <param name="rowPrimaryKey"> <param name="rowLocation"> using the WriteType <param name="type">. /// </summary> /// <param name="rowPrimaryKey"> /// Primary key for row. /// </param> /// <param name="rowLocation"> /// The location of the row with <param name="rowPrimaryKey"> in the database. /// </param> /// <param name="type"> /// The kind of row write to perform. /// </param> private void WriteIndexRow(int rowPrimaryKey, int rowLocation, WriteType type) { // If we're moving an index within the index file (rellocating), set the stream position appropriately. if (type == WriteType.IndexRowMove) { IndexStream.Position = (rowLocation - 1) * INDEX_ROW_BYTE_SIZE; } // Write the index values. IndexWriter.Write(rowPrimaryKey); IndexWriter.Write(rowLocation); }
public void Dev2PutRawOperation_Constructor_TakesContentsAndWriteTypeEnum() { //------------Setup for test-------------------------- const WriteType WriteType = WriteType.AppendBottom; const string Contents = "Some test"; //------------Execute Test--------------------------- var dev2PutRawOperation = new Dev2PutRawOperationTO(WriteType, Contents); //------------Assert Results------------------------- Assert.IsNotNull(dev2PutRawOperation); }
public static void SetLogFileName(WriteType writeType, bool useTempFolder = false) { try { string logFolder = CreateLogFolder(useTempFolder); string fileName = string.Format("{0}.log", GetProgramName()); if (writeType == WriteType.CreateNew) { string[] existingLogFiles = Directory.GetFiles(logFolder, string.Format("{0}*.log", GetProgramName())); if (existingLogFiles.Length != 0) { int maxLogFileNumber = 0; foreach (string logFile in existingLogFiles) { string[] sep = new string[1]; sep[0] = GetProgramName(); string[] logNumbers = logFile.Split(sep, StringSplitOptions.RemoveEmptyEntries); foreach (string workingNumber in logNumbers) { string num = workingNumber.ToUpper().Replace(".LOG", ""); if (int.TryParse(num, out int n)) { if (n > maxLogFileNumber) { maxLogFileNumber = n; } } } } fileName = string.Format("{0}{1}.log", GetProgramName(), maxLogFileNumber + 1); } } LogFile = new FileInfo(Path.Combine(logFolder, fileName)); Debug.WriteLine(string.Format("Logfile name: {0}", LogFile.FullName)); string initial = string.Format("\r\nLog start: {0}\r\n----------------------\r\n", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")); if (writeType == WriteType.OverWrite) { File.WriteAllText(LogFile.FullName, initial); } else { File.AppendAllText(LogFile.FullName, initial); } } catch (Exception e) { Debug.WriteLine("Exception occured during SetLogFileName: " + e.Message); if (WriteToConsole) { Console.WriteLine("Exception occured during SetLogFileName: " + e.Message); } } }
public void Dev2PutRawOperationTO_Constructor_GivenParameter_ShouldSetProperties() { //------------Setup for test-------------------------- const WriteType WriteType = WriteType.AppendBottom; const string Contents = "Some test"; //------------Execute Test--------------------------- var dev2PutRawOperation = new Dev2PutRawOperationTO(WriteType, Contents); //------------Assert Results------------------------- Assert.AreEqual(WriteType, dev2PutRawOperation.WriteType); Assert.AreEqual(Contents, dev2PutRawOperation.FileContents); }
/// <summary> /// This takes ownership of the random number generator. /// </summary> public DelegateEnvironment(Random rand, int verbose = 0, MessageSensitivity sensitivity = MessageSensitivity.All, int conc = 0, WriteType outWriter = null, WriteType errWriter = null) : base(rand, verbose > 0, conc, nameof(DelegateEnvironment)) { Contracts.CheckValueOrNull(outWriter); Contracts.CheckValueOrNull(errWriter); Contracts.CheckParam(verbose >= 0 && verbose <= 4, nameof(verbose), "verbose must be in [[0, 4]]"); _outErrWriter = new OutErrLogWriter(this, new LogWriter(outWriter), new LogWriter(errWriter), verbose); _sensitivityFlags = sensitivity; _verbose = verbose; AddListener <ChannelMessage>(PrintMessage); }
private void writeGetterSetter(StreamWriter sw, List <CStruct> cstructs, WriteType t) { /*string[] whiteList = new string[] { * "OMX_PARAM_PORTDEFINITIONTYPE" , * "OMX_AUDIO_PORTDEFINITIONTYPE", * "OMX_VIDEO_PORTDEFINITIONTYPE", * "OMX_IMAGE_PORTDEFINITIONTYPE", * "OMX_OTHER_PORTDEFINITIONTYPE", * "OMX_VIDEO_PARAM_PORTFORMATTYPE" * };*/ foreach (CStruct cstruct in cstructs) { //if (!whiteList.Contains(cstruct.name)) continue; if (blackList.Contains(cstruct.name)) { continue; } if (t == WriteType.get) { writeFunctionGetter(sw, cstruct, false, cstructs); } else { writeFunctionSetter(sw, cstruct, false, cstructs); } } sw.WriteLine(); foreach (CStruct cstruct in cstructs) { //if (!whiteList.Contains(cstruct.name)) continue; if (blackList.Contains(cstruct.name)) { continue; } if (t == WriteType.get) { writeFunctionGetter(sw, cstruct, true, cstructs); sw.WriteLine(); } else { writeFunctionSetter(sw, cstruct, true, cstructs); sw.WriteLine(); } } }
/// <summary> /// 将 System.Object 写入 HTTP 响应流。 /// </summary> /// <param name="obj">要写入 HTTP 输出流的 System.Object。</param> /// <param name="contentType">返回客户端的类型</param> public async Task WriteAsync(object obj, WriteType contentType) { if (Response != null) { if (obj == null) { obj = string.Empty; } bool isstr = obj.GetType() == typeof(string); switch (contentType) { case WriteType.Html: SetContentType("text/html"); await Response.WriteAsync(obj.ToString()); break; case WriteType.Json: SetContentType("application/json"); await Response.WriteAsync(isstr?obj.ToString() : obj.ToJson(routeData.JsonOptions)); break; case WriteType.Xml: SetContentType("application/xml"); await Response.WriteAsync(obj.ToString()); break; case WriteType.Text: SetContentType("text/plain"); await Response.WriteAsync(obj.ToString()); break; } } else { throw new System.Exception("请在{Ashx注入后}调用方法,使用。"); } }
private string PrepareLine(WriteType type, Exception exception, string message) { if (exception != null) { return(string.Format("{0} {1} {2} {3} {4}\r\n{5}\r\n", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), Enum.GetName(typeof(WriteType), type), message, exception.Message, exception.StackTrace)); } else { return(string.Format("{0} {1} {2} {3}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), Enum.GetName(typeof(WriteType), type), message)); } }
private void InternalWrite(WriteType type, Exception exception, string message) { try { lock (_locker) { var logDir = Path.Combine(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "LazuriteLogs"); if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } var logPath = Path.Combine(logDir, _logFileName); if (!File.Exists(logPath)) { File.Create(logPath); } if (new FileInfo(logPath).Length > 1024 * 1024 * 1024) //1mb { File.WriteAllText(logPath, PrepareLine(type, exception, message)); } else { File.AppendAllLines(logPath, new[] { PrepareLine(type, exception, message) }); } } } catch (Exception e) { try { AlertDialog.Builder alert = new AlertDialog.Builder(Application.Context); alert.SetMessage("Ошибка при записи в лог: " + e.Message); alert.Show(); } catch { //mega crutch } } }
public WriterBase GetWriter(WriteType writerType, TextControl textControl) { var writer = default(WriterBase); switch (writerType) { case WriteType.Instant: writer = _writers[typeof(InstantWriter)]; break; case WriteType.CharByChar: writer = _writers[typeof(CharByCharWriter)]; break; default: Debug.LogError($"Type: {writerType} is not in the factory."); return(null); } writer.SetTextControl(textControl); return(writer); }
/// <summary> /// 将 System.Object 写入 HTTP 响应流。 /// </summary> /// <param name="obj">要写入 HTTP 输出流的 System.Object。</param> /// <param name="contentType">返回客户端的类型</param> public void Write(object obj, WriteType contentType) { WriteAsync(obj, contentType).Wait(); //if (Response != null) //{ // if (obj == null) // { // obj = string.Empty; // } // bool isstr = obj.GetType() == typeof(string); // switch (contentType) // { // case WriteType.Html: // SetContentType("text/html"); // Response.Write(obj.ToString()); // break; // case WriteType.Json: // SetContentType("application/json"); // Response.Write(isstr ? obj.ToString() : obj.ToJson()); // break; // case WriteType.Xml: // SetContentType("application/xml"); // Response.Write(obj.ToString()); // break; // case WriteType.Text: // SetContentType("text/plain"); // Response.Write(obj.ToString()); // break; // } //} //else //{ // throw new System.Exception("请在{Ashx注入后}调用方法,使用。"); //} }
public void InitializeWriteType() { string columnType = GetType(); switch (columnType) { case "int": case "decimal": WriteType = WriteType.Default; break; case "DateTime": WriteType = WriteType.Default; break; case "bool": WriteType = WriteType.Checkbox; break; default: WriteType = WriteType.Default; break; } }
/// <summary> /// Write the row <param name="row"> with primary key <param name="primaryKey"> using the WriteType <param name="type">. /// </summary> /// <param name="row"> /// Row to write. /// </param> /// <param name="primaryKey"> /// Primary key of row to write. /// </param> /// <param name="type"> /// The kind of row write to perform. /// </param> private void WriteRow(Row row, int primaryKey, WriteType type) { // If we're not udating an existing row. I.e. moving a row, writing a new row or deleting a row. if (type != WriteType.RowUpdate) { if (type != WriteType.NewRowWrite) { // Set the database stream to the location of the row DataBaseStream.Position = (Index [row.PrimaryKey] - 1) * ROW_BYTE_SIZE + HEADER_BYTE_SIZE; } // If the row is deleted, only write to it's status and leave the method. if (type == WriteType.RowDelete) { DataBaseWriter.Write(row.Status); return; } // Write the row's status and primary key. DataBaseWriter.Write(row.Status); DataBaseWriter.Write(primaryKey); // If it's a new row, write the new row's data and return from the method. if (type == WriteType.NewRowWrite) { DataBaseWriter.Write(row.NewTextData.PadRight(20, (char)0).ToCharArray()); DataBaseWriter.Write(row.NewNumberData); return; } } // If the row is being updated, set the database stream to the rows data locaton if (type == WriteType.RowUpdate) { DataBaseStream.Position = (Index [row.PrimaryKey] - 1) * ROW_BYTE_SIZE + HEADER_BYTE_SIZE + ROW_DATA_LOCATION; } // Write the row data. This will happen for rows being moved or updated. DataBaseWriter.Write(row.TextData.PadRight(20, (char)0).ToCharArray()); DataBaseWriter.Write(row.NumberData); }
public static void Write(WriteType type, string message, params object[] args) { var template = string.Format(" \t{0}:->{1} \t\t \t", type, message); Console.WriteLine(string.Format(template, args)); }
public Dev2PutRawOperationTO(WriteType writeType, string contents) { WriteType = writeType; FileContents = contents; }
private char GetCharForLine(WriteType Type) { if (Type.Equals(WriteType.Outgoing)) { return '»'; } return '«'; }
/// <summary> /// Create an PutRawOperationTo object /// </summary> /// <returns></returns> public static Dev2PutRawOperationTO CreatePutRawOperationTO(WriteType writeType, string contents) { return(new Dev2PutRawOperationTO(writeType, contents)); }
/// <summary> /// Write changes to the PCM's flash memory. /// </summary> private async void write_BackgroundThread(WriteType writeType) { using (new AwayMode()) { try { this.currentWriteType = writeType; if (this.Vehicle == null) { // This shouldn't be possible - it would mean the buttons // were enabled when they shouldn't be. return; } this.cancellationTokenSource = new CancellationTokenSource(); string path = null; this.Invoke((MethodInvoker) delegate() { this.DisableUserInput(); this.cancelButton.Enabled = true; path = this.ShowOpenDialog(); }); if (path == null) { return; } this.AddUserMessage(path); byte[] image; using (Stream stream = File.OpenRead(path)) { image = new byte[stream.Length]; int bytesRead = await stream.ReadAsync(image, 0, (int)stream.Length); if (bytesRead != stream.Length) { // If this happens too much, we should try looping rather than reading the whole file in one shot. this.AddUserMessage("Unable to load file."); return; } } // Sanity checks. FileValidator validator = new FileValidator(image, this); if (!validator.IsValid()) { this.AddUserMessage("This file is corrupt. It would render your PCM unusable."); return; } UInt32 kernelVersion = 0; bool needUnlock; int keyAlgorithm = 1; UInt32 pcmOperatingSystemId = 0; bool needToCheckOperatingSystem = writeType != WriteType.Full; this.AddUserMessage("Requesting operating system ID..."); Response <uint> osidResponse = await this.Vehicle.QueryOperatingSystemId(this.cancellationTokenSource.Token); if (osidResponse.Status == ResponseStatus.Success) { pcmOperatingSystemId = osidResponse.Value; PcmInfo info = new PcmInfo(pcmOperatingSystemId); keyAlgorithm = info.KeyAlgorithm; needUnlock = true; if (needToCheckOperatingSystem && !validator.IsSameOperatingSystem(pcmOperatingSystemId)) { this.AddUserMessage("Flashing this file could render your PCM unusable."); return; } needToCheckOperatingSystem = false; } else { if (this.cancellationTokenSource.Token.IsCancellationRequested) { return; } this.AddUserMessage("Operating system request failed, checking for a live kernel..."); kernelVersion = await this.Vehicle.GetKernelVersion(); if (kernelVersion == 0) { this.AddUserMessage("Checking for recovery mode..."); bool recoveryMode = await this.Vehicle.IsInRecoveryMode(); if (recoveryMode) { this.AddUserMessage("PCM is in recovery mode."); needUnlock = true; } else { this.AddUserMessage("PCM is not responding to OSID, kernel version, or recovery mode checks."); this.AddUserMessage("Unlock may not work, but we'll try..."); needUnlock = true; } } else { needUnlock = false; this.AddUserMessage("Kernel version: " + kernelVersion.ToString("X8")); this.AddUserMessage("Asking kernel for the PCM's operating system ID..."); if (needToCheckOperatingSystem && !await this.Vehicle.IsSameOperatingSystemAccordingToKernel(validator, this.cancellationTokenSource.Token)) { this.AddUserMessage("Flashing this file could render your PCM unusable."); return; } needToCheckOperatingSystem = false; } } await this.Vehicle.SuppressChatter(); if (needUnlock) { bool unlocked = await this.Vehicle.UnlockEcu(keyAlgorithm); if (!unlocked) { this.AddUserMessage("Unlock was not successful."); return; } this.AddUserMessage("Unlock succeeded."); } DateTime start = DateTime.Now; CKernelWriter writer = new CKernelWriter( this.Vehicle, new Protocol(), this); await writer.Write( image, writeType, kernelVersion, validator, needToCheckOperatingSystem, this.cancellationTokenSource.Token); this.AddUserMessage("Elapsed time " + DateTime.Now.Subtract(start)); } catch (IOException exception) { this.AddUserMessage(exception.ToString()); } finally { this.currentWriteType = WriteType.None; this.Invoke((MethodInvoker) delegate() { this.EnableUserInput(); this.cancelButton.Enabled = false; }); // The token / token-source can only be cancelled once, so we need to make sure they won't be re-used. this.cancellationTokenSource = null; } } }
public void ScretchLine(string Line, WriteType Type) { using (TextWriter Writer = this.Writer) { lock (Writer) { string Format = string.Format(" [{0}] {1} {2}", DateTime.Now.ToShortTimeString(), GetCharForLine(Type), Line); Writer.WriteLine(Format); BrickEngine.GetMemoryWriter().ImportLine(Format); } } PaintLogger.Clear(); }
/// <summary> /// Create an PutRawOperationTo object /// </summary> /// <returns></returns> public static Dev2PutRawOperationTO CreatePutRawOperationTO(WriteType writeType, string contents) { return new Dev2PutRawOperationTO(writeType, contents); }
public static Dev2PutRawOperationTO CreatePutRawOperationTO(WriteType writeType, string contents, bool fileContentsAsBase64 = false) => new Dev2PutRawOperationTO(writeType, contents, fileContentsAsBase64);
public static void Write(WriteType type, string message, params object[] args) { message = message.Replace("{","{{").Replace("}","}}"); var template = string.Format(" \t{0}:->{1} \t\t \t", type, message); Console.WriteLine(string.Format(template, args)); }
/// <summary> /// Write changes to the PCM's flash memory, or just test writing (Without /// making changes) to evaluate the connection quality. /// </summary> public async Task <bool> Write( byte[] image, WriteType writeType, UInt32 kernelVersion, FileValidator validator, bool needToCheckOperatingSystem, CancellationToken cancellationToken) { bool success = false; try { await this.vehicle.SendToolPresentNotification(); this.vehicle.ClearDeviceMessageQueue(); // TODO: install newer version if available. if (kernelVersion == 0) { // switch to 4x, if possible. But continue either way. // if the vehicle bus switches but the device does not, the bus will need to time out to revert back to 1x, and the next steps will fail. if (!await this.vehicle.VehicleSetVPW4x(VpwSpeed.FourX)) { this.logger.AddUserMessage("Stopping here because we were unable to switch to 4X."); return(false); } Response <byte[]> response = await this.vehicle.LoadKernelFromFile("write-kernel.bin"); if (response.Status != ResponseStatus.Success) { logger.AddUserMessage("Failed to load kernel from file."); return(false); } if (cancellationToken.IsCancellationRequested) { return(false); } // TODO: instead of this hard-coded address, get the base address from the PcmInfo object. if (!await this.vehicle.PCMExecute(response.Value, 0xFF8000, cancellationToken)) { logger.AddUserMessage("Failed to upload kernel to PCM"); return(false); } logger.AddUserMessage("Kernel uploaded to PCM succesfully."); } if (needToCheckOperatingSystem) { if (!await this.vehicle.IsSameOperatingSystemAccordingToKernel(validator, cancellationToken)) { this.logger.AddUserMessage("Flashing this file could render your PCM unusable."); return(false); } } success = await this.Write(cancellationToken, image, writeType); // We only do cleanup after a successful write. // If the kernel remains running, the user can try to flash again without rebooting and reloading. // TODO: kernel version should be stored at a fixed location in the bin file. // TODO: app should check kernel version (not just "is present") and reload only if version is lower than version in kernel file. if (success) { await this.vehicle.Cleanup(); } return(success); } catch (Exception exception) { if (!success) { switch (writeType) { case WriteType.None: case WriteType.Compare: case WriteType.TestWrite: await this.vehicle.Cleanup(); this.logger.AddUserMessage("Something has gone wrong. Please report this error."); this.logger.AddUserMessage("Errors during comparisons or test writes indicate a"); this.logger.AddUserMessage("problem with the PCM, interface, cable, or app. Don't"); this.logger.AddUserMessage("try to do any actual writing until you are certain that"); this.logger.AddUserMessage("the underlying problem has been completely corrected."); break; default: this.logger.AddUserMessage("Something went wrong. " + exception.Message); this.logger.AddUserMessage("Do not power off the PCM! Do not exit this program!"); this.logger.AddUserMessage("Try flashing again. If errors continue, seek help online."); break; } this.logger.AddUserMessage("https://pcmhacking.net/forums/viewtopic.php?f=42&t=6080"); this.logger.AddUserMessage(string.Empty); this.logger.AddUserMessage(exception.ToString()); } return(success); } }
/// <summary> /// Write the calibration blocks. /// </summary> private async Task <bool> Write(CancellationToken cancellationToken, byte[] image, WriteType writeType) { await this.vehicle.SendToolPresentNotification(); BlockType relevantBlocks; switch (writeType) { case WriteType.Compare: relevantBlocks = BlockType.All; break; case WriteType.TestWrite: relevantBlocks = BlockType.Calibration; break; case WriteType.Calibration: relevantBlocks = BlockType.Calibration; break; case WriteType.Parameters: relevantBlocks = BlockType.Parameter; break; case WriteType.OsAndCalibration: relevantBlocks = BlockType.Calibration | BlockType.OperatingSystem; break; case WriteType.Full: // Overwriting parameter blocks would break the EBCM pairing, // which is not what most users want. They just want a new OS // and the calibration to go along with it. // // The cast seems redundant, but C# converts the enum values // to ints when it does arithmetic. relevantBlocks = (BlockType)(BlockType.All - BlockType.Parameter); break; default: throw new InvalidDataException("Unsuppported operation type: " + writeType.ToString()); } // Which flash chip? await this.vehicle.SendToolPresentNotification(); await this.vehicle.SetDeviceTimeout(TimeoutScenario.ReadProperty); Query <UInt32> chipIdQuery = this.vehicle.CreateQuery <UInt32>( this.protocol.CreateFlashMemoryTypeQuery, this.protocol.ParseFlashMemoryType, cancellationToken); Response <UInt32> chipIdResponse = await chipIdQuery.Execute(); if (chipIdResponse.Status != ResponseStatus.Success) { logger.AddUserMessage("Unable to determine which flash chip is in this PCM"); return(false); } // TODO: Move the device types lookup to a function in Misc/FlashChips.cs // known chips in the P01 and P59 // http://ftp1.digi.com/support/documentation/jtag_v410_flashes.pdf string Amd = "AMD"; // 0001 string Intel = "Intel"; // 0089 string I4471 = "28F400B5-B 512Kb"; // 4471 string A2258 = "Am29F800B 1Mbyte"; // 2258 string I889D = "28F800B5-B 1Mbyte"; // 889D string unknown = "unknown"; // default case logger.AddUserMessage("Flash memory ID code: " + chipIdResponse.Value.ToString("X8")); switch ((chipIdResponse.Value >> 16)) { case 0x0001: logger.AddUserMessage("Flash memory manufactuer: " + Amd); break; case 0x0089: logger.AddUserMessage("Flash memory manufactuer: " + Intel); break; default: logger.AddUserMessage("Flash memory manufactuer: " + unknown); break; } switch (chipIdResponse.Value & 0xFFFF) { case 0x4471: logger.AddUserMessage("Flash memory type: " + I4471); break; case 0x2258: logger.AddUserMessage("Flash memory type: " + A2258); break; case 0x889D: logger.AddUserMessage("Flash memory type: " + I889D); break; default: logger.AddUserMessage("Flash memory type: " + unknown); break; } await this.vehicle.SendToolPresentNotification(); IList <MemoryRange> ranges = FlashChips.GetMemoryRanges(chipIdResponse.Value, this.logger); if (ranges == null) { return(false); } CKernelVerifier verifier = new CKernelVerifier( image, ranges, this.vehicle, this.protocol, this.logger); bool allRangesMatch = false; bool writeAttempted = false; for (int attempt = 1; attempt <= 5; attempt++) { if (await verifier.CompareRanges( ranges, image, relevantBlocks, cancellationToken)) { allRangesMatch = true; // Don't stop here if the user just wants to test their cable. if (writeType == WriteType.TestWrite) { if (attempt == 1) { this.logger.AddUserMessage("Beginning test."); } } else { this.logger.AddUserMessage("All ranges are identical."); return(true); } } if ((writeType == WriteType.TestWrite) && (attempt > 1)) { // TODO: the app should know if any errors were encountered. The user shouldn't need to check. this.logger.AddUserMessage("Test complete. Were any errors logged above?"); return(true); } // Stop now if the user only requested a comparison. if (writeType == WriteType.Compare) { this.logger.AddUserMessage("Note that mismatched Parameter blocks are to be expected."); this.logger.AddUserMessage("Parameter data can change every time the PCM is used."); return(true); } writeAttempted = true; // Erase and rewrite the required memory ranges. await this.vehicle.SetDeviceTimeout(TimeoutScenario.Maximum); foreach (MemoryRange range in ranges) { // We'll send a tool-present message during the erase request. if ((range.ActualCrc == range.DesiredCrc) && (writeType != WriteType.TestWrite)) { continue; } if ((range.Type & relevantBlocks) == 0) { continue; } this.logger.AddUserMessage( string.Format( "Processing range {0:X6}-{1:X6}", range.Address, range.Address + (range.Size - 1))); if (writeType == WriteType.TestWrite) { this.logger.AddUserMessage("Pretending to erase."); } else { if (!await this.EraseMemoryRange(range, cancellationToken)) { return(false); } } if (writeType == WriteType.TestWrite) { this.logger.AddUserMessage("Pretending to write..."); } else { this.logger.AddUserMessage("Writing..."); } await this.vehicle.SendToolPresentNotification(); await WriteMemoryRange( range, image, writeType == WriteType.TestWrite, cancellationToken); } } if (!writeAttempted) { this.logger.AddUserMessage("Assertion failed. WriteAttempted should be true."); } if (allRangesMatch) { this.logger.AddUserMessage("Flash successful!"); return(true); } this.logger.AddUserMessage("==============================================="); this.logger.AddUserMessage("THE CHANGES WERE -NOT- WRITTEN SUCCESSFULLY"); this.logger.AddUserMessage("==============================================="); if (writeType == WriteType.Calibration) { this.logger.AddUserMessage("Erasing Calibration to force recovery mode."); this.logger.AddUserMessage(""); foreach (MemoryRange range in ranges) { if (range.Type == BlockType.Calibration) { await this.EraseMemoryRange(range, cancellationToken); } } } if (cancellationToken.IsCancellationRequested) { this.logger.AddUserMessage(""); this.logger.AddUserMessage("The operation was cancelled."); this.logger.AddUserMessage("This PCM is probably not usable in its current state."); this.logger.AddUserMessage(""); } else { this.logger.AddUserMessage("This may indicate a hardware problem on the PCM."); this.logger.AddUserMessage("We tried, and re-tried, and it still didn't work."); this.logger.AddUserMessage(""); this.logger.AddUserMessage("Please start a new thread at pcmhacking.net, and"); this.logger.AddUserMessage("include the contents of the debug tab."); this.RequestDebugLogs(cancellationToken); } return(false); }
public async Task WriteTests(int[][] writes, WriteType writeType) { await RunClientServer( async clientConnection => { await using QuicStream stream = clientConnection.OpenUnidirectionalStream(); foreach (int[] bufferLengths in writes) { switch (writeType) { case WriteType.SingleBuffer: foreach (int bufferLength in bufferLengths) { await stream.WriteAsync(new byte[bufferLength]); } break; case WriteType.GatheredBuffers: var buffers = bufferLengths .Select(bufferLength => new ReadOnlyMemory <byte>(new byte[bufferLength])) .ToArray(); await stream.WriteAsync(buffers); break; case WriteType.GatheredSequence: var firstSegment = new BufferSegment(new byte[bufferLengths[0]]); BufferSegment lastSegment = firstSegment; foreach (int bufferLength in bufferLengths.Skip(1)) { lastSegment = lastSegment.Append(new byte[bufferLength]); } var buffer = new ReadOnlySequence <byte>(firstSegment, 0, lastSegment, lastSegment.Memory.Length); await stream.WriteAsync(buffer); break; default: Debug.Fail("Unknown write type."); break; } } stream.Shutdown(); await stream.ShutdownCompleted(); }, async serverConnection => { await using QuicStream stream = await serverConnection.AcceptStreamAsync(); var buffer = new byte[4096]; int receivedBytes = 0, totalBytes = 0; while ((receivedBytes = await stream.ReadAsync(buffer)) != 0) { totalBytes += receivedBytes; } int expectedTotalBytes = writes.SelectMany(x => x).Sum(); Assert.Equal(expectedTotalBytes, totalBytes); stream.Shutdown(); await stream.ShutdownCompleted(); }); }
public static void WriteLine(WriteType writeType, string @out, params object[] args) { SetConsoleColorFromType(writeType); SysCon.WriteLine(@out, args); SetConsoleColorFromType(); }