static async Task TestFileManagerCommands() { var meadow = await MeadowDeviceManager.GetMeadowForSerialPort("COM3"); // request rejected; unknown command //Console.WriteLine("CreateFileSystem"); //await MeadowFileManager.CreateFileSystem(meadow); Console.WriteLine("WriteFileToFlash"); File.WriteAllText(".\\hello_meadow.txt", "test"); await MeadowFileManager.WriteFileToFlash(meadow, @".\\hello_meadow.txt"); // MonoUpdateRt, PartitionFileSystem, MountFileSystem, InitializeFileSystem, CreateFileSystem, FormatFileSystem - do we still need these? Console.WriteLine("ListFiles"); await MeadowFileManager.ListFiles(meadow); Console.WriteLine("ListFilesAndCrcs"); await MeadowFileManager.ListFilesAndCrcs(meadow); Console.WriteLine("DeleteFile"); await MeadowFileManager.DeleteFile(meadow, @"hello_meadow.txt"); Console.WriteLine("ListFiles"); await MeadowFileManager.ListFiles(meadow); //await MeadowFileManager.EraseFlash(meadow); //await MeadowFileManager.VerifyErasedFlash(meadow); }
public override async ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); using var device = await MeadowDeviceManager.GetMeadowForSerialPort(SerialPortName, true, cancellationToken).ConfigureAwait(false); await device.MonoDisable(cancellationToken).ConfigureAwait(false); }
public override async ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); _logger.LogInformation("Verifying flash"); using var device = await MeadowDeviceManager.GetMeadowForSerialPort(SerialPortName, true, cancellationToken).ConfigureAwait(false); await device.VerifyErasedFlash(cancellationToken).ConfigureAwait(false); }
public override async ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); await console.Output.WriteLineAsync("Renewing file system on the Meadow."); using var device = await MeadowDeviceManager.GetMeadowForSerialPort(SerialPortName, true, cancellationToken) .ConfigureAwait(false); await device.RenewFileSystem(cancellationToken : cancellationToken).ConfigureAwait(false); }
static async Task GetFilesAndCrcs() { var meadow = await MeadowDeviceManager.GetMeadowForSerialPort("/dev/tty.usbmodem01"); // MeadowDeviceManager.MonoDisable(meadow); await meadow.SetDeviceInfo(); // var (files, crcs) = await meadow.GetFilesAndCrcs(); // var fileList = await meadow.GetFilesOnDevice(); // Console.WriteLine("File list received"); }
private async Task UpdateTargetsList(CancellationToken ct) { var serialPorts = MeadowDeviceManager.FindSerialDevices(); foreach (var port in serialPorts) { if (ct.IsCancellationRequested) { break; } if (Targets.Any(t => t.meadowSerialDevice.connection?.USB?.DevicePort == port)) { continue; } var timeout = Task <MeadowDevice> .Delay(1000); var meadowTask = MeadowDeviceManager.GetMeadowForSerialPort(port); await Task.WhenAny(timeout, meadowTask); var meadow = meadowTask.Result; if (meadow != null) { //we should really just have the execution target own an instance of MeadowDevice Targets.Add(new MeadowDeviceExecutionTarget(meadow)); //meadow.CloseConnection(); DeviceListChanged?.Invoke(null); meadow.StatusChange += StatusDisplay; } } var removeList = new List <MeadowDeviceExecutionTarget>(); foreach (var t in Targets) { if (serialPorts.Any(p => p == t.meadowSerialDevice.connection?.USB?.DevicePort) == false) { removeList.Add(t); } } foreach (var r in removeList) { r.meadowSerialDevice.StatusChange -= StatusDisplay; Targets.Remove(r); DeviceListChanged?.Invoke(null); } }
private async void Check_Version(object sender, RoutedEventArgs e) { try { if (IsDfuMode()) { await OutputMessageAsync($"Device is in bootloader mode. Connect device in normal mode to check version.", true); return; } EnableControls(false); MeadowSettings settings = new MeadowSettings(Globals.SettingsFilePath); await OutputMessageAsync($"Initialize device (~30s)", true); if (string.IsNullOrEmpty(settings.DeviceTarget)) { await OutputMessageAsync($"Select Target Device Port and click '{Flash_Device_Text}' to resume."); _skipFlashToSelectDevice = true; EnableControls(true); return; } MeadowSerialDevice meadow = null; // initialize connection. need to jump through hoops after exiting dfu mode =( meadow = await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget).ConfigureAwait(false); await MeadowDeviceManager.ResetMeadow(meadow).ConfigureAwait(false); await Task.Delay(1000); meadow = await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget).ConfigureAwait(false); await MeadowDeviceManager.GetDeviceInfo(meadow); await OutputMessageAsync($"Device {meadow.DeviceInfo.MeadowOSVersion}", true); } catch (Exception ex) { await OutputMessageAsync($"Could not read device version."); } finally { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); EnableControls(true); } }
public async Task MonoEnableTest() { var cts = new CancellationTokenSource(); using var meadow = await MeadowDeviceManager.GetMeadowForSerialPort(port, logger : NullLogger.Instance).ConfigureAwait(false); Assert.IsNotNull(meadow, "Initial connection"); await meadow.MonoEnableAsync(cts.Token); var monoEnabled = await meadow.GetMonoRunStateAsync(cts.Token); Assert.True(monoEnabled, "monoEnabled"); }
public override async ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); using var device = await MeadowDeviceManager .GetMeadowForSerialPort( SerialPortName, true, cancellationToken) .ConfigureAwait(false); var runState = await device.GetMonoRunState(cancellationToken) .ConfigureAwait(false); _logger.LogInformation($"Mono Run State: {(runState ? "Enabled" : "Disabled")}"); }
public override async ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); using var device = await MeadowDeviceManager .GetMeadowForSerialPort( SerialPortName, true, cancellationToken) .ConfigureAwait(false); var deviceName = await device.GetDeviceName(cancellationToken : cancellationToken) .ConfigureAwait(false); _logger.LogInformation($"Device Name: {deviceName}"); }
public override async ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); using var device = await MeadowDeviceManager.GetMeadowForSerialPort(SerialPortName, true, cancellationToken).ConfigureAwait(false); var deviceInfoString = await device.GetDeviceInfo(cancellationToken : cancellationToken).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(deviceInfoString)) { throw new Exception("Unable to retrieve device info"); } var deviceInfo = new MeadowDeviceInfo(deviceInfoString); _logger.LogInformation(deviceInfo.ToString()); }
static async Task TestFlashCommands() { Stopwatch sw = new Stopwatch(); string networkBootloaderFilename = "bootloader.bin"; string networkMeadowCommsFilename = "MeadowComms.bin"; string networkPartitionTableFilename = "partition-table.bin"; var meadow = await MeadowDeviceManager.GetMeadowForSerialPort("COM3"); //MeadowSerialDevice meadow = null; for (int i = 0; i < 20; i++) { //meadow = await MeadowDeviceManager.GetMeadowForSerialPort("COM3"); Console.WriteLine("disable"); await MeadowDeviceManager.MonoDisable(meadow); Thread.Sleep(11000); //meadow = await MeadowDeviceManager.GetMeadowForSerialPort("COM3"); Console.WriteLine("enable"); await MeadowDeviceManager.MonoEnable(meadow); Thread.Sleep(11000); } ////await MeadowFileManager.MonoUpdateRt(meadow, @"C:\Users\brikim\AppData\Local\WildernessLabs\Firmware\Meadow.OS.Runtime.bin"); //Console.WriteLine("write runtime"); //await MeadowFileManager.WriteFileToFlash(meadow, @"C:\Users\brikim\AppData\Local\WildernessLabs\Firmware\Meadow.OS.Runtime.bin"); //Console.WriteLine("mono flash"); //sw.Start(); //await MeadowDeviceManager.MonoFlash(meadow); // does not emit `Concluded` //Console.WriteLine($"elapsed: {sw.Elapsed.TotalSeconds}"); //Console.WriteLine($"flash esp: {networkBootloaderFilename}"); //await MeadowFileManager.WriteFileToEspFlash(MeadowDeviceManager.CurrentDevice, Path.Combine(@"C:\Users\brikim\AppData\Local\WildernessLabs\Firmware", networkBootloaderFilename), mcuDestAddr: "0x1000"); //Console.WriteLine($"flash esp: {networkPartitionTableFilename}"); //await MeadowFileManager.WriteFileToEspFlash(MeadowDeviceManager.CurrentDevice, Path.Combine(@"C:\Users\brikim\AppData\Local\WildernessLabs\Firmware", networkPartitionTableFilename), mcuDestAddr: "0x8000"); //Console.WriteLine($"flash esp: {networkMeadowCommsFilename}"); //await MeadowFileManager.WriteFileToEspFlash(MeadowDeviceManager.CurrentDevice, Path.Combine(@"C:\Users\brikim\AppData\Local\WildernessLabs\Firmware", networkMeadowCommsFilename), mcuDestAddr: "0x10000"); }
async Task DeployAppAsync(string target, string folder, IOutputPaneWriter outputPaneWriter, CancellationToken cts) { Stopwatch sw = Stopwatch.StartNew(); await outputPaneWriter.WriteAsync($"Deploying to Meadow on {target}..."); try { var meadow = await MeadowDeviceManager.GetMeadowForSerialPort(target).ConfigureAwait(false); if (meadow == null) { await outputPaneWriter.WriteAsync($"Device connection error, please disconnect device and try again."); return; } await MeadowDeviceManager.ResetMeadow(meadow).ConfigureAwait(false); await Task.Delay(1000); meadow = await MeadowDeviceManager.GetMeadowForSerialPort(target).ConfigureAwait(false); await Task.Delay(1000); await MeadowDeviceManager.MonoDisable(meadow).ConfigureAwait(false); var meadowFiles = await GetFilesOnDevice(meadow, outputPaneWriter, cts).ConfigureAwait(false); var localFiles = await GetLocalFiles(outputPaneWriter, cts, folder).ConfigureAwait(false); await DeleteUnusedFiles(meadow, outputPaneWriter, cts, meadowFiles, localFiles).ConfigureAwait(false); await DeployApp(meadow, outputPaneWriter, cts, folder, meadowFiles, localFiles).ConfigureAwait(false); await MeadowDeviceManager.MonoEnable(meadow).ConfigureAwait(false); } catch (Exception ex) { throw ex; } sw.Stop(); await outputPaneWriter.WriteAsync($"Deployment Duration: {sw.Elapsed}"); }
public async Task FlashOSTest() { //DfuUpload.FlashOS(Path.Combine(fixturesPath.FullName, osFilename)); using (var meadow = await MeadowDeviceManager.GetMeadowForSerialPort(port)) { Assert.IsNotNull(meadow, "Initial connection"); await MeadowDeviceManager.MonoDisable(meadow); var isEnabled = await MeadowDeviceManager.MonoRunState(meadow); // try to disable one more time if (isEnabled) { await MeadowDeviceManager.MonoDisable(meadow); isEnabled = await MeadowDeviceManager.MonoRunState(meadow); } Assert.IsFalse(isEnabled, "Disable mono"); } using (var meadow = await MeadowDeviceManager.GetMeadowForSerialPort(port)) { await MeadowFileManager.MonoUpdateRt(meadow, Path.Combine(fixturesPath.FullName, runtimeFilename)); } using (var meadow = await MeadowDeviceManager.GetMeadowForSerialPort(port)) { await MeadowFileManager.FlashEsp(meadow, fixturesPath.FullName); } using (var meadow = await MeadowDeviceManager.GetMeadowForSerialPort(port)) { Assert.IsNotNull(meadow); await MeadowDeviceManager.MonoEnable(meadow); var isEnabled = await MeadowDeviceManager.MonoRunState(meadow); Assert.IsTrue(isEnabled); } }
async Task DeployAppAsync(string target, string folder, IOutputPaneWriter outputPaneWriter, CancellationToken cts) { Stopwatch sw = Stopwatch.StartNew(); await outputPaneWriter.WriteAsync($"Deploying to Meadow on {target}..."); try { var meadow = MeadowDeviceManager.CurrentDevice; if (meadow == null) { meadow = await MeadowDeviceManager.GetMeadowForSerialPort(target); } if (await InitializeMeadowDeviceAsync(meadow, outputPaneWriter, cts) == false) { throw new Exception("Failed to initialize Meadow. Try resetting or reconnecting the device."); } var meadowFiles = await GetFilesOnDevice(meadow, outputPaneWriter, cts); var localFiles = await GetLocalFiles(outputPaneWriter, cts, folder); await DeleteUnusedFiles(meadow, outputPaneWriter, cts, meadowFiles, localFiles); await DeployApp(meadow, outputPaneWriter, cts, folder, meadowFiles, localFiles); await ResetMeadowAndStartMonoAsync(meadow, outputPaneWriter, cts); } catch (Exception ex) { throw ex; } sw.Stop(); await outputPaneWriter.WriteAsync($"Deployment Duration: {sw.Elapsed}"); }
private async void Flash_ESP_Click(object sender, RoutedEventArgs e) { _verbose = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); MeadowSerialDevice meadow = null; try { MeadowSettings settings = new MeadowSettings(Globals.SettingsFilePath); await OutputMessageAsync($"Begin '{Flash_Coprocessor_Text}'", true); EnableControls(false); await OutputMessageAsync($"Initialize device (~30s)"); if (string.IsNullOrEmpty(settings.DeviceTarget)) { await OutputMessageAsync($"Select Target Device Port and click '{Flash_Device_Text}' to resume."); _skipFlashToSelectDevice = true; EnableControls(true); return; } // initialize connection. need to jump through hoops after exiting dfu mode =( meadow = await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget).ConfigureAwait(false); await MeadowDeviceManager.ResetMeadow(meadow).ConfigureAwait(false); await Task.Delay(1000); meadow = await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget).ConfigureAwait(false); if (_verbose) { await MeadowDeviceManager.TraceEnable(meadow).ConfigureAwait(false); } else { await MeadowDeviceManager.TraceDisable(meadow).ConfigureAwait(false); } meadow.OnMeadowMessage += MeadowMesageHandler; await Task.Delay(1000); await MeadowDeviceManager.MonoDisable(meadow).ConfigureAwait(false); await Task.Delay(10000); // wait for reconnect, need an event for this await MeadowFileManager.WriteFileToEspFlash(meadow, Path.Combine(Globals.FirmwareDownloadsFilePath, networkMeadowCommsFilename), mcuDestAddr : "0x10000").ConfigureAwait(false); await Task.Delay(1000); await MeadowFileManager.WriteFileToEspFlash(meadow, Path.Combine(Globals.FirmwareDownloadsFilePath, networkBootloaderFilename), mcuDestAddr : "0x1000").ConfigureAwait(false); await Task.Delay(1000); await MeadowFileManager.WriteFileToEspFlash(meadow, Path.Combine(Globals.FirmwareDownloadsFilePath, networkPartitionTableFilename), mcuDestAddr : "0x8000").ConfigureAwait(false); await Task.Delay(1000); await OutputMessageAsync($"{Flash_Coprocessor_Text} completed."); await MeadowDeviceManager.MonoEnable(meadow).ConfigureAwait(false); await Task.Delay(10000); // wait for reconnect, need an event for this } catch (Exception ex) { await OutputMessageAsync($"An unexpected error occurred. Please try again."); } finally { if (meadow != null) { meadow.OnMeadowMessage -= MeadowMesageHandler; } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); EnableControls(true); } }
private async void Flash_Device(object sender, RoutedEventArgs e) { _verbose = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); MeadowSerialDevice meadow = null; try { MeadowSettings settings = new MeadowSettings(Globals.SettingsFilePath); var(osFilePath, runtimeFilePath) = await GetWorkingFiles(); if (string.IsNullOrEmpty(osFilePath) && string.IsNullOrEmpty(runtimeFilePath)) { await OutputMessageAsync($"Meadow OS files not found. 'Download Meadow OS' first."); return; } EnableControls(false); await OutputMessageAsync($"Begin '{Flash_Device_Text}'", true); if (_verbose) { await OutputMessageAsync($"Trace output enabled."); } if (!string.IsNullOrEmpty(osFilePath)) { if (!await DfuFlash(osFilePath, osAddress).ConfigureAwait(false)) { EnableControls(true); return; } } else { await OutputMessageAsync($"{osFilename} not selected. Skipping OS flash."); } //reset skip flash flag _skipFlashToSelectDevice = false; if (!string.IsNullOrEmpty(runtimeFilePath)) { await OutputMessageAsync($"Initialize device (~30s)"); if (string.IsNullOrEmpty(settings.DeviceTarget)) { await OutputMessageAsync($"Select Target Device Port and click '{Flash_Device_Text}' to resume."); _skipFlashToSelectDevice = true; EnableControls(true); return; } // initialize connection. need to jump through hoops after exiting dfu mode =( meadow = await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget).ConfigureAwait(false); await MeadowDeviceManager.ResetMeadow(meadow).ConfigureAwait(false); await Task.Delay(1000); meadow = await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget).ConfigureAwait(false); if (_verbose) { await MeadowDeviceManager.TraceEnable(meadow).ConfigureAwait(false); } else { await MeadowDeviceManager.TraceDisable(meadow).ConfigureAwait(false); } meadow.OnMeadowMessage += MeadowMesageHandler; await Task.Delay(1000); await MeadowDeviceManager.MonoDisable(meadow).ConfigureAwait(false); await Task.Delay(10000); // wait for reconnect, need an event for this await MeadowFileManager.WriteFileToFlash(meadow, runtimeFilePath).ConfigureAwait(false); await MeadowDeviceManager.MonoFlash(meadow).ConfigureAwait(false); await meadow.DeleteFile(runtimeFilename).ConfigureAwait(false); await MeadowDeviceManager.MonoEnable(meadow).ConfigureAwait(false); await Task.Delay(10000); // wait for reconnect, need an event for this } else { await OutputMessageAsync($"{runtimeFilename} not selected. Skipping Runtime flash."); } await OutputMessageAsync($"'{Flash_Device_Text}' completed"); } catch (Exception ex) { await OutputMessageAsync($"An unexpected error occurred. Please try again."); } finally { if (meadow != null) { meadow.OnMeadowMessage -= MeadowMesageHandler; } _verbose = false; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); EnableControls(true); } }
private async void Flash_Device(object sender, RoutedEventArgs e) { try { MeadowSettings settings = new MeadowSettings(Globals.SettingsFilePath); var(osFilePath, runtimeFilePath) = await GetWorkingFiles(); if (string.IsNullOrEmpty(osFilePath) && string.IsNullOrEmpty(runtimeFilePath)) { await OutputMessageAsync($"Meadow OS files not found. 'Download Meadow OS' first."); return; } EnableControls(false); await OutputMessageAsync($"Begin '{Flash_Device_Text}'", true); if (!string.IsNullOrEmpty(osFilePath)) { if (!await DfuFlash(osFilePath, osAddress)) { EnableControls(true); return; } } else { await OutputMessageAsync($"{osFilename} not selected. Skipping OS flash."); } //reset skip flash flag _skipFlashToSelectDevice = false; if (!string.IsNullOrEmpty(runtimeFilePath)) { await OutputMessageAsync($"Initialize device"); MeadowDeviceManager.CurrentDevice = null; if (string.IsNullOrEmpty(settings.DeviceTarget)) { await OutputMessageAsync($"Select Target Device Port and click '{Flash_Device_Text}' to resume."); _skipFlashToSelectDevice = true; EnableControls(true); return; } else { await MeadowDeviceManager.GetMeadowForSerialPort(settings.DeviceTarget); } if (MeadowDeviceManager.CurrentDevice == null) { await OutputMessageAsync($"Initialization failed. Try again."); return; } if (!await Process(() => MeadowDeviceManager.ResetMeadow(MeadowDeviceManager.CurrentDevice, 0))) { return; } if (!await Process(() => MeadowDeviceManager.MonoDisable(MeadowDeviceManager.CurrentDevice))) { return; } await OutputMessageAsync($"Erase flash (~3 mins)"); if (!await Process(() => MeadowFileManager.EraseFlash(MeadowDeviceManager.CurrentDevice))) { return; } await OutputMessageAsync($"Restart device"); if (!await Process(() => MeadowDeviceManager.ResetMeadow(MeadowDeviceManager.CurrentDevice, 0))) { return; } await OutputMessageAsync($"Upload {runtimeFilename} (~1 min)"); if (!await Process(() => MeadowFileManager.WriteFileToFlash(MeadowDeviceManager.CurrentDevice, runtimeFilePath))) { return; } await OutputMessageAsync($"Process {runtimeFilename} (~30 secs)"); if (!await Process(() => MeadowDeviceManager.MonoFlash(MeadowDeviceManager.CurrentDevice))) { return; } await MeadowDeviceManager.CurrentDevice.DeleteFile(runtimeFilename); if (!await Process(() => MeadowDeviceManager.MonoEnable(MeadowDeviceManager.CurrentDevice))) { return; } await OutputMessageAsync($"Restart device"); if (!await Process(() => MeadowDeviceManager.ResetMeadow(MeadowDeviceManager.CurrentDevice, 0))) { return; } } else { await OutputMessageAsync($"{runtimeFilename} not selected. Skipping Runtime flash."); } EnableControls(true); await OutputMessageAsync($"'{Flash_Device_Text}' completed"); } catch (Exception ex) { await OutputMessageAsync($"An unexpected error occurred. Please try again."); EnableControls(true); } }
public static async Task Deploy() { var cts = new CancellationTokenSource(); logger = new OutputLogger(); try { meadow = await MeadowDeviceManager.GetMeadowForSerialPort(SerialPortName, logger : logger).ConfigureAwait(false); var meadowDH = new MeadowDeviceHelper(meadow, logger); await meadowDH.MonoDisableAsync(false, cts.Token); //meadowDH.DeployAppAsync(); var items = await meadowDH.GetFilesAndFoldersAsync(new TimeSpan(0, 0, 10), cts.Token); bool isRoot = false; bool isFolder = false; string folderName = string.Empty; var filesToDelete = new List <string>(); for (int i = 0; i < items.Count; i++) { //start of folders in root if (isRoot == false && items[i].Contains("meadow0/")) { isRoot = true; } //next root folder - break out else if (isRoot && items[i].Contains(" ") == false) { break; } //item under meadow0 else if (isRoot && items[i].Contains("/") && items[i].Contains("./") == false) { folderName = items[i].Substring(1); isFolder = true; } else if (isFolder == true && items[i].Contains(" ") && items[i].Contains("[file]")) { var end = items[i].IndexOf(" [file]"); filesToDelete.Add(Path.Combine(folderName, items[i].Substring(2, end - 2))); } else { continue; } } foreach (var item in filesToDelete) { if (item.Contains("Data/") || item.Contains("Documents/")) { continue; } Console.WriteLine($"Deleting {item}"); await meadow.DeleteFileAsync(item, 0, cts.Token); } /* * await meadowDH.DeployAppAsync("//Users//adrianstevens//Projects//Blink51Standard//Blink51Standard//bin//Debug//netstandard2.1//App.exe", * true, cts.Token); * * await meadowDH.MonoEnableAsync(cts.Token); * * meadow = meadowDH.MeadowDevice; //reference to keep alive */ } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } }
public static async Task <string> DfuFlashAsync(string serialPortName, string osPath, string?osVersion, ILogger logger, CancellationToken cancellationToken = default ) { var dfuAttempts = 0; UsbRegistry dfuDevice; while (true) { try { try { dfuDevice = DfuUtils.GetDevice(); break; } catch (MultipleDfuDevicesException) { // This is bad, we can't just blindly flash with multiple devices, let the user know throw; } catch (DeviceNotFoundException) { // eat it. } // No DFU device found, lets try to set the meadow to DFU mode. using var device = await MeadowDeviceManager.GetMeadowForSerialPort(serialPortName, false).ConfigureAwait(false); if (device != null) { logger.LogInformation("Entering DFU Mode"); await device.EnterDfuModeAsync(cancellationToken) .ConfigureAwait(false); } } catch (Exception ex) { logger.LogDebug( "An exception occurred while switching device to DFU Mode. Exception: {0}", ex); } switch (dfuAttempts) { case 5: logger.LogInformation( "Having trouble putting Meadow in DFU Mode, please press RST button on Meadow and press enter to try again"); Console.ReadKey(); break; case 10: logger.LogInformation( "Having trouble putting Meadow in DFU Mode, please hold BOOT button, press RST button and release BOOT button on Meadow and press enter to try again"); Console.ReadKey(); break; case > 15: throw new Exception( "Unable to place device in DFU mode, please disconnect the Meadow, hold the BOOT button, reconnect the Meadow, release the BOOT button and try again."); } // Lets give the device a little time to settle in and get picked up await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); dfuAttempts++; } // Get the serial number so that later we can pick the right device if the system has multiple meadow plugged in string serialNumber = DfuUtils.GetDeviceSerial(dfuDevice); logger.LogInformation("Device in DFU Mode, flashing OS"); var res = await DfuUtils.DfuFlashAsync(osPath, osVersion ?? "", dfuDevice, logger).ConfigureAwait(false); if (res) { logger.LogInformation("Device Flashed."); return(serialNumber); } else { throw new MeadowDeviceException("Failed to flash meadow"); } }
//Probably rename static async Task ProcessHcom(Options options) { if (string.IsNullOrEmpty(options.SerialPort)) { Console.WriteLine("Please specify a --SerialPort"); return; } MeadowSerialDevice device = null; try { Console.WriteLine($"Opening port '{options.SerialPort}'"); device = await MeadowDeviceManager.GetMeadowForSerialPort(options.SerialPort); } catch (Exception ex) { Console.WriteLine($"Error connecting to device: {ex.Message}"); return; } using (device) { // verify that the port was actually connected if (device.Socket == null && device.SerialPort == null) { Console.WriteLine($"Port is unavailable."); return; } try { if (options.WriteFile.Any()) { string[] parameters = options.WriteFile.ToArray(); string[] files = parameters[0].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); string[] targetFileNames; if (parameters.Length == 1) { targetFileNames = new string[files.Length]; } else { targetFileNames = parameters[1].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } if (files.Length != targetFileNames.Length) { Console.WriteLine($"Number of files to write ({files.Length}) does not match the number of target file names ({targetFileNames.Length})."); } else { for (int i = 0; i < files.Length; i++) { string targetFileName = targetFileNames[i]; if (String.IsNullOrEmpty(targetFileName)) { targetFileName = null; } if (!File.Exists(files[i])) { Console.WriteLine($"Cannot find {files[i]}"); } else { if (string.IsNullOrEmpty(targetFileName)) { #if USE_PARTITIONS Console.WriteLine($"Writing {files[i]} to partition {options.Partition}"); #else Console.WriteLine($"Writing {files[i]}"); #endif } else { #if USE_PARTITIONS Console.WriteLine($"Writing {files[i]} as {targetFileName} to partition {options.Partition}"); #else Console.WriteLine($"Writing {files[i]} as {targetFileName}"); #endif } await MeadowFileManager.WriteFileToFlash(device, files[i], targetFileName, options.Partition).ConfigureAwait(false); } } } } else if (options.DeleteFile.Any()) { string[] parameters = options.DeleteFile.ToArray(); string[] files = parameters[0].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (string file in files) { if (!String.IsNullOrEmpty(file)) { #if USE_PARTITIONS Console.WriteLine($"Deleting {file} from partion {options.Partition}"); #else Console.WriteLine($"Deleting {file}"); #endif await MeadowFileManager.DeleteFile(device, file, options.Partition); } } } else if (options.EraseFlash) { Console.WriteLine("Erasing flash"); await MeadowFileManager.EraseFlash(device); } else if (options.VerifyErasedFlash) { Console.WriteLine("Verifying flash is erased"); await MeadowFileManager.VerifyErasedFlash(device); } else if (options.PartitionFileSystem) { Console.WriteLine($"Partioning file system into {options.NumberOfPartitions} partition(s)"); await MeadowFileManager.PartitionFileSystem(device, options.NumberOfPartitions); } else if (options.MountFileSystem) { #if USE_PARTITIONS Console.WriteLine($"Mounting partition {options.Partition}"); #else Console.WriteLine("Mounting file system"); #endif await MeadowFileManager.MountFileSystem(device, options.Partition); } else if (options.InitFileSystem) { #if USE_PARTITIONS Console.WriteLine($"Intializing filesystem in partition {options.Partition}"); #else Console.WriteLine("Intializing filesystem"); #endif await MeadowFileManager.InitializeFileSystem(device, options.Partition); } else if (options.CreateFileSystem) //should this have a partition??? { Console.WriteLine($"Creating file system"); await MeadowFileManager.CreateFileSystem(device); } else if (options.FormatFileSystem) { #if USE_PARTITIONS Console.WriteLine($"Format file system on partition {options.Partition}"); #else Console.WriteLine("Format file system"); #endif await MeadowFileManager.FormatFileSystem(device, options.Partition); } else if (options.ListFiles) { #if USE_PARTITIONS Console.WriteLine($"Getting list of files on partition {options.Partition}"); #else Console.WriteLine($"Getting list of files"); #endif await MeadowFileManager.ListFiles(device, options.Partition); } else if (options.ListFilesAndCrcs) { #if USE_PARTITIONS Console.WriteLine($"Getting list of files and CRCs on partition {options.Partition}"); #else Console.WriteLine("Getting list of files and CRCs"); #endif await MeadowFileManager.ListFilesAndCrcs(device, options.Partition); } else if (options.SetTraceLevel) { Console.WriteLine($"Setting trace level to {options.TraceLevel}"); await MeadowDeviceManager.SetTraceLevel(device, options.TraceLevel); } else if (options.SetDeveloper1) { Console.WriteLine($"Setting developer level to {options.DeveloperValue}"); await MeadowDeviceManager.SetDeveloper1(device, options.DeveloperValue); } else if (options.SetDeveloper2) { Console.WriteLine($"Setting developer level to {options.DeveloperValue}"); await MeadowDeviceManager.SetDeveloper2(device, options.DeveloperValue); } else if (options.SetDeveloper3) { Console.WriteLine($"Setting developer level to {options.DeveloperValue}"); await MeadowDeviceManager.SetDeveloper3(device, options.DeveloperValue); } else if (options.SetDeveloper4) { Console.WriteLine($"Setting developer level to {options.DeveloperValue}"); await MeadowDeviceManager.SetDeveloper4(device, options.DeveloperValue); } else if (options.NshEnable) { Console.WriteLine($"Enable Nsh"); await MeadowDeviceManager.NshEnable(device); } else if (options.MonoDisable) { await MeadowDeviceManager.MonoDisable(device); } else if (options.MonoEnable) { await MeadowDeviceManager.MonoEnable(device); } else if (options.MonoRunState) { await MeadowDeviceManager.MonoRunState(device); } else if (options.MonoFlash) { await MeadowDeviceManager.MonoFlash(device); } else if (options.MonoUpdateRt) { string sourcefilename = options.FileName; if (string.IsNullOrWhiteSpace(sourcefilename)) { // check local override sourcefilename = Path.Combine(Directory.GetCurrentDirectory(), DownloadManager.RuntimeFilename); if (File.Exists(sourcefilename)) { Console.WriteLine($"Using current directory '{DownloadManager.RuntimeFilename}'"); } else { sourcefilename = Path.Combine(DownloadManager.FirmwareDownloadsFilePath, DownloadManager.RuntimeFilename); if (File.Exists(sourcefilename)) { Console.WriteLine("FileName not specified, using latest download."); } else { Console.WriteLine("Unable to locate a runtime file. Either provide a path or download one."); return; // KeepConsoleOpen? } } } if (!File.Exists(sourcefilename)) { Console.WriteLine($"File '{sourcefilename}' not found"); return; // KeepConsoleOpen? } await MeadowFileManager.MonoUpdateRt(device, sourcefilename, options.TargetFileName, options.Partition); } else if (options.GetDeviceInfo) { await MeadowDeviceManager.GetDeviceInfo(device); } else if (options.GetDeviceName) { await MeadowDeviceManager.GetDeviceName(device); } else if (options.ResetMeadow) { Console.WriteLine("Resetting Meadow"); await MeadowDeviceManager.ResetMeadow(device); } else if (options.EnterDfuMode) { Console.WriteLine("Entering Dfu mode"); await MeadowDeviceManager.EnterDfuMode(device); } else if (options.TraceDisable) { Console.WriteLine("Disabling Meadow trace messages"); await MeadowDeviceManager.TraceDisable(device); } else if (options.TraceEnable) { Console.WriteLine("Enabling Meadow trace messages"); await MeadowDeviceManager.TraceEnable(device); } else if (options.Uart1Apps) { Console.WriteLine("Use Uart1 for .NET Apps"); await MeadowDeviceManager.Uart1Apps(device); } else if (options.Uart1Trace) { Console.WriteLine("Use Uart1 for outputting Meadow trace messages"); await MeadowDeviceManager.Uart1Trace(device); } else if (options.RenewFileSys) { Console.WriteLine("Recreate a new file system on Meadow"); await MeadowDeviceManager.RenewFileSys(device); } else if (options.QspiWrite) { Console.WriteLine($"Executing QSPI Flash Write using {options.DeveloperValue}"); await MeadowDeviceManager.QspiWrite(device, options.DeveloperValue); } else if (options.QspiRead) { Console.WriteLine($"Executing QSPI Flash Read using {options.DeveloperValue}"); await MeadowDeviceManager.QspiRead(device, options.DeveloperValue); } else if (options.QspiInit) { Console.WriteLine($"Executing QSPI Flash Initialization using {options.DeveloperValue}"); await MeadowDeviceManager.QspiInit(device, options.DeveloperValue); } else if (options.StartDebugging) { MeadowDeviceManager.StartDebugging(device, options.VSDebugPort); Console.WriteLine($"Ready for Visual Studio debugging"); options.KeepAlive = true; } else if (options.Esp32WriteFile) { if (string.IsNullOrEmpty(options.FileName)) { Console.WriteLine($"option --Esp32WriteFile requires option --File (the local file you wish to write)"); } else { if (string.IsNullOrEmpty(options.TargetFileName)) { Console.WriteLine($"Writing {options.FileName} to ESP32"); } else { Console.WriteLine($"Writing {options.FileName} as {options.TargetFileName}"); } await MeadowFileManager.WriteFileToEspFlash(device, options.FileName, options.TargetFileName, options.Partition, options.McuDestAddr); } } else if (options.FlashEsp) { Console.WriteLine($"Transferring {DownloadManager.NetworkMeadowCommsFilename}"); await MeadowFileManager.WriteFileToEspFlash(device, Path.Combine(DownloadManager.FirmwareDownloadsFilePath, DownloadManager.NetworkMeadowCommsFilename), mcuDestAddr : "0x10000"); await Task.Delay(1000); Console.WriteLine($"Transferring {DownloadManager.NetworkBootloaderFilename}"); await MeadowFileManager.WriteFileToEspFlash(device, Path.Combine(DownloadManager.FirmwareDownloadsFilePath, DownloadManager.NetworkBootloaderFilename), mcuDestAddr : "0x1000"); await Task.Delay(1000); Console.WriteLine($"Transferring {DownloadManager.NetworkPartitionTableFilename}"); await MeadowFileManager.WriteFileToEspFlash(device, Path.Combine(DownloadManager.FirmwareDownloadsFilePath, DownloadManager.NetworkPartitionTableFilename), mcuDestAddr : "0x8000"); await Task.Delay(1000); } else if (options.Esp32ReadMac) { await MeadowDeviceManager.Esp32ReadMac(device); } else if (options.Esp32Restart) { await MeadowDeviceManager.Esp32Restart(device); } else if (options.DeployApp && !string.IsNullOrEmpty(options.FileName)) { await MeadowDeviceManager.DeployApp(device, options.FileName); } else if (options.RegisterDevice) { var sn = await MeadowDeviceManager.GetDeviceSerialNumber(device); if (string.IsNullOrEmpty(sn)) { Console.WriteLine("Could not get device serial number. Reconnect device and try again."); return; } Console.WriteLine($"Registering device {sn}"); DeviceRepository repository = new DeviceRepository(); var result = await repository.AddDevice(sn); if (result.isSuccess) { Console.WriteLine("Device registration complete"); } else { Console.WriteLine(result.message); } } if (options.KeepAlive) { Console.Read(); } } catch (IOException ex) { if (ex.Message.Contains("semaphore")) { if (ex.Message.Contains("semaphore")) { Console.WriteLine("Timeout communicating with Meadow"); } else { Console.WriteLine($"Unexpected error occurred: {ex.Message}"); } return; // KeepConsoleOpen? } } catch (Exception ex) { Console.WriteLine($"Unexpected error occurred: {ex.Message}"); return; // KeepConsoleOpen? } } }
static async Task TestNonFlashDeviceManagerCommands() { try { var meadow = await MeadowDeviceManager.GetMeadowForSerialPort("COM3"); Console.WriteLine("SetTraceLevel"); await MeadowDeviceManager.SetTraceLevel(meadow, 1); // does not sent Concluded //Console.WriteLine("ResetMeadow"); //await MeadowDeviceManager.ResetMeadow(meadow); // not implemented //Console.WriteLine("EnterDfuMode"); //await MeadowDeviceManager.EnterDfuMode(meadow); // request rejected; unknown command //Console.WriteLine("NshEnable"); //await MeadowDeviceManager.NshEnable(meadow); Console.WriteLine("MonoRunState"); await MeadowDeviceManager.MonoRunState(meadow); Console.WriteLine("GetDeviceInfo"); await MeadowDeviceManager.GetDeviceInfo(meadow); Console.WriteLine("SetDeveloper1"); await MeadowDeviceManager.SetDeveloper1(meadow, 1); Console.WriteLine("SetDeveloper2"); await MeadowDeviceManager.SetDeveloper2(meadow, 1); Console.WriteLine("SetDeveloper3"); await MeadowDeviceManager.SetDeveloper3(meadow, 1); Console.WriteLine("SetDeveloper4"); await MeadowDeviceManager.SetDeveloper4(meadow, 1); Console.WriteLine("TraceDisable"); await MeadowDeviceManager.TraceDisable(meadow); Console.WriteLine("TraceEnable"); await MeadowDeviceManager.TraceEnable(meadow); Console.WriteLine("Uart1Apps"); await MeadowDeviceManager.Uart1Apps(meadow); Console.WriteLine("Uart1Trace"); await MeadowDeviceManager.Uart1Trace(meadow); // restarts device. send reconnect? //Console.WriteLine("RenewFileSys"); //await MeadowDeviceManager.RenewFileSys(meadow); // request rejected; unknown command //Console.WriteLine("QspiWrite"); //await MeadowDeviceManager.QspiWrite(meadow, 1); // request rejected; unknown command //Console.WriteLine("QspiRead"); //await MeadowDeviceManager.QspiRead(meadow, 1); //request rejected; unknown command //Console.WriteLine("QspiInit"); //await MeadowDeviceManager.QspiInit(meadow, 1); // mono needs to be disabled for the ESP commands await MeadowDeviceManager.MonoDisable(meadow); Console.WriteLine("Esp32ReadMac"); await MeadowDeviceManager.Esp32ReadMac(meadow); Console.WriteLine("Esp32Restart"); await MeadowDeviceManager.Esp32Restart(meadow); } catch (MeadowDeviceManagerException ex) { Console.WriteLine(ex.HcomMeadowRequestType); } }