Exemplo n.º 1
0
        private static void ExecuteCommand(IDictionary <string, ValueObject> param, StringBuilder batString, string command, Dictionary <string, string> tokens)
        {
            foreach (var token in tokens)
            {
                command = command.Replace(token.Key, token.Value);
            }


            if (param["--bat"] != null)
            {
                batString.AppendLine(command);
            }
            else
            {
                // Execute each batch

                using (var cli = new Cli("cmd"))
                {
                    var handler = new BufferHandler(
                        stdOutLine => Console.WriteLine(stdOutLine),
                        stdErrLine => Console.WriteLine(stdErrLine));

                    Console.WriteLine(string.Empty);

                    Console.WriteLineFormatted($@"Executing: ", Color.CadetBlue);
                    Console.WriteLineFormatted("    " + command, Color.White);
                    Console.WriteLine(string.Empty);

                    cli.Execute($@"/c ""{command}""", bufferHandler: handler);
                }
            }
        }
Exemplo n.º 2
0
        public async Task <string> Run(string imageName, Dictionary <string, string> environmentVariables = null, string command = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            StringBuilder result = new StringBuilder();
            StringBuilder error  = new StringBuilder();

            StringBuilder s = new StringBuilder();

            foreach (var key in environmentVariables.Keys)
            {
                s.Append($" -e {key}={environmentVariables[key]} ");
            }

            ExecutionInput input = new ExecutionInput($"run --rm {s.ToString()} {imageName} {command}");



            //input.StandardInput = s.ToString();


            var handler = new BufferHandler(stdOutLine => result.Append(stdOutLine), stdErrLine => error.Append(stdErrLine));

            //if (environmentVariables != null)
            //{
            //    input.EnvironmentVariables = environmentVariables;
            //}
            ExecutionOutput output = await _cliDocker.ExecuteAsync(input, cancellationToken, handler);

            if (output.ExitCode != 0)
            {
                throw new CliException("Could not run image", result.ToString(), error.ToString());
            }
            return(result.ToString());
        }
Exemplo n.º 3
0
        public void Enter(NavGroup helper)
        {
            mHelper = helper;
            SimGUIUtil.BuildLabelRegion(false);

            mPolyRefs = new BufferHandler <uint>("Search Buffer Size"
                                                 , 1, QEUtil.SmallBufferInit, 1, QEUtil.SmallBufferMax);

            int size = mPolyRefs.MaxElementCount;

            mParentRefs = new uint[size];
            mCosts      = new float[size];
            mCentroids  = new Vector3[size];

            mResultCount = 0;
            mHasPosition = false;

            SimGUIUtil.contextHelpText = string.Format(
                "Scale Search: [{0}] [{1}], Translate Search Y: [{2}] [{3}]"
                , StdButtons.AdjustXZMinus, StdButtons.AdjustXZPlus
                , StdButtons.AdjustYMinus, StdButtons.AdjustYPlus);

            SimGUIUtil.contextControlZone.height = SimGUIUtil.LineHeight * 2.5f;
            SimGUIUtil.contextActive             = true;
        }
Exemplo n.º 4
0
 public virtual void Exit()
 {
     path = null;
     SimGUIUtil.labels.Clear();
     SimGUIUtil.contextHelpText = "";
     SimGUIUtil.contextActive   = false;
 }
Exemplo n.º 5
0
 public void Exit()
 {
     SimGUIUtil.labels.Clear();
     mPolyRefs     = null;
     mStraightPath = null;
     SimGUIUtil.contextHelpText = "";
     SimGUIUtil.contextActive   = false;
 }
Exemplo n.º 6
0
        public void Exit()
        {
            mPolyRefs = null;

            SimGUIUtil.labels.Clear();
            SimGUIUtil.contextHelpText = "";
            SimGUIUtil.contextActive   = false;
        }
Exemplo n.º 7
0
        public NetServerService(PacketHandler packetHandler, ILog logger, int maxConnection, int bufferSize, int keepAliveTime, int keepAliveInterval, bool onMonitoring)
            : base(packetHandler, logger, bufferSize, keepAliveTime, keepAliveInterval, onMonitoring)
        {
            _listener = new Listener();
            _listener.OnNewClientCallback += OnConnectedClient;


            // SocketAsyncEventArgs object pool 생성
            _receiveEventAragePool = new SocketAsyncEventArgsPool(maxConnection);
            _sendEventAragePool    = new SocketAsyncEventArgsPool(maxConnection);



            // 버퍼 할당
            _bufferHandler = new BufferHandler(maxConnection * bufferSize * preAllocCount, bufferSize);
            _bufferHandler.InitBuffer();


            // SocketAsyncEventArgs object pool 할당
            SocketAsyncEventArgs args;

            for (int i = 0; i < maxConnection; i++)
            {
                ClientSession clientSession = new ClientSession(_logger, bufferSize);
                clientSession.CompletedMessageCallback += OnMessageCompleted;


                // receive pool
                {
                    args            = new SocketAsyncEventArgs();
                    args.Completed += new EventHandler <SocketAsyncEventArgs>(OnReceiveCompleted);
                    args.UserToken  = clientSession;

                    _bufferHandler.SetBuffer(args);
                    _receiveEventAragePool.Push(args);
                }

                // send pool
                {
                    args            = new SocketAsyncEventArgs();
                    args.Completed += new EventHandler <SocketAsyncEventArgs>(OnSendCompleted);
                    args.UserToken  = clientSession;

                    _bufferHandler.SetBuffer(args);
                    _sendEventAragePool.Push(args);
                }
            }


            _authedClientSessions    = new Dictionary <string, ClientSession>();
            _reconnectClientSessions = new List <ClientSession>();
            _expiredClientSessions   = new List <string>();

            _removeClientSessionTick = DateTime.UtcNow.AddSeconds(10).Ticks;

            _netMonitorHandler = new MonitorHandler(logger, 10);
        }
Exemplo n.º 8
0
 // 释放对象
 internal void Dispose()
 {
     if (Interlocked.CompareExchange(ref DisposedCAS, 1, 0) == 0)        // CAS
     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock )
     // Lock objects : InnerSocket
     {
         LOCK(ref InnerSocketLockRoot);
         try {
             if (InnerSocket.Connected)
             {
                 InnerSocket.Shutdown(SocketShutdown.Both);
             }
             InnerSocket.Close();
         } finally { UNLOCK(ref InnerSocketLockRoot); }
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock )
         if (ConnectArgs != null)
         {
             ConnectArgs.Dispose();
         }
         if (SendArgs != null)
         {
             SendArgs.Dispose();
         }
         if (ReceivingMessage != null)
         {
             ReceivingMessage.Dispose();
         }
         if (SendingMessage != null)
         {
             SendingMessage.Dispose();
         }
         // 归还缓冲区
         BufferHandler.RecyclingBuffer(ReceiveBuffer);
         ReceiveBuffer = null;
         // 清空并释放接收消息队列
         int length = ReceiveMessageQueue.Count;
         for (int i = 0; i < length; i++)
         {
             ReceiveMessageQueue[i].Dispose();
         }
         ReceiveMessageQueue.RemoveRange(0, length);
         // 清空并释放发送消息队列
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock )
         // Lock objects : SendMessageQueue
         LOCK(ref SendMessageQueueLockRoot);
         try {
             length = SendMessageQueue.Count;
             for (int i = 0; i < length; i++)
             {
                 SendMessageQueue[i].Dispose();
             }
             SendMessageQueue.RemoveRange(0, length);
         } finally { UNLOCK(ref SendMessageQueueLockRoot); }
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock )
     }
 }
Exemplo n.º 9
0
        public override void Enter(NavGroup helper)
        {
            base.Enter(helper);

            mTarget.polyRef = 0;
            mStraightCount  = 0;
            mStraightPath   = new BufferHandler <Vector3>("Straight Path Buffer"
                                                          , 1, QEUtil.SmallBufferInit, 1, QEUtil.SmallBufferMax);

            SimGUIUtil.contextControlZone.height += SimGUIUtil.LineHeight * 2.5f;
        }
Exemplo n.º 10
0
        public Task <ExecutionOutput> GetFrameAsync(string path, TimeSpan start, string fps, string dir, CancellationToken token = default(CancellationToken))
        {
            Directory.CreateDirectory(dir);
            var argumentStr = $"ffmpeg.exe -i \"{path}\" -ss {start} -r {fps} -q:v 2 -f image2 \"{dir}/pic_%5d.jpg\"";

            using (var cli = new Cli("cmd"))
            {
                var handler = new BufferHandler(
                    stdOut => Logger.Log(stdOut),
                    stdErr => Logger.Log(stdErr)
                    );
                return(cli.Execute1Async(argumentStr, cancellationToken: token, bufferHandler: handler));
            }
        }
Exemplo n.º 11
0
        static async Task Run(string source, string output)
        {
            // Split volume
            var volumePathSplited = DevCore.IO.SplitVolumePath(source);

            Matcher matcher = new Matcher(StringComparison.InvariantCultureIgnoreCase);

            matcher.AddInclude(volumePathSplited.Item2);

            var results = MatcherExtensions.GetResultsInFullPath(matcher, volumePathSplited.Item1 + System.IO.Path.DirectorySeparatorChar);

            Console.WriteLine(string.Empty);
            Console.WriteLineFormatted($@"Volume: {volumePathSplited.Item1}", Color.Green);
            Console.WriteLineFormatted($@"Path: {volumePathSplited.Item2}", Color.Green);
            Console.WriteLineFormatted($@"{results.Count()} files found", Color.Green);
            results.ToList().ForEach(e => Console.WriteLine(e));

            Stopwatch sw = new Stopwatch();

            sw.Start();
            foreach (var item in results)
            {
                using (var cli = new Cli("ffmpeg"))
                {
                    var destiny = Path.ChangeExtension(item, output);
                    var args    = $@"-i ""{item}"" ""{destiny}""";

                    var handler = new BufferHandler(
                        stdOutLine => Console.WriteLine(stdOutLine),
                        stdErrLine => Console.WriteLine(stdErrLine));

                    Console.WriteLine(string.Empty);
                    Console.WriteFormatted($@"Executing: ", Color.Green);
                    Console.WriteLineFormatted($"ffmpeg {args}", Color.White);
                    Console.WriteLine(string.Empty);

                    await cli.ExecuteAsync(args, bufferHandler : handler);
                }
            }
            sw.Stop();

            if (results.Any())
            {
                Console.WriteLine(string.Empty);
                Console.Write($"The process has been executed in: ");
                Console.WriteFormatted($"{sw.Elapsed.TotalSeconds}", Color.Green);
                Console.WriteLine($" seconds.");
            }
        }
Exemplo n.º 12
0
        public void Enter(NavGroup helper)
        {
            this.mHelper      = helper;
            mPosition.polyRef = 0;
            mGoal.polyRef     = 0;

            SimGUIUtil.BuildLabelRegion(false);

            mPolyRefs = new BufferHandler <uint>("Visited Buffer Size"
                                                 , 1, QEUtil.SmallBufferInit, 1, QEUtil.SmallBufferMax);

            mStraightPath = new Vector3[mPolyRefs.MaxElementCount];

            SimGUIUtil.contextControlZone.height = SimGUIUtil.LineHeight * 2.5f;
            SimGUIUtil.contextActive             = true;
        }
Exemplo n.º 13
0
        public void Enter(NavGroup helper)
        {
            mHelper           = helper;
            mPosition.polyRef = 0;
            mGoal.polyRef     = 0;

            SimGUIUtil.BuildLabelRegion(false);

            mPolyRefs = new BufferHandler <uint>("Buffer size"
                                                 , 1, QEUtil.SmallBufferInit, 1, QEUtil.SmallBufferMax);

            mResultCount = 0;

            SimGUIUtil.contextControlZone.height = SimGUIUtil.LineHeight * 2.5f;
            SimGUIUtil.contextActive             = true;
        }
Exemplo n.º 14
0
        public virtual void Enter(NavGroup helper)
        {
            this.helper = helper;

            pathCount        = 0;
            position.polyRef = 0;
            goal.polyRef     = 0;

            SimGUIUtil.BuildLabelRegion(false);

            path =
                new BufferHandler <uint>("Path Buffer", 1, QEUtil.SmallBufferInit, 1, MaxPathBuffer);

            mLocalMessage = "No path";
            SimGUIUtil.contextHelpText           = "";
            SimGUIUtil.contextControlZone.height = SimGUIUtil.LineHeight * 5.5f;
            SimGUIUtil.contextActive             = true;
        }
Exemplo n.º 15
0
        //ffmpeg -i input.mp4 -ss 00:00:20 -t 10 -r 1 -q:v 2 -f image2 pic-%03d.jpeg
        public void GetFrame(string path, TimeSpan start, string fps, string name)
        {
            var videoName = name ?? Path.GetFileNameWithoutExtension(path);
            var dir       = $"./images/{videoName}";

            Directory.CreateDirectory(dir);
            var argumentStr = $"ffmpeg.exe -i \"{path}\" -ss {start} -r {fps} -q:v 2 -f image2 \"{dir}/pic_%5d.jpg\"";

            using (var cli = new Cli("cmd"))
            {
                var handler = new BufferHandler(
                    stdOut => Logger.Log(stdOut),
                    stdErr => Logger.Log(stdErr)
                    );
                var output = cli.Execute1Async(argumentStr, bufferHandler: handler);
                //output.GetAwaiter().GetResult();
            }
        }
Exemplo n.º 16
0
        public void Enter(NavGroup helper)
        {
            mHelper = helper;

            SimGUIUtil.BuildLabelRegion(false);

            mPolyRefs = new BufferHandler <uint>("Search Buffer"
                                                 , 1, QEUtil.SmallBufferInit, 1, QEUtil.SmallBufferMax);

            mResultCount = 0;

            SimGUIUtil.contextHelpText = string.Format("Scale Search: [{0}] [{1}] [{2}] [{3}]"
                                                       , StdButtons.AdjustXZMinus, StdButtons.AdjustXZPlus
                                                       , StdButtons.AdjustYMinus, StdButtons.AdjustYPlus);

            SimGUIUtil.contextControlZone.height = SimGUIUtil.LineHeight * 2.5f;
            SimGUIUtil.contextActive             = true;
        }
Exemplo n.º 17
0
    private bool InitializeNav()
    {
        NavManagerProvider provider =
            (NavManagerProvider)FindObjectOfType(typeof(NavManagerProvider));

        if (provider == null)
        {
            Debug.LogError(string.Format("{0}: There is no {1} in the scene."
                                         , name, typeof(NavManagerProvider).Name));

            return(false);
        }

        NavManager manager = provider.CreateManager();

        if (manager == null)
        {
            Debug.LogError(string.Format("{0}: Could not get the navigation manager.", name));

            return(false);
        }

        mGroup = manager.NavGroup;

        maxPathSize = Mathf.Max(1, maxPathSize);

        mPath = new BufferHandler <uint>(
            "Max Path Size", 1, maxPathSize, 1, Mathf.Max(100, maxPathSize));

        mPathStart = new NavmeshPoint();
        mPathEnd   = new NavmeshPoint();

        maxCorners = Mathf.Max(1, maxCorners);

        mCornerPolys =
            new BufferHandler <uint>("Max Corner Size", 1, maxCorners, 1, Mathf.Max(maxCorners, 20));

        HandlePathBufferResize();

        return(true);
    }
Exemplo n.º 18
0
        public void connect(String host, int port, BufferHandler bufferHandler)
        {
            if (this.client != null)
            {
                throw new Exception("连接己打开");
            }
            this.client = new TcpClient(host, port);

            /*
             * IAsyncResult ar = this.client.BeginConnect(host, port, new AsyncCallback(connectCallback), this.client);
             * if (ar.AsyncWaitHandle.WaitOne() == false)
             * {
             *  this.close();
             *  throw new Exception("连接超时");
             * }
             */
            this.socket          = this.client.Client;
            this.socket.Blocking = false;
            this.bufferHandler   = bufferHandler;

            this.buff = new byte[receiveBufferSize];
            tryReceive();
        }
Exemplo n.º 19
0
        private async Task WaitForContainerToDie()
        {
            ExecutionInput          input = new ExecutionInput($@"events --filter com.docker.compose.project={_projectName} --filter event=die");
            CancellationTokenSource monitorTokenSource = new CancellationTokenSource();
            var linkedTokens = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, monitorTokenSource.Token);

            var handler = new BufferHandler(
                stdOutLine => monitorTokenSource.Cancel(), // We received the info we were waiting for
                stdErrLine => monitorTokenSource.Cancel());

            try
            {
                await _cliDocker.ExecuteAsync(input, linkedTokens.Token, handler);
            }
            catch (OperationCanceledException e)
            {
                // Only throw the cancelltion exception if the global token was cancelled
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    throw;
                }
            }
        }
Exemplo n.º 20
0
        public void Execute_EchoSpam_BufferHandler_Test()
        {
            using (var cli = new Cli(_echoSpamBat))
            {
                // Collect stdout/stderr from handler separately
                var stdOutBuffer = new StringBuilder();
                var stdErrBuffer = new StringBuilder();
                var handler      = new BufferHandler(
                    stdOutLine => stdOutBuffer.AppendLine(stdOutLine),
                    stdErrLine => stdErrBuffer.AppendLine(stdErrLine));

                var output = cli.Execute(bufferHandler: handler);
                var ex     = Assert.Throws <StandardErrorException>(() => output.ThrowIfError());

                Assert.That(output, Is.Not.Null);
                Assert.That(output.ExitCode, Is.EqualTo(TestExitCode));
                Assert.That(output.StandardOutput, Is.EqualTo(stdOutBuffer.ToString()));
                Assert.That(output.StandardError, Is.EqualTo(stdErrBuffer.ToString()));
                Assert.That(output.StandardError, Is.EqualTo(ex.StandardError));
                Assert.That(output.StartTime, Is.LessThanOrEqualTo(output.ExitTime));
                Assert.That(output.RunTime, Is.EqualTo(output.ExitTime - output.StartTime));
            }
        }
Exemplo n.º 21
0
        public async Task Process(BufferHandler handler)
        {
            int started    = 0;
            int registered = 0;

            Queue <byte[]> memory             = new Queue <byte[]>(blockCount + 1);
            Queue <Task <BufferEntry> > tasks = new Queue <Task <BufferEntry> >(blockCount);

            BufferBlock[] blocks = new BufferBlock[(source.Length - 1) / blockSize + 1];

            void newBlockIfNotExists(int id)
            {
                if (blocks.Length > id && blocks[id] == null)
                {
                    blocks[id] = new BufferBlock
                    {
                        Request = new SemaphoreSlim(0, blocks.Length - id),
                        Ready   = new ManualResetEventSlim(false)
                    };
                }
            }

            void enableBlock(int id, byte[] data, int size)
            {
                blocks[id].Data = data;
                blocks[id].Size = size;
                blocks[id].Ready.Set();
            }

            async Task <bool> readNextBlock(int id)
            {
                byte[] data;

                if (memory.Count == 0)
                {
                    data = new byte[blockSize];
                }
                else
                {
                    data = memory.Dequeue();
                }

                int read = await ReadNext(data).ConfigureAwait(false);

                if (read == 0)
                {
                    return(false);
                }

                for (int i = 0; i <= 1; i++)
                {
                    newBlockIfNotExists(id + i);
                }

                enableBlock(id, data, read);
                return(true);
            }

            while (true)
            {
                if (await readNextBlock(registered++).ConfigureAwait(false) == false)
                {
                    break;
                }

                while (tasks.Count == blockCount)
                {
                    List <Task> wait = new List <Task> {
                        tasks.Peek()
                    };

                    if (blocks.Length > registered)
                    {
                        wait.Add(blocks[registered].Request.WaitAsync());
                    }

                    int index = Task.WaitAny(wait.ToArray());

                    if (index == 0)
                    {
                        BufferEntry entry = tasks.Dequeue().Result;
                        BufferBlock block = blocks[entry.Id];

                        //Console.WriteLine($"awaited block {entry.Id}");

                        blocks[entry.Id] = null;
                        memory.Enqueue(block.Data);

                        block.Request.Dispose();
                        block.Ready.Dispose();
                        block.Data = null;
                    }
                    else
                    {
                        //Console.WriteLine($"awaited request");

                        if (await readNextBlock(registered++).ConfigureAwait(false) == false)
                        {
                            break;
                        }
                    }
                }

                //Console.WriteLine($"started block {started}");
                tasks.Enqueue(handler.Handle(new BufferEntry(started++, blocks)));
            }

            while (started < blocks.Length)
            {
                tasks.Enqueue(handler.Handle(new BufferEntry(started++, blocks)));
            }

            while (tasks.Count > 0)
            {
                await tasks.Dequeue();
            }
        }
Exemplo n.º 22
0
 public override void Exit()
 {
     mStraightPath = null;
     base.Exit();
 }
Exemplo n.º 23
0
 public static void Handle <TFrom, TTo>(this ReadOnlySpan <TFrom> src, Span <TTo> dst, int length, BufferHandler <TFrom, TTo> handler) where TFrom : unmanaged where TTo : unmanaged
 {
     if (src.Length < length)
     {
         throw new ArgumentOutOfRangeException(nameof(src));
     }
     if (dst.Length < length)
         throw new ArgumentOutOfRangeException(nameof(dst));
     fixed(TFrom * @in = src)
     {
         if (MemoryMarshal.Cast <TFrom, byte>(src).Overlaps(MemoryMarshal.Cast <TTo, byte>(dst), out int offset) && offset > 0)
         {
             TTo * @out = stackalloc TTo[length];
             handler(@in, @out, length);
             new ReadOnlySpan <TTo>(@out, length).CopyTo(dst);
         }
         else
         {
             fixed(TTo * @out = dst)
             {
                 handler(@in, @out, length);
             }
         }
     }
 }
Exemplo n.º 24
0
        // --- ( Static ) Public Function ------------------------------------------------------------------------------------------------------------------------------------ //

        // --- ( Static ) Internal & Protected Function ---------------------------------------------------------------------------------------------------------------------- //

        // --- ( Static ) Private Function ----------------------------------------------------------------------------------------------------------------------------------- //

        // --- Public Function ----------------------------------------------------------------------------------------------------------------------------------------------- //

        // --- Internal & Protected Function --------------------------------------------------------------------------------------------------------------------------------- //

        // 创建套接字代理 ( 频道 )
        internal SocketAgent(string host, SocketChannel parentChannel)
        {
            InnerSocket   = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ParentChannel = parentChannel;
            // 解析主机地址
            string[] hostStrings = host.Split(":".ToCharArray());
            if (hostStrings.Length < 2 || !IPAddress.TryParse(hostStrings[0], out IPAddress ip) || !ushort.TryParse(hostStrings[1], out ushort port))
            {
                ERROR("Nero.ManageSocket.AddSocketChannel --- host 格式错误, 解析失败",
                      "channel : " + ParentChannel.ChannelIndex,
                      "host : " + ParentChannel.ChannelHost);
            }
            else
            {
                MessageListeners    = new List <SocketMessageListener> [65536];
                ReceiveBuffer       = BufferHandler.GetBuffer();
                SendArgs            = new SocketAsyncEventArgs();
                SendArgs.Completed += new EventHandler <SocketAsyncEventArgs>((object o, SocketAsyncEventArgs e) => {
                    if (e.SocketError == SocketError.Success)
                    {
                        SendMessageBody();
                    }
                    else
                    {
                        Disconnect();
                    }
                });
                ConnectArgs = new SocketAsyncEventArgs()
                {
                    RemoteEndPoint = new IPEndPoint(ip, port)
                };
                ConnectArgs.Completed += new EventHandler <SocketAsyncEventArgs>((object o, SocketAsyncEventArgs e) => {
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock )
                    // Lock objects : SocketChannelHandler.DelayedOperations
                    LOCK(ref SocketChannelHandler.DelayedOperationsLockRoot);
                    try {
                        if (ConnectArgs.SocketError == SocketError.Success)
                        {
                            ConnectedCAS = 1;
                            SYSTEM("Socket Channel - 套接字频道连接成功", "Channel - " + ParentChannel.ChannelIndex, "Host - " + ParentChannel.ChannelHost);
                            // 添加套接字频道连接成功延迟操作
                            SocketChannelHandler.DelayedOperations.Add(new SocketChannelOperation()
                            {
                                Type         = DelayedOperationType.ConnectionCompleted,
                                ChannelIndex = ParentChannel.ChannelIndex
                            });
                        }
                        else
                        {
                            WARNING("Socket Channel - 套接字频道连接失败", "Channel - " + ParentChannel.ChannelIndex, "Host - " + ParentChannel.ChannelHost);
                            // 添加套接字频道连接失败延迟操作
                            SocketChannelHandler.DelayedOperations.Add(new SocketChannelOperation()
                            {
                                Type          = DelayedOperationType.ConnectionFailed,
                                ChannelIndex  = ParentChannel.ChannelIndex,
                                TargetChannel = ParentChannel
                            });
                        }
                    } finally { UNLOCK(ref SocketChannelHandler.DelayedOperationsLockRoot); }
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock )
                    ConnectArgs.Dispose();
                });
                if (!InnerSocket.ConnectAsync(ConnectArgs))
                {
                    ConnectedCAS = 1;
                    SYSTEM("Socket Channel - 套接字频道连接成功", "Channel - " + ParentChannel.ChannelIndex, "Host - " + ParentChannel.ChannelHost);
                    // 添加套接字频道连接成功延迟操作 ( 同步完成, 无需重复进 SocketChannelHandler.DelayedOperations 锁 )
                    SocketChannelHandler.DelayedOperations.Add(new SocketChannelOperation()
                    {
                        Type         = DelayedOperationType.ConnectionCompleted,
                        ChannelIndex = ParentChannel.ChannelIndex
                    });
                    ConnectArgs.Dispose();
                }
            }
        }
Exemplo n.º 25
0
        private async Task <FirmwareUpdateStatus> UploadFirmwareArduinoNanoOldBootloader(string comPort)
        {
            #region Arduino Nano - old bootloader

            _outputTextHandler("", false);
            _outputTextHandler("/***************************************************/", false);
            _outputTextHandler("/******** Arduino Nano - old bootloader *********/", false);
            _outputTextHandler("/***************************************************/", false);
            _outputTextHandler("", false);

            using (Program.CurrentCli = new Cli("Avrdude/avrdude.exe"))
            {
                var cmd     = $"-CAvrdude/avrdude.conf -v -patmega328p -carduino -P{comPort} -b57600 -D -Uflash:w:\".\\tmp\\nano.hex\":i ";
                var handler = new BufferHandler(
                    stdOutLine => {
                    if (stdOutLine.Contains("not responding"))
                    {
                        Program.CurrentCli.CancelAll();
                    }
                    else
                    {
                        _outputTextHandler(stdOutLine, false);
                    }
                },
                    stdErrLine => {
                    if (stdErrLine.Contains("not responding"))
                    {
                        Program.CurrentCli.CancelAll();
                    }
                    else
                    {
                        _outputTextHandler(stdErrLine, true);
                    }
                }
                    );

                try
                {
                    var output = await Program.CurrentCli.ExecuteAsync(cmd, bufferHandler : handler);

                    if (output.ExitCode == 0)
                    {
                        Program.CurrentCli = null;
                        _statusUpdateHandler(FirmwareUpdateStatus.Successful);
                        return(FirmwareUpdateStatus.Successful);
                    }
                }
                catch (Exception e)
                {
                    _outputTextHandler(e.Message, true);
                }
            }

            Program.CurrentCli = null;

            _outputTextHandler("Arduino Nano - old bootloader failed", true);

            #endregion

            return(FirmwareUpdateStatus.Error);
        }
Exemplo n.º 26
0
        private async Task <FirmwareUpdateStatus> UploadFirmwareArduinoNanoEvery(string comPort)
        {
            #region Arduino Nano Every

            _outputTextHandler("", false);
            _outputTextHandler("/***************************************************/", false);
            _outputTextHandler("/************* Arduino Nano Every ***************/", false);
            _outputTextHandler("/***************************************************/", false);
            _outputTextHandler("", false);

            _outputTextHandler("Switch to 1200 baud rate, open/close to force reset", false);

            using (Program.CurrentCli = new Cli("Avrdude/putty.exe"))
            {
                var cmd = $"-serial {comPort} -sercfg 1200";

                Program.CurrentCli.ExecuteAsync(cmd);

                Thread.Sleep(500);

                Program.CurrentCli.CancelAll();
            }

            Program.CurrentCli = null;

            using (Program.CurrentCli = new Cli("Avrdude/avrdude.exe"))
            {
                // Execute
                var cmd     = $"-CAvrdude/avrdude.conf -v -p atmega4809 -c jtag2updi -D -V -b 115200 -e -P{comPort} -Uflash:w:\".\\tmp\\nano_every.hex\":i -Ufuse2:w:0x01:m -Ufuse5:w:0xC9:m -Ufuse8:w:0x00:m";
                var handler = new BufferHandler(
                    stdOutLine => {
                    if (stdOutLine.Contains("status -1") || stdOutLine.Contains("access is denied"))
                    {
                        Program.CurrentCli.CancelAll();
                    }
                    else
                    {
                        _outputTextHandler(stdOutLine, false);
                    }
                },
                    stdErrLine => {
                    if (stdErrLine.Contains("status -1"))
                    {
                        Program.CurrentCli.CancelAll();
                    }
                    else
                    {
                        _outputTextHandler(stdErrLine, true);
                    }
                }
                    );

                try
                {
                    var output = await Program.CurrentCli.ExecuteAsync(cmd, bufferHandler : handler);

                    if (output.ExitCode == 0)
                    {
                        MessageBox.Show("Please reconnect AF3 power in order to finish the upgrade", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Program.CurrentCli = null;
                        _statusUpdateHandler(FirmwareUpdateStatus.Successful);
                        return(FirmwareUpdateStatus.Successful);
                    }
                }
                catch (Exception e)
                {
                    _outputTextHandler(e.Message, true);
                }
            }

            Program.CurrentCli = null;

            _outputTextHandler("Arduino Nano Every falied", true);

            #endregion

            return(FirmwareUpdateStatus.Error);
        }
Exemplo n.º 27
0
        public async Task <FirmwareUpdateStatus> UpoloadFirmwareEsp32(string comPort, string path)
        {
            try
            {
                _statusUpdateHandler(FirmwareUpdateStatus.Uploading);

                if (Directory.Exists("tmp"))
                {
                    Directory.Delete("tmp", true);
                }

                Directory.CreateDirectory("tmp");

                ZipFile.ExtractToDirectory(path, "tmp");

                /*
                 * Building esptool.exe
                 * mkdir build_tmp
                 * pyinstaller --onefile --specpath build_tmp --workpath build_tmp/build --distpath build_tmp/dist C:\Users\bramor\.platformio\packages\tool-esptoolpy\esptool.py
                 *
                 */
                using (Program.CurrentCli = new Cli("Esptool/esptool.exe"))
                {
                    // Execute

                    /*
                     # Name,   Type, SubType, Offset,  Size, Flags
                     #  nvs,      data, nvs,     0x9000,  0x5000,
                     #  otadata,  data, ota,     0xe000,  0x2000,
                     #  app0,     app,  ota_0,   0x10000, 0x140000,
                     #  app1,     app,  ota_1,   0x150000,0x140000,
                     #  eeprom,   data, 0x99,    0x290000,0x1000,
                     #  spiffs,   data, spiffs,   0x291000,0x16F000
                     */
                    var cmd     = $"--chip esp32 --port \"{comPort}\" --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 40m --flash_size detect 0x1000 .\\tmp\\bootloader_dio_40m.bin 0x8000 .\\tmp\\partitions.bin 0xe000 .\\tmp\\boot_app0.bin 0x10000 .\\tmp\\firmware.bin 0x291000 .\\tmp\\spiffs.bin";
                    var handler = new BufferHandler(
                        stdOutLine => _outputTextHandler(stdOutLine, false),
                        stdErrLine => _outputTextHandler(stdErrLine, true)
                        );

                    var output = await Program.CurrentCli.ExecuteAsync(cmd, bufferHandler : handler);

                    // Extract output
                    var code      = output.ExitCode;
                    var stdOut    = output.StandardOutput;
                    var stdErr    = output.StandardError;
                    var startTime = output.StartTime;
                    var exitTime  = output.ExitTime;
                    var runTime   = output.RunTime;
                    //output.ThrowIfError();

                    Directory.Delete("tmp", true);

                    if (output.ExitCode != 0)
                    {
                        _statusUpdateHandler(FirmwareUpdateStatus.Error);
                        return(FirmwareUpdateStatus.Error);
                    }
                    else
                    {
                        _statusUpdateHandler(FirmwareUpdateStatus.Successful);
                        return(FirmwareUpdateStatus.Successful);
                    }
                }
            }
            catch (Exception ex)
            {
                _outputTextHandler(ex.Message, true);
                _statusUpdateHandler(FirmwareUpdateStatus.Error);
                return(FirmwareUpdateStatus.Error);
            }
        }