protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, RolandMidiClient client) { using (var device = new DeviceController(client)) { return(await InvokeAsync(context, console, device)); } }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device) { var kitNumber = context.ParseResult.ValueForOption <int>("kit"); var file = context.ParseResult.ValueForOption <string>("file"); try { Stopwatch sw = Stopwatch.StartNew(); // Allow up to 30 seconds in total. var token = new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token; var kit = await device.LoadKitAsync(kitNumber, null, token); console.WriteLine($"Finished loading in {(int) sw.Elapsed.TotalSeconds} seconds"); using (var stream = File.Create(file)) { kit.Save(stream); } console.WriteLine($"Saved kit to {file}"); } catch (OperationCanceledException) { console.WriteLine("Data loading from device was cancelled"); return(1); } catch (Exception ex) { console.WriteLine($"Error loading data from device: {ex}"); return(1); } return(0); }
public void SetErrorInstruction(string message, NotificationErrorType notificationErrorType) { IStandardStreamWriter errorWriter = _console.Error; switch (notificationErrorType) { case NotificationErrorType.Error: Environment.ExitCode = CLIConsts.ExistErrorCode; _console.ForegroundColor = ConsoleColor.DarkRed; break; case NotificationErrorType.Attention: _console.ForegroundColor = ConsoleColor.DarkBlue; break; case NotificationErrorType.None: default: throw new Exception($"Invalid NotificationErrorType '{notificationErrorType}'"); } errorWriter.WriteLine(message); _console.ForegroundColor = ConsoleColor.White; }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, RolandMidiClient client) { var schema = ModuleSchema.KnownSchemas[ModuleIdentifier.AE10].Value; var instrumentField = schema.PhysicalRoot.ResolveField("TemporaryStudioSet/Part[1]/Instrument"); var instrumentDataField = new EnumDataField((EnumField)instrumentField); var deviceController = new DeviceController(client, new ConsoleLogger(console)); var temporaryKitRoot = schema.LogicalRoot.ResolveNode("TemporaryStudioSet"); // First 100 presets client.SendData(0x01_00_00_05, new byte[] { 64 }); for (int i = 1; i <= 100; i++) { console.WriteLine($"Copying studio set {i}"); client.SendData(0x01_00_00_06, new byte[] { (byte)((i - 1) & 0x7f) }); await Task.Delay(40); var data = ModuleData.FromLogicalRootNode(temporaryKitRoot); await deviceController.LoadDescendants(data.LogicalRoot, null, progressHandler : null, cancellationToken : default); await deviceController.SaveDescendants(data.LogicalRoot, schema.GetKitRoot(i).Container.Address, progressHandler : null, cancellationToken : default); } return(0); }
protected ContentRenderingSpanVisitor( IStandardStreamWriter writer, Region region) { Writer = writer ?? throw new ArgumentNullException(nameof(writer)); Region = region ?? throw new ArgumentNullException(nameof(region)); }
private static void ClearCurrent(StringBuilder sb, IStandardStreamWriter consoleOut) { if (sb.Length > 0) { consoleOut.Write(Enumerable.Repeat("\b \b", sb.Length).ToCsv("")); sb.Length = 0; } }
public void Write(string value) { foreach (var console in _consoles) { IStandardStreamWriter writer = _error ? console.Error : console.Out; writer.WriteLine(value.TrimEnd('\r', '\n')); } }
/// <summary> /// Creates a <see cref="TextWriter"/> that writes to the specified <see cref="IStandardStreamWriter"/>. /// </summary> public static TextWriter CreateTextWriter(this IStandardStreamWriter writer) { if (writer is null) { throw new ArgumentNullException(nameof(writer)); } return(new TextWriterThatWritesToStandardStreamWriter(writer)); }
/// <summary> /// Writes the current string value, followed by the current environment's line terminator. /// </summary> /// <param name="writer">The writer to write to.</param> /// <param name="value">The value to write.</param> public static void WriteLine(this IStandardStreamWriter writer, string value) { if (writer is null) { throw new ArgumentNullException(nameof(writer)); } writer.Write(value + Environment.NewLine); }
public static TextWriter Create(IStandardStreamWriter writer) { if (writer is null) { throw new ArgumentNullException(nameof(writer)); } return(new AnonymousTextWriter(writer)); }
public static void WriteLine(this IStandardStreamWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } writer.Write(NewLine); }
public static void VerboseWrite(this IStandardStreamWriter writer, string value = "") { if (!Globals.Verbose) { return; } writer.Write(value); }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, RolandMidiClient client) { var schema = ModuleSchema.KnownSchemas[ModuleIdentifier.AE10].Value; var instrumentField = schema.PhysicalRoot.ResolveField("TemporaryStudioSet/Part[1]/Instrument"); var instrumentDataField = new EnumDataField((EnumField)instrumentField); // Presets client.SendData(0x01_00_00_05, new byte[] { 64 }); for (int i = 1; i <= 128; i++) { await ShowStudioSet('P', i); } // Preset 129 is in a different bank... client.SendData(0x01_00_00_05, new byte[] { 65 }); for (int i = 129; i <= 129; i++) { await ShowStudioSet('P', i); } // User sets client.SendData(0x01_00_00_05, new byte[] { 0 }); for (int i = 1; i <= 100; i++) { await ShowStudioSet('U', i); } async Task ShowStudioSet(char prefix, int index) { client.SendData(0x01_00_00_06, new byte[] { (byte)((index - 1) & 0x7f) }); await Task.Delay(50); var common = await client.RequestDataAsync(0x18_00_00_00, 16, CancellationToken.None); string name = Encoding.UTF8.GetString(common); console.WriteLine($"{prefix}:{index:D3}: {name}"); for (int partIndex = 0; partIndex < 4; partIndex++) { var part = await client.RequestDataAsync(0x18_00_20_00 + partIndex * 0x1_00, 9, CancellationToken.None); if (part[1] != 1) { continue; } // The address doesn't matter, as only the offset is passed. var segment = new DataSegment(ModuleAddress.FromDisplayValue(0), part); instrumentDataField.Load(segment); console.WriteLine($"Part {partIndex + 1}: {instrumentDataField.Value}"); } console.WriteLine(); } return(0); }
public static void ReportProgress(this IStandardStreamWriter writer, int percentage) { var mode = 1; if (percentage is 100) { mode = 0; } writer.Write($"\x1B]9;4;{mode};{percentage}\x1B\\"); }
public void SetErrorMessage(string message) { Environment.ExitCode = CLIConsts.ExistErrorCode; IStandardStreamWriter errorWriter = _console.Error; _console.ForegroundColor = ConsoleColor.Red; errorWriter.WriteLine(message); _console.ForegroundColor = ConsoleColor.White; }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device) { var schema = device.Schema; for (int i = 1; i <= schema.Kits; i++) { var name = await device.LoadKitNameAsync(i, CancellationToken.None); console.WriteLine($"Kit {i}: {name}"); } return(0); }
internal static void WriteLine(this IStandardStreamWriter writer, string?value, bool avoidExtraNewLine) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } writer.Write(value); if (!avoidExtraNewLine || (!value?.EndsWith(NewLine) ?? false)) { writer.Write(NewLine); } }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, RolandMidiClient client) { var address = ModuleAddress.FromDisplayValue(HexInt32.Parse(context.ParseResult.ValueForOption <string>("address")).Value); var size = HexInt32.Parse(context.ParseResult.ValueForOption <string>("size")).Value; var timeout = context.ParseResult.ValueForOption <int>("timeout"); // Wait up to 10 seconds to receive all the requested data... int sizeReceived = 0; var delayTask = Task.Delay(TimeSpan.FromSeconds(timeout)); var completeTaskCts = new TaskCompletionSource <int>(); client.DataSetMessageReceived += DumpMessage; client.SendDataRequestMessage(address.DisplayValue, size); await Task.WhenAny(delayTask, completeTaskCts.Task); return(0); void DumpMessage(object sender, DataSetMessage message) { ModuleAddress address = ModuleAddress.FromDisplayValue(message.Address); console.WriteLine($"Address: {address} Length: {message.Length:x4}"); int index = 0; while (index < message.Length) { var builder = new StringBuilder(); var textBuilder = new StringBuilder(); builder.Append(address); builder.Append(" "); for (int i = 0; i < 16 && index < message.Length; i++) { byte b = message.Data[index]; textBuilder.Append(b >= 32 && b < 127 ? (char)b : ' '); builder.Append(b.ToString("x2")); builder.Append(" "); index++; } string text = builder.ToString().PadRight(9 + 16 * 3) + textBuilder; console.WriteLine(text); address = address.PlusLogicalOffset(16); } console.WriteLine(); if (Interlocked.Add(ref sizeReceived, message.Length) >= size) { completeTaskCts.SetResult(0); } } }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, RolandMidiClient client) { using (var device = new DeviceController(client)) { var schema = device.Schema; var channel = context.ParseResult.ValueForOption <int>("channel"); var keys = context.ParseResult.ValueForOption <string>("keys"); var targetKit = context.ParseResult.ValueForOption <int>("kit"); if (targetKit < 1 || targetKit + 1 > schema.Kits) { console.WriteLine($"Kit {targetKit} is out of range for {schema.Identifier.Name} for this command."); console.WriteLine("Note that one extra kit is required after the specified one."); return(1); } // Detect the current kit var currentKit = await device.GetCurrentKitAsync(CancellationToken.None); // Copy current kit to target kit and target kit + 1 var kit = await device.LoadKitAsync(currentKit, progressHandler : null, CreateCancellationToken()); var dataNode = new DataTreeNode(kit.Data, kit.KitRoot); await device.SaveDescendants(dataNode, schema.GetKitRoot(targetKit).Container.Address, progressHandler : null, CreateCancellationToken()); await device.SaveDescendants(dataNode, schema.GetKitRoot(targetKit + 1).Container.Address, progressHandler : null, CreateCancellationToken()); await device.SetCurrentKitAsync(targetKit, CancellationToken.None); var programChangeCommand = (byte)(0xc0 | (channel - 1)); // Now listen for the foot switch... client.MessageReceived += async(sender, message) => { if (message.Data.Length == 2 && message.Data[0] == programChangeCommand) { console.WriteLine("Turning the page..."); SendKeysUtilities.SendWait(keys); await device.SetCurrentKitAsync(targetKit, CancellationToken.None); } }; console.WriteLine("Listening for foot switch"); await Task.Delay(TimeSpan.FromHours(1)); } return(0); CancellationToken CreateCancellationToken() => new CancellationTokenSource(10000).Token; }
private static void WriteLine(this IConsole console, IStandardStreamWriter writer, string message, ConsoleColor?color) { lock (_writeLock) { if (color.HasValue) { console.SetTerminalForeground(color.Value); } writer.WriteLine(message); if (color.HasValue) { console.ResetColor(); } } }
private static void WriteMessage(this IConsole console, IStandardStreamWriter writer, ConsoleColor color, string messsage) { var terminal = console.GetTerminal(preferVirtualTerminal: false); var originalForegroundColor = terminal?.ForegroundColor ?? Console.ForegroundColor; if (terminal is not null) { terminal.ForegroundColor = color; } writer.WriteLine(messsage); if (terminal is not null) { terminal.ForegroundColor = originalForegroundColor; } }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device) { var path = context.ParseResult.ValueForOption <string>("path"); bool interpret = context.ParseResult.ValueForOption <bool>("interpret"); var root = device.Schema.LogicalRoot.ResolveNode(path); var container = (FieldContainer)root.Container; var segment = await device.LoadSegment(container.Address, container.Size, default); foreach (var field in container.Fields) { var bytes = new byte[field.Size]; segment.ReadBytes(field.Offset, bytes.AsSpan()); if (field is OverlayField overlay) { var sizePerNestedField = field.Size / overlay.NestedFieldCount; for (int i = 0; i < overlay.NestedFieldCount; i++) { string description = $"{field.Description} {i + 1}"; var nestedBytes = bytes[(i * sizePerNestedField)..((i + 1) * sizePerNestedField)];
public CustomConsole(IStandardStreamWriter stdOut = null, IStandardStreamWriter stdError = null) { if (stdOut != null) { Out = stdOut; } else { Out = StandardStreamWriter.Create(Console.Out); } if (stdError != null) { Error = stdError; } else { Error = StandardStreamWriter.Create(Console.Error); } }
private static void LogException(IStandardStreamWriter output, Logger logger, Exception error) { logger.Error(error.Message); output.WriteLine(error.Message); if (error.StackTrace != null) { logger.Error(error.StackTrace); output.WriteLine(error.StackTrace); } if (error.InnerException == null) { return; } logger.Error("==Inner Exception=="); output.WriteLine("==Inner Exception=="); LogException(output, logger, error.InnerException); logger.Error("==End Inner Exception=="); output.WriteLine("==End Inner Exception=="); }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, RolandMidiClient client) { var channel = context.ParseResult.ValueForOption <int>("channel"); var keys = context.ParseResult.ValueForOption <string>("keys"); var midiNote = context.ParseResult.ValueForOption <int>("note"); var noteOn = (byte)(0x90 | (channel - 1)); // Now listen for the foot switch... client.MessageReceived += (sender, message) => { if (message.Data.Length == 3 && message.Data[0] == noteOn && message.Data[1] == midiNote) { console.WriteLine("Turning the page..."); SendKeysUtilities.SendWait(keys); } }; console.WriteLine("Listening for MIDI note"); await Task.Delay(TimeSpan.FromHours(1)); return(0); }
private static void OnException(Exception ex, InvocationContext context) { IStandardStreamWriter err = context.Console.Error; switch (ex) { case AggregateException aex: aex.Handle(x => { err.WriteLine($"fatal: {x.Message}"); return(true); }); break; case Win32Exception wex: err.WriteLine($"fatal: {wex.Message} [0x{wex.NativeErrorCode:x}]"); break; default: err.WriteLine($"fatal: {ex.Message}"); break; } }
public FileRenderingSpanVisitor(IStandardStreamWriter writer, Region region) : base(writer, region) { }
internal static void WriteLine(this IStandardStreamWriter streamWriter, string message) { streamWriter.Write(message); streamWriter.WriteLine(); }
internal static void WriteLine(this IStandardStreamWriter streamWriter) { streamWriter.Write(Environment.NewLine); }
public static void Write(this IStandardStreamWriter writer, object?value) { writer.Write(value?.ToString()); }