예제 #1
0
        async void ToggleAnimation()
        {
            if (IsRunning)
            {
                if (OnStartedAnimation != null)
                {
                    await OnStartedAnimation.Begin();
                }

                ToggleIndicator(IsRunning);

                OnStarted?.Invoke(this, null);
            }
            else
            {
                if (OnCompletedAnimation != null)
                {
                    await OnCompletedAnimation.Begin();
                }

                ToggleIndicator(IsRunning);

                OnCompleted?.Invoke(this, null);
            }

            void ToggleIndicator(bool isRunning)
            {
                IsVisible =
                    _loadingIndicator.IsVisible     =
                        _loadingIndicator.IsRunning =
                            IsRunning;

                Opacity = 1;
            }
        }
예제 #2
0
 private void Init()
 {
     OnStarted.AddListener(OnStarted_Listener);
     OnStartedSilent.AddListener(OnStartedSilent_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     _actionResult = ActionResult.PROGRESS;
 }
예제 #3
0
        /////////////////////////////////////
        //          Public
        /////////////////////////////////////

        public bool Start(int port = 7788)
        {
            try
            {
                Host = new SimpleTcpServer();
                //Host.Delimiter
                //Host.DelimiterDataReceived += (o, e) => { Console.WriteLine("Delimter data received"); };
                //Host.DataReceived += (o, e) => { Console.WriteLine("##############Data received"); };
                //Host.DataReceived += DataReceived;
                Host.DelimiterDataReceived += DataReceived;

                Host.ClientConnected += ClientConnected;

                Host.Start(port);

                disconnectPing.Start();
                InvokeOutput("Server Started.");

                if (!hasConnectedBefore)
                {
                    hasConnectedBefore = true;
                    Application.Current.MainWindow.Closed += Program_Exit;
                }
                OnStarted?.Invoke();


                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Warning#001 :" + ex.Message);
                InvokeOutput("Server Not Started.");
                return(false);
            }
        }
예제 #4
0
        /// <summary>
        /// Run code in a new worker thread. WorkerDelegate should return true to end, false to repeat.
        /// </summary>
        /// <param name="worker">Delegate to be run</param>
        /// <param name="waitTime"></param>
        public static void Start(Func <bool> worker, int waitTime = 25)
        {
            if (IsRunning)
            {
                return;
            }

            WaitTime = waitTime;

            var frame  = new StackFrame(1);
            var method = frame.GetMethod();
            var type   = method.DeclaringType;
            var ns     = type != null ? type.Namespace : string.Empty;

            _worker = worker;
            _thread = new Thread(SafeWorkerDelegate)
            {
                Name         = $"Worker: {ns}.{type}",
                IsBackground = true,
                Priority     = ThreadPriority.BelowNormal,
            };

            Core.Logger.Debug("Starting {0} Thread Id={1}", _thread.Name, _thread.ManagedThreadId);

            _working = true;
            _thread.Start();

            OnStarted.Invoke();
        }
예제 #5
0
 /// <summary>
 /// Runs the child node with the given probability chance between 0 and 1
 /// </summary>
 /// <param name="probability">Between 0 and 1</param>
 public BehaviourRandom(float probability) : base("Random", NodeType.DECORATOR)
 {
     m_probability = probability;
     OnStarted.AddListener(OnStarted_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
 }
예제 #6
0
        public void SwitchState()
        {
            State next = State.idle;

            switch (_State)
            {
            case State.idle:
                next       = State.started;
                _StartedAt = DateTime.Now;
                OnStarted?.Invoke();
                break;

            case State.paused:
                next       = State.started;
                _PauseSum += DateTime.Now - _PausedAt;
                _PausedAt  = new DateTime();
                OnStarted?.Invoke();
                break;

            case State.started:
                next      = State.paused;
                _PausedAt = DateTime.Now;
                OnPaused?.Invoke();
                break;
            }

            _State = next;
        }
예제 #7
0
        /// <summary>
        /// Run code in a new worker thread. WorkerDelegate should return true to end, false to repeat.
        /// </summary>
        /// <param name="worker">Delegate to be run</param>
        public void Start(WorkerDelegate worker)
        {
            if (IsRunning)
            {
                return;
            }

            var frame  = new StackFrame(1);
            var method = frame.GetMethod();
            var type   = method.DeclaringType;
            var ns     = type != null ? type.Namespace : string.Empty;

            _worker = worker;
            _thread = new Thread(SafeWorkerDelegate)
            {
                Name         = string.Format("Worker: {0}.{1}", ns, type),
                IsBackground = true,
                Priority     = ThreadPriority.BelowNormal,
            };

            Logger.Debug("Starting {0} Thread Id={1}", _thread.Name, _thread.ManagedThreadId);

            _working = true;
            _thread.Start();

            OnStarted.Invoke();
        }
예제 #8
0
        public override void Start()
        {
            try
            {
                if (Listener?.Running == true)
                {
                    return;
                }

                bool ret = connected ? true : Connect(ConnectTimeout);

                if (ret)
                {
                    Listener = new TcpListener(this);
                    Listener.Start();
                }

                if (Listener?.Running == true)
                {
                    OnStarted?.Invoke(new NetClientEventArgs <ITcpConnection>(this));
                }
            }
            catch (Exception ex)
            {
                OnException?.Invoke(new NetClientEventArgs <ITcpConnection>(this)
                {
                    Exception = ex
                });

                if (!connected)
                {
                    throw ex;
                }
            }
        }
 /// <summary>
 /// Overrides the child node's result
 /// </summary>
 /// <param name="result">The result to override the child node's result</param>
 public BehaviourResultOverrider(bool result) : base("ResultOverrider", NodeType.DECORATOR)
 {
     m_result = result;
     OnStarted.AddListener(OnStarted_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
 }
예제 #10
0
 public void StartListening(string ip, string port)
 {
     _webSocketServer = new WebSocketServer($"ws://{ip}:{port}");
     AddWsServerService();
     _webSocketServer.Start();
     OnStarted?.Invoke(this, EventArgs.Empty);
 }
예제 #11
0
        public void Start(IPAddress address, int port)
        {
            if (IsClosing || IsWorking)
            {
                throw new InvalidOperationException("Listener must be closed before executing Start method.");
            }
            if (address is null || port == 0)
            {
                throw new ArgumentNullException();
            }

            OnStarting?.Invoke(this, new ListenerEventArgs {
                Server = this, UtcTime = DateTime.UtcNow
            });

            // IP Check
            if (
                NetworkInterface
                .GetAllNetworkInterfaces()
                .Where(interf =>
                       interf.OperationalStatus == OperationalStatus.Up)
                .Select(interf => new
            {
                uni = interf.GetIPProperties().UnicastAddresses,
                multi = interf.GetIPProperties().MulticastAddresses
            })
                .Where(item =>
                       item.uni.Where(ip => ip.Address == address).Count() > 0 ||
                       item.multi.Where(ip => ip.Address == address).Count() > 0
                       )
                .Count() == 0
                )
            {
                throw new ArgumentException("This IP address isn't assigned to active interface");
            }

            IPEndPoint endpoint = new IPEndPoint(address, port);

            this.socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            this.socket.Bind(endpoint);
            this.socket.Listen(50);

            CurrentPassword = GeneratePassword();

            OnStarted.Invoke(
                this,
                new ListenerEventArgs {
                Server = this, UtcTime = DateTime.UtcNow
            }
                );

            new Thread(() =>
            {
                while (!IsClosing)
                {
                    socket.BeginAccept(new AsyncCallback(AcceptCallback), socket);
                }
            });
        }
예제 #12
0
        internal override void InvokeEvent(ServerType type, IConnection conn, IMessage msg)
        {
            switch (type)
            {
            case ServerType.Started:
                OnStarted?.Invoke(conn, msg);
                break;

            case ServerType.Accepted:
                OnAccepted?.Invoke(conn, msg);
                break;

            case ServerType.Sended:
                OnSended?.Invoke(conn, msg);
                break;

            case ServerType.Received:
                OnRecieved?.Invoke(conn, msg);
                break;

            case ServerType.Disconnected:
                OnDisconnected?.Invoke(conn, msg);
                break;

            case ServerType.Stopped:
                OnStopped?.Invoke(conn, msg);
                break;
            }
        }
 /// <summary>
 /// Inverts the child node result.
 /// </summary>
 /// <param name="child">The child node</param>
 public BehaviourInverter(BehaviourNode child) : base("Inverter", NodeType.DECORATOR)
 {
     AddChild(child);
     OnStarted.AddListener(OnStarted_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
 }
예제 #14
0
 public override void Start(int port)
 {
     Port = port;
     try { base.Start(port); }
     catch (Exception error) { throw error; }
     OnStarted?.BeginInvoke(result => { try { OnStarted.EndInvoke(result); } catch { } }, null);
 }
예제 #15
0
        public void Start()
        {
            clientList = new List <TcpClient>();

            listener = new TcpListener(ipEndPoint);
            listener.Start();

            alive = true;

            runner = new Thread(new ThreadStart(Run));
            runner.IsBackground = true;
            runner.Name         = "Tcp Listener Runner";
            runner.Start();
            while (!runner.IsAlive)
            {
                Thread.Sleep(10);
            }

            acceptor = new Thread(new ThreadStart(Accept));
            acceptor.IsBackground = true;
            acceptor.Name         = "Tcp Listener Acceptor";
            acceptor.Start();
            while (!acceptor.IsAlive)
            {
                Thread.Sleep(10);
            }

            if (OnStarted != null)
            {
                OnStarted.Invoke();
            }
        }
예제 #16
0
 /// <summary>
 /// The root node of a tree
 /// </summary>
 /// <param name="name"></param>
 public BehaviourRootNode(string name = "Root") : base(name, NodeType.DECORATOR)
 {
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnStoppingSilent.AddListener(OnStoppingSilent_Listener);
     OnStarted.AddListener(OnStarted_Listener);
     OnStartedSilent.AddListener(OnStartedSilent_Listener);
 }
예제 #17
0
 public IGraphPath FindPath()
 {
     OnStarted?.Invoke(this, new AlgorithmEventArgs());
     OnVertexVisited?.Invoke(this, new AlgorithmEventArgs());
     OnVertexEnqueued?.Invoke(this, new AlgorithmEventArgs());
     OnFinished?.Invoke(this, new AlgorithmEventArgs());
     return(new NullGraphPath());
 }
 private void MessagingStartedHandle(MessagingStartedData value)
 {
     synchronization.Post(async state =>
     {
         var connection = await CreateConnectionAsync(myId, value.SecurityKey);
         OnStarted?.Invoke(this, new StartMessagingConnectionEventArgs(connection, value.UserId));
     }, value);
 }
예제 #19
0
 public BehaviourSequenceSelectBase(string name, bool isRandom) : base(name, NodeType.COMPOSITE)
 {
     IsRandom = isRandom;
     OnStarted.AddListener(OnStarted_Listener);
     OnStartedSilent.AddListener(OnStartedSilent_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
 }
예제 #20
0
        private async Task Start()
        {
            CurrentPhase = Phase.Running;
            if (_users.Count <= 1)
            {
                foreach (var user in _users)
                {
                    if (user.Bet > 0)
                    {
                        await _currency.AddAsync(user.UserId, "Race refund", user.Bet).ConfigureAwait(false);
                    }
                }

                var _sf = OnStartingFailed?.Invoke(this);
                CurrentPhase = Phase.Ended;
                return;
            }

            var _  = OnStarted?.Invoke(this);
            var _t = Task.Run(async() =>
            {
                var rng = new NadekoRandom();
                while (!_users.All(x => x.Progress >= 60))
                {
                    foreach (var user in _users)
                    {
                        user.Progress += rng.Next(1, 11);
                        if (user.Progress >= 60)
                        {
                            user.Progress = 60;
                        }
                    }

                    var finished = _users.Where(x => x.Progress >= 60 && !FinishedUsers.Contains(x))
                                   .Shuffle();

                    FinishedUsers.AddRange(finished);

                    var _ignore = OnStateUpdate?.Invoke(this);
                    await Task.Delay(2500).ConfigureAwait(false);
                }

                var win_amount = 0;

                foreach (var u in FinishedUsers)
                {
                    win_amount += (int)u.Bet;
                }

                if (FinishedUsers[0].Bet > 0)
                {
                    await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", win_amount)
                    .ConfigureAwait(false);
                }

                var _ended = OnEnded?.Invoke(this);
            });
        }
예제 #21
0
        void StartSystem()
        {
            for (int i = 0; i < _systems.Count; ++i)
            {
                _systems[i].StartSystem(this);
            }

            OnStarted?.Invoke();
        }
예제 #22
0
 public void Init(float seconds, float randomVariance)
 {
     this.WaitSeconds    = seconds;
     this.randomVariance = randomVariance;
     OnStarted.AddListener(OnStarted_Listener);
     OnStartedSilent.AddListener(OnStartedSilent_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnStoppingSilent.AddListener(OnStoppingSilent_Listener);
 }
        public static async void Start(IConfigurationRoot configuration, IServiceProvider services)
        {
            SystemController.configuration = configuration;
            SystemController.services      = services;

            if (Boolean.Parse(configuration["FirstRun"]))
            {
                if (!firstRun)
                {
                    firstRun = true;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("\nWelcome to MyNodes.NET. \nPlease configure the system in the web interface.\n");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }

                return;
            }

            if (systemControllerStarted)
            {
                return;
            }
            systemControllerStarted = true;



            //read settings
            ReadConfig();


            await Task.Run(() =>
            {
                //waiting for starting web server
                Thread.Sleep(500);

                logs.AddSystemInfo("---------------- STARTING ------------------");

                if (nodesDb == null)
                {
                    ConnectToDB();
                }

                if (gateway == null)
                {
                    ConnectToGateway();
                }

                if (nodesEngine == null)
                {
                    StartNodesEngine();
                }

                logs.AddSystemInfo("------------- SARTUP COMPLETE --------------");

                OnStarted?.Invoke();
            });
        }
예제 #24
0
 public BotDoSeek(BotLocomotive botLocomotiveComponent,
                  Bot.DistanceType stopMovementCondition = Bot.DistanceType.INTERACTION,
                  string name = NODE_NAME) : base(name)
 {
     BotLocomotiveComponent = botLocomotiveComponent;
     StopMovementCondition  = stopMovementCondition;
     _multiFrameFunc        = DoSeek;
     OnStarted.AddListener(DoSeekOnStarted_Listener);
 }
예제 #25
0
 public BehaviourRepeatUntil(Func <bool> isConditionMetFunc) : base(NODE_NAME, NodeType.DECORATOR)
 {
     m_isConditionMetFunc = isConditionMetFunc;
     OnStarted.AddListener(OnStarted_Listener);
     OnStartedSilent.AddListener(OnStartedSilent_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnStoppingSilent.AddListener(OnStoppingSilent_Listener);
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
     OnChildNodeStoppedSilent.AddListener(OnChildNodeStoppedSilent_Listener);
 }
 private void MessagingStartingHandle(MessagingStartingData value)
 {
     synchronization.Post(async state =>
     {
         var securityKey = GenerateSecurityKey();
         var connection  = await CreateConnectionAsync(myId, securityKey);
         await roomConnection.StartMessagingAsync(value.UserId, securityKey);
         OnStarted?.Invoke(this, new StartMessagingConnectionEventArgs(connection, value.UserId));
     }, value);
 }
예제 #27
0
 /// <summary>
 /// Setup and run the story using the parents cancellationTokenSource & refreshRate
 /// </summary>
 /// <returns></returns>
 public void Start(CancellationTokenSource cancellationTokenSource, RefreshRate refreshRate)
 {
     RefreshRate             = refreshRate;
     StepCount               = (int)Duration.TotalMilliseconds / (int)RefreshRate;
     CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token);
     Setup();
     State = StoryState.Running;
     OnStarted?.Invoke(this, EventArgs.Empty);
     Begin();
 }
예제 #28
0
        public void Start(int bot)
        {
            if (!_run)
            {
                if (_wordlist == null)
                {
                    throw new Exception("Wordlist is null.");
                }
                if (!_wordlist.HasNext)
                {
                    throw new Exception("Wordlist is null.");
                }

                _theEnd = false;
                _run    = true;

                _threadList.Clear();

                _bot = bot;
                if (_bot > _wordlist.Count - _position)
                {
                    _bot = _wordlist.Count - _position;
                }

                _runnerStatus = RunnerStatus.Started;
                try { OnStarted?.Invoke(this, new StartEventArgs()
                    {
                        Bot = _bot
                    }); } catch (Exception ex) { OnException?.Invoke(this, new ExceptionEventArgs()
                    {
                        Location = "OnStarted", Exception = ex, Log = _log
                    }); }

                _stopwatch.Restart();
                _stopwatch.Start();

                _cts = new CancellationTokenSource();

                for (int i = 0; i < _bot; i++)
                {
                    int    num    = i;
                    Thread thread = new Thread(() => { Config(num, _cts.Token); })
                    {
                        IsBackground = true, Name = $"ID{num}"
                    };
                    thread.Start();
                    _threadList.Add(thread);
                }

                new Thread(() => { CompletedTask(); })
                {
                    IsBackground = true
                }.Start();
            }
        }
예제 #29
0
        /// <summary>
        /// Run child nodes in parallel
        /// </summary>
        /// <param name="successStopCondition">
        /// How many children should return success before parallel stops with success
        /// </param>
        /// <param name="failureStopCondition">
        /// How many children should return failure before parallel stops with failure
        /// </param>
        public BehaviourParallel(StopCondition successStopCondition, StopCondition failureStopCondition) : base("Parallel", NodeType.COMPOSITE)
        {
            m_successStopCondition = successStopCondition;
            m_failureStopCondition = failureStopCondition;

            OnStarted.AddListener(OnStarted_Listener);
            OnStartedSilent.AddListener(OnStartedSilent_Listener);
            OnStopping.AddListener(OnStopping_Listener);
            OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
            OnChildNodeStoppedSilent.AddListener(OnChildNodeStoppedSilent_Listener);
        }
예제 #30
0
파일: GameTimer.cs 프로젝트: lunacys/lunge
        public void Start()
        {
            if (Math.Abs(Interval) < 0.001)
            {
                return;
            }

            OnStarted?.Invoke(this, new GameTimerEventArgs(TotalSeconds, Interval));
            IsStopped = false;
            IsStarted = true;
        }