Пример #1
0
        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 = _currentDevice = await MeadowDeviceManager.GetMeadowForSerialPort(target);

                EventHandler <MeadowMessageEventArgs> handler = (s, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Message))
                    {
                        outputPaneWriter.WriteAsync(e.Message).Wait();
                    }
                };

                await MeadowDeviceManager.MonoDisable(meadow).ConfigureAwait(false);

                meadow.OnMeadowMessage += handler;
                await MeadowDeviceManager.DeployApp(meadow, Path.Combine(folder, "App.exe"));

                meadow.OnMeadowMessage -= handler;
                await MeadowDeviceManager.MonoEnable(meadow).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            sw.Stop();
            await outputPaneWriter.WriteAsync($"Deployment Duration: {sw.Elapsed}");
        }
        // Avoid changing signature
        public static async Task <IMeadowDevice?> GetMeadowForSerialPort(string serialPort, bool verbose = true, ILogger?logger = null)
        {
            logger ??= NullLogger.Instance;

            try
            {
                logger.LogInformation($"Connecting to Meadow on {serialPort}");
                IMeadowDevice?meadow        = null;
                var           createTask    = Task.Run(() => meadow = new MeadowSerialDevice(serialPort, logger));
                var           completedTask = await Task.WhenAny(createTask, Task.Delay(1000))
                                              .ConfigureAwait(false);

                if (completedTask != createTask || meadow == null)
                {
                    logger.LogTrace("Timeout while creating Meadow");
                    try
                    {
                        await createTask;
                    }
                    catch (Exception ex)
                    {
                        logger.LogInformation(ex, "An error occurred while attempting to create Meadow");
                        throw;
                    }
                    return(null);
                }

                await meadow.InitializeAsync(CancellationToken.None);

                return(meadow);
            }
            catch (FileNotFoundException fnfEx)
            {
                LogUserError(verbose, logger);

                logger.LogDebug(fnfEx, "Failed to open Serial Port.");
                return(null);
            }
            catch (IOException ioEx)
            {
                LogUserError(verbose, logger);

                logger.LogDebug(ioEx, "Failed to open Serial Port.");
                return(null);
            }
            catch (UnauthorizedAccessException unAuthEx) when(
                unAuthEx.InnerException is IOException)
            {
                LogUserError(verbose, logger);

                logger.LogDebug(unAuthEx, "Failed to open Serial Port.");
                return(null);
            }
            catch (Exception ex)
            {
                // TODO: Remove exception catch here and let the caller handle it or wrap it up in our own exception type.
                logger.LogError(ex, "Failed to connect to Meadow on {serialPort}", serialPort);
                throw;
            }
        }
Пример #3
0
        async Task <(List <string> files, List <UInt32> crcs)> GetFilesOnDevice(MeadowSerialDevice meadow, TextWriter outputPaneWriter, CancellationToken cts)
        {
            if (cts.IsCancellationRequested)
            {
                return(new List <string>(), new List <UInt32>());
            }

            await outputPaneWriter.WriteAsync("Checking files on device (may take several seconds)");

            var meadowFiles = await meadow.GetFilesAndCrcs(30000);

            foreach (var f in meadowFiles.files)
            {
                if (cts.IsCancellationRequested)
                {
                    break;
                }
                await outputPaneWriter.WriteAsync($"Found {f}").ConfigureAwait(false);
            }

            if (meadowFiles.files.Count == 0)
            {
                await outputPaneWriter.WriteAsync($"Deploying for the first time may take several minutes.").ConfigureAwait(false);
            }

            return(meadowFiles);
        }
Пример #4
0
        async Task <MeadowDeviceExecutionTarget> InitalizeMeadow(Connection connection)
        {
            MeadowDeviceExecutionTarget target = null;

            await Task <MeadowDeviceExecutionTarget> .Run(() =>
            {
                var meadowSerialDevice = new MeadowSerialDevice(true);
                if (MeadowDeviceManager.CurrentDevice == null || (MeadowDeviceManager.CurrentDevice?.connection.Removed ?? true))
                {
                    MeadowDeviceManager.CurrentDevice = meadowSerialDevice;
                }

                lock (_lockObject)
                {
                    target = new MeadowDeviceExecutionTarget(meadowSerialDevice, connection);
                    if (target != null)
                    {
                        Console.WriteLine($"DeploymentTargetsManagerLinux Added: {target}");
                        Targets.Add(target);
                        target.SerialNumberSet += Target_SerialNumberSet;
                        DeviceListChanged?.Invoke(target);
                    }
                }
            });

            return(target);
        }
        public MeadowPadWidget(MeadowSerialDevice meadow, MeadowPad meadowPad)
        {
            meadowSerialDevice = meadow;
            this.meadowPad     = meadowPad;
            this.Build();

            meadowOS = new Lazy <MeadowOS>(() => new MeadowOS(meadowPad));

            Gdk.Pixbuf image = Gdk.Pixbuf.LoadFromResource("Meadow.Sdks.IdeExtensions.Vs4Mac.MeadowLogo.png");

            // Gtk.ListStore list = new Gtk.ListStore(typeof(Gdk.Pixbuf));
            image = image.ScaleSimple(30, 20, Gdk.InterpType.Bilinear);

            image1.Pixbuf = image;


            iter = textview1.Buffer.EndIter;
            this.textview1.ModifyFont(FontDescription.FromString(MonoDevelop.Ide.Fonts.FontService.MonospaceFontName));
            this.labelState.ModifyFont(FontDescription.FromString(MonoDevelop.Ide.Fonts.FontService.MonospaceFontName));

            LoadTags();

            textview1.SizeAllocated            += Textview1_SizeAllocated;
            meadowSerialDevice.OnMeadowMessage += MeadowData;


            //Textview background. Cant get this to work
            //textview1.Realized += (sender, e) =>
            //{
            //    Gdk.Pixbuf image = Gdk.Pixbuf.LoadFromResource("Meadow.Sdks.IdeExtensions.Vs4Mac.MeadowLogo.png");
            //    Gdk.Pixmap pixmap, pixmap_mask;
            //    image.RenderPixmapAndMask(out pixmap, out pixmap_mask, 0);
            //    textview1.GdkWindow.SetBackPixmap(pixmap, false);
            //};
        }
Пример #6
0
        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);
            }
        }
Пример #7
0
            internal async void ReceiveVSDebug(MeadowSerialDevice meadow)
            {
                // Console.WriteLine("ActiveClient:Start receiving from VS");
                try
                {
                    // Receive from Visual Studio and send to Meadow
                    await Task.Run(async() =>
                    {
                        while (tcpClient.Connected && okayToRun)
                        {
                            var recvdBuffer = new byte[490];
                            var bytesRead   = await networkStream.ReadAsync(recvdBuffer, 0, recvdBuffer.Length);
                            if (!okayToRun)
                            {
                                break;
                            }

                            if (bytesRead > 0)
                            {
                                // Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}-Received {bytesRead} bytes from VS will forward to HCOM");

                                // Need a buffer the exact size of received data to work with CLI
                                var meadowBuffer = new byte[bytesRead];
                                Array.Copy(recvdBuffer, 0, meadowBuffer, 0, bytesRead);

                                // Forward to Meadow
                                MeadowDeviceManager.ForwardVisualStudioDataToMono(meadowBuffer, meadow, 0);
                                //Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}-Forwarded {bytesRead} from VS to Meadow");
                            }
                        }
                    });
                }
                catch (System.IO.IOException ioe)
                {
                    // VS client probably died
                    Console.WriteLine(ioe.ToString());
                    debuggingServer.CloseActiveClient();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    debuggingServer.CloseActiveClient();
                    if (okayToRun)
                    {
                        throw;
                    }
                }
            }
Пример #8
0
        //temp code until we get the device manager logic in place
        static bool ConnectToMeadowDevice(string commPort)
        {
            var device = new MeadowSerialDevice(commPort);

            try
            {
                device.Initialize();
            }
            catch (MeadowDeviceException ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }

            MeadowDeviceManager.CurrentDevice = device;
            return(true);
        }
Пример #9
0
        public async void StartListening(MeadowSerialDevice meadow)
        {
            try
            {
                IPHostEntry ipHostInfo    = Dns.GetHostEntry("localhost");
                IPAddress   ipAddress     = ipHostInfo.AddressList[0];
                IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, vsPort);

                TcpListener tcpListener = new TcpListener(localEndPoint);
                tcpListener.Start();
                Console.WriteLine("Listening for Visual Studio to connect");

                while (true)
                {
                    await Task.Run(async() =>
                    {
                        // Wait for client to connect
                        TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();

                        // tcpClient valid after connection
                        Console.WriteLine("Visual Studio has connected");
                        if (activeClientCount > 0)
                        {
                            Debug.Assert(activeClientCount == 1);
                            Debug.Assert(activeClient != null);
                            activeClient.Close();
                            activeClient      = null;
                            activeClientCount = 0;
                        }

                        activeClient = new ActiveClient(this, tcpClient);
                        activeClient.ReceiveVSDebug(meadow);
                        activeClientCount++;
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #10
0
        public MeadowDeviceExecutionTarget(MeadowSerialDevice meadowSerialDevice, Connection connection = null)
        {
            this.meadowSerialDevice = meadowSerialDevice;
            var waitHandle = new ManualResetEventSlim(false);

            Gtk.Application.Invoke(delegate
                                   { try
                                     {
                                         meadowPad   = new MeadowPad(this, meadowSerialDevice);
                                         var pad     = MonoDevelop.Ide.IdeApp.Workbench.ShowPad(meadowPad, (PadID++).ToString(), "Meadow", "bottom", MonoDevelop.Components.Docking.DockItemStatus.Dockable, new IconId("meadow"));
                                         pad.Visible = true;
                                         pad.IsOpenedAutomatically = true;
                                         pad.BringToFront();

                                         waitHandle.Set();
                                     }
                                     catch (Exception ex)
                                     {
                                         Console.WriteLine($"MeadowDeviceExecutionTarget: Error {ex.Message}");
                                     } });
            if (waitHandle.Wait(3000))
            {
                meadowSerialDevice.StatusChange   += StatusDisplay;
                meadowSerialDevice.RunStateChange += RunState;
                if (meadowSerialDevice.RunState.HasValue)
                {
                    meadowPad.control.SetRunState(meadowSerialDevice.RunState.Value);
                }
                meadowSerialDevice.connection = connection;
                Gtk.Application.Invoke(delegate
                {
                    meadowPad.Window.Title = meadowSerialDevice.connection.ToString();
                });
            }
            else
            {
                MessageDialog dialog = new MessageDialog(IdeApp.Workbench.RootWindow, DialogFlags.DestroyWithParent,
                                                         MessageType.Info, ButtonsType.Ok,
                                                         "Failed to open Meadow console window");
            }
        }
Пример #11
0
        async Task <bool> InitializeMeadowDeviceAsync(MeadowSerialDevice meadow, TextWriter outputPaneWriter, CancellationToken cts)
        {
            if (cts.IsCancellationRequested)
            {
                return(true);
            }

            await outputPaneWriter.WriteAsync("Initializing Meadow");

            if (meadow == null)
            {
                await outputPaneWriter.WriteAsync("Can't read Meadow device");

                return(false);
            }

            meadow.Initialize(false);
            MeadowDeviceManager.MonoDisable(meadow);
            await Task.Delay(5000); //hack for testing

            if (meadow.Initialize() == false)
            {
                await outputPaneWriter.WriteAsync("Couldn't initialize serial port");

                return(false);
            }
            else
            {
                MeadowDeviceManager.GetDeviceInfo(meadow);
                await Task.Delay(1000); // wait for device info to populate

                await outputPaneWriter.WriteAsync($"Device {meadow.DeviceInfo.MeadowOSVersion}");
            }

            return(true);
        }
Пример #12
0
 async Task DeleteUnusedFiles(MeadowSerialDevice meadow, TextWriter outputPaneWriter, CancellationToken cts,
                              (List <string> files, List <UInt32> crcs) meadowFiles, (List <string> files, List <UInt32> crcs) localFiles)
Пример #13
0
        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);
            }
        }
Пример #14
0
        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);
            }
        }
Пример #15
0
        public override Control Control => control; //?? (control = new MeadowPadWidget(meadowSerialDevice));
        //  public override string Id => "MeadowPad";


        public MeadowPad(MeadowDeviceExecutionTarget target, MeadowSerialDevice meadow)
        {
            Target             = target;
            meadowSerialDevice = meadow;
            control            = new MeadowPadWidget(meadowSerialDevice, this);
        }
Пример #16
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
            };

            CompletionBehavior behavior = CompletionBehavior.Success;

            DownloadManager downloadManager = new DownloadManager();
            var             check           = downloadManager.CheckForUpdates().Result;

            if (check.updateExists)
            {
                Console.WriteLine($"CLI version {check.latestVersion} is available. To update, run: {DownloadManager.UpdateCommand}");
            }

            if (args.Length == 0)
            {
                args = new string[] { "--help" };
            }

            var parser = new Parser(settings => {
                settings.CaseSensitive          = false;
                settings.AutoVersion            = false; // needed to supercede the built in --version command
                settings.HelpWriter             = Console.Out;
                settings.IgnoreUnknownArguments = true;
            });

            parser.ParseArguments <Options>(args)
            .WithParsed <Options>(options =>
            {
                if (options.ListPorts)
                {
                    Console.WriteLine("Available serial ports\n----------------------");

                    var ports = MeadowSerialDevice.GetAvailableSerialPorts();
                    if (ports == null || ports.Length == 0)
                    {
                        Console.WriteLine("\t <no ports found>");
                    }
                    else
                    {
                        foreach (var p in ports)
                        {
                            Console.WriteLine($"\t{p}");
                        }
                    }
                    Console.WriteLine($"\n");
                }
                else
                {
                    if (options.DownloadLatest)
                    {
                        downloadManager.DownloadLatest().Wait();
                    }
                    else if (options.FlashOS)
                    {
                        DfuUpload.FlashOS(options.FileName);
                    }
                    else if (options.Login)
                    {
                        IdentityManager identityManager = new IdentityManager();
                        var result = identityManager.LoginAsync().Result;
                        if (result)
                        {
                            var cred = identityManager.GetCredentials(identityManager.WLRefreshCredentialName);
                            Console.WriteLine($"Signed in as {cred.username}");
                        }
                    }
                    else if (options.Logout)
                    {
                        IdentityManager identityManager = new IdentityManager();
                        identityManager.Logout();
                    }
                    else if (options.InstallDfuUtil)
                    {
                        if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                        {
                            Console.WriteLine("To install on macOS, run: brew install dfu-util");
                        }
                        else
                        {
                            downloadManager.InstallDfuUtil(Environment.Is64BitOperatingSystem);
                        }
                    }
                    else if (args[0].Equals("--version", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine($"Current version: {check.currentVersion}");
                    }
                    else
                    {
                        SyncArgsCache(options);
                        try
                        {
                            ProcessHcom(options).Wait();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"An unexpected error occurred: {ex?.InnerException?.Message}");
                        }
                    }
                }
            });

            //if (System.Diagnostics.Debugger.IsAttached)
            //{
            //    behavior = CompletionBehavior.KeepConsoleOpen;
            //}

            Environment.Exit(0);
        }
Пример #17
0
 //==========================================================================
 // Constructor
 public SendTargetData(MeadowSerialDevice device, bool verbose = true)
 {
     _device      = device;
     this.Verbose = verbose;
 }
Пример #18
0
        //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?
                }
            }
        }
Пример #19
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += (s, e) =>
            {
                _quit    = true;
                e.Cancel = true;
                MeadowDeviceManager.CurrentDevice?.SerialPort?.Close();
            };

            CompletionBehavior behavior = CompletionBehavior.Success;

            if (args.Length == 0)
            {
                args = new string[] { "--help" };
            }
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(options =>
            {
                if (options.ListPorts)
                {
                    Console.WriteLine("Available serial ports\n----------------------");

                    var ports = MeadowSerialDevice.GetAvailableSerialPorts();
                    if (ports == null || ports.Length == 0)
                    {
                        Console.WriteLine("\t <no ports found>");
                    }
                    else
                    {
                        foreach (var p in ports)
                        {
                            Console.WriteLine($"\t{p}");
                        }
                    }
                    Console.WriteLine($"\n");
                }
                else
                {
                    if (options.Dfu)
                    {
                        //ToDo update to use command line args for os and user
                        DfuUpload.FlashNuttx(options.DfuOsPath, options.DfuUserPath);
                    }
                    else
                    {
                        SyncArgsCache(options);
                        try
                        {
                            behavior = ProcessHcom(options).Result;
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            });

            if (System.Diagnostics.Debugger.IsAttached)
            {
                behavior = CompletionBehavior.KeepConsoleOpen;
            }

            if ((behavior & CompletionBehavior.KeepConsoleOpen) == CompletionBehavior.KeepConsoleOpen)
            {
                Console.Read();
            }
            else
            {
                Thread.Sleep(500);
            }
        }