/// <summary>
        /// Insert terminal message into queue if it doesn't exist in queue and so on.
        /// </summary>
        /// <param name="terminalMessage"></param>
        public void InsertOrUpdate(TerminalMessage terminalMessage)
        {
            // Find command in existing queue.
            var instance = FindCommandInQueue(terminalMessage.CommandSequence, terminalMessage.CommandIndex);

            // Command doesn't exist in queue.
            if (instance == null)
            {
                // Insert command in queue.
                CommandsQueue.Add(terminalMessage);
                return;
            }

            // Update the command.
            instance.CommandSequence = terminalMessage.CommandSequence;
            instance.CommandIndex    = terminalMessage.CommandIndex;
            instance.Command         = terminalMessage.Command;
            instance.Status          = terminalMessage.Status;
            instance.From            = terminalMessage.From;
            instance.To        = terminalMessage.To;
            instance.PalletNo  = terminalMessage.PalletNo;
            instance.Filter    = terminalMessage.Filter;
            instance.Date      = terminalMessage.Date;
            instance.Sent      = terminalMessage.Sent;
            instance.IsAck     = terminalMessage.IsAck;
            instance.SentCount = terminalMessage.SentCount;
        }
Esempio n. 2
0
        /// <summary>
        /// Request set SRB1 for board
        /// </summary>
        public bool RequestSetSrb1(int board, bool enable)
        {
            if (BoardSettings == null || (!BoardSettings.IsValid && BoardSettings.Boards.Count() < board))
            {
                return(false);
            }

            //  this is the board configuration index, not the board ID
            switch (board)
            {
            case 0:
                StartSrb1CytonSet = enable;
                break;

            case 1:
                StartSrb1DaisySet = enable;
                break;
            }

            var channel       = BoardSettings.Boards[board].Channels[0];
            var setSrb1String = FormatSetSrb1String(channel, enable);

            CommandsQueue.Enqueue(setSrb1String);
            return(true);
        }
        /// <summary>
        /// Initializes the simulation and its datamembers.
        /// </summary>
        /// <param name="roomSize"></param>
        /// <param name="startPosition"></param>
        /// <param name="commands"></param>
        /// <param name="entityBody"></param>
        /// <returns></returns>
        public override int Initialize(string roomSize, string startPosition, string commands, Body entityBody)
        {
            if (_isLogging) Console.WriteLine("Initializing simulation.");
            try
            {
                string[] roomData = Helper.Parse(roomSize);
                string[] carData = Helper.Parse(startPosition);
                string[] carCommands = Helper.Parse(commands, true);

                int roomWidth = Int32.Parse(roomData[0]);
                int roomHeight = Int32.Parse(roomData[1]);
                int carStartX = Int32.Parse(carData[0]);
                int carStartY = Int32.Parse(carData[1]);

                _car = new Car(carStartX, carStartY, (CarBody)entityBody, carData[2][0], _isLogging);

                CommandsQueue = new CommandsQueue(carCommands.Length);
                _room = new Room(roomWidth, roomHeight, _car, _isLogging);
                foreach (string command in carCommands)
                {
                    CommandsQueue.Enqueue(new CarCommand(command[0]));
                }
            }
            catch (IsNotEnumException e) {
                Console.WriteLine("Simulation error in Initialize.\n" + e.Message);
                return -1;
            }
            catch (Exception) {
                Console.WriteLine("Simulation error in Initialize.");
                return -1;
            }
            return  0;
        }
Esempio n. 4
0
        public async Task Loop()
        {
            string      errMsg = string.Empty;
            BoardStatus oldStatus = null, latestStatus;

            if (!TestBoard(_config.PortName, ref _ic, ref version, ref errMsg))
            {
                AppLog.Error("{0}. {1}", "Connect to board fail", errMsg);
                await Task.Delay(ERROR_DELAY);

                return;
            }
            PrintBoardInfo(_ic, version);

            AppLog.Info("Authenticating...");
            _jwt = await Login(_ic, _config.Secret);

            AppLog.Info("Authenticated");

            await Subscribe(_jwt);

            while (true)
            {
                latestStatus = ReadBoardStatus(ref errMsg);
                if (latestStatus is null || !string.IsNullOrEmpty(errMsg))
                {
                    AppLog.Error("{0}. {1}", "Can't read board's status", errMsg);
                    break;
                }

                if (latestStatus != oldStatus)
                {
                    Console.WriteLine("Previous status:");
                    Console.WriteLine(oldStatus);
                    Console.WriteLine("New status:");
                    Console.WriteLine(latestStatus);
                    SendStatus(latestStatus);
                    oldStatus = latestStatus;
                }

                if (IsCommandAvailable())
                {
                    lock (CommandsQueue)
                    {
                        var safe = CommandsQueue.Dequeue();
                        if (!ExecuteCommand(safe, ref errMsg))
                        {
                            AppLog.Error("{0}. {1}", "Execute command fail", errMsg);
                        }
                        else
                        {
                            AppLog.Info("Opened Safe:{0}", safe);
                        }
                    }
                }

                await Task.Delay(LOOP_DELAY);
            }
        }
Esempio n. 5
0
 protected override void OnDestroy()
 {
     foreach (NativeQueue <COMMAND> CommandsQueue in CommandsQueues)
     {
         CommandsQueue.Dispose();
     }
     CommandsMap.Dispose();
 }
        /// <summary>
        /// Remove command by using specific condition.
        /// </summary>
        /// <param name="condition"></param>
        public void RemoveCommand(Func <TerminalMessage, bool> condition)
        {
            var command = CommandsQueue.FirstOrDefault(condition);

            if (command != null)
            {
                CommandsQueue.Remove(command);
            }
        }
Esempio n. 7
0
 internal void ResetMode()
 {
     AddMode          = false;
     EditMode         = false;
     RemoveMode       = false;
     UpdateUseridMode = false;
     VoteMode         = false;
     EventAddMode     = false;
     CommandsQueue.Clear();
 }
        /// <summary>
        /// Remove command from cache.
        /// </summary>
        /// <param name="commandSequence"></param>
        /// <param name="commandIndex"></param>
        public void RemoveCommand(string commandSequence, string commandIndex)
        {
            var command =
                CommandsQueue.FirstOrDefault(
                    x =>
                    x.CommandSequence.Equals(commandSequence, StringComparison.InvariantCultureIgnoreCase) &&
                    x.CommandIndex.Equals(commandIndex, StringComparison.InvariantCultureIgnoreCase));

            if (command != null)
            {
                CommandsQueue.Remove(command);
            }
        }
Esempio n. 9
0
 public void Stop(Action callback)
 {
     StopServer();
     this.paquetQueue.ContinueWith((pq) =>
     {
         apiTaskQuee.ContinueWith(aq =>
         {
             CommandsQueue.ContinueWith(cq =>
             {
                 try { callback(); } catch { }
             });
         });
     });
 }
Esempio n. 10
0
 public virtual void Dispose(Action callback = null)
 {
     try
     {
         Listener.Stop();
         Listener.Close();
         ApiHandler.Dispose();
         services.Clear();
         Serializers.Clear();
         paquetQueue.Dispose();
         CommandsQueue.Dispose();
         apiTaskQuee.Dispose();
     }
     catch { }
     callback?.Invoke();
 }
Esempio n. 11
0
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != null)
        {
            Destroy(gameObject);
        }
        DontDestroyOnLoad(gameObject);


        nowTurn                     = 0;
        commandsReceved             = new CommandsQueue();
        Application.targetFrameRate = 30;
        this.networkManager         = GameObject.Find("NetworkManager").GetComponent <CNetworkManager>();
    }
Esempio n. 12
0
        public async Task Subscribe(string jwt)
        {
            await Task.WhenAny(Task.Delay(TIME_OUT), Task.Run(async() =>
            {
                AppLog.Info("Connecting to server...");
                var options            = new IO.Options();
                options.Query          = new Dictionary <string, string>();
                options.Query["token"] = jwt;
                options.Reconnection   = true;
                _socket = IO.Socket(_config.ServerUrl, options);
                _socket.On(Socket.EVENT_CONNECT, () =>
                {
                    AppLog.Info("Connected to server");
                });
                _socket.On(Socket.EVENT_RECONNECTING, () =>
                {
                    AppLog.Info("Reconnecting to server...");
                });
                _socket.On(EVENT_OPEN, (payload) =>
                {
                    int idNo = Convert.ToInt32(payload);
                    AppLog.Info("Received command open lock: {0}", idNo);
                    lock (CommandsQueue)
                    {
                        CommandsQueue.Enqueue(idNo);
                    }
                });

                // wait for connect to server
                while (_socket.Io().ReadyState != Manager.ReadyStateEnum.OPEN)
                {
                    await Task.Yield();
                }
            }));

            if (_socket.Io().ReadyState != Manager.ReadyStateEnum.OPEN)
            {
                throw new Exception("Open socket timeout.");
            }
        }
Esempio n. 13
0
        protected virtual bool OnRequest(HttpListenerContext context)
        {
            if (context.Request.HttpMethod == "OPTIONS")
            {
                ApisHandler.RespondOptions(context);
                return(true);
            }
            context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            var user = ApiHandler.CheckAuth(context, out bool logged);

            if (user != null || logged)
            {
                var serviceArgs = RequestArgs.NewRequestArgs(context, this, user);

                if (serviceArgs.Service == null)
                {
                    serviceArgs.SendCode(HttpStatusCode.OK);
                }
                else if (serviceArgs.Service.CanbeDelayed(serviceArgs))
                {
                    CommandsQueue.Add(new CommandsParam(serviceArgs, ExecuteCommand, this));
                    return(false);
                }
                else
                {
                    using (serviceArgs)
                    {
                        Api(serviceArgs);
                        return(!serviceArgs.IsBusy);
                    }
                }
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            }
            return(true);
        }
Esempio n. 14
0
 static void Main(string[] args)
 {
     CommandsQueue.RunTest();
 }
Esempio n. 15
0
 public async Task <R> Send <R>(CommandMessage cmd) where R : CommandResponse, new()
 => await CommandsQueue.Enqueue(() => SendCommand <R>(cmd));
Esempio n. 16
0
 public void Dispose()
 => CommandsQueue.Dispose();
Esempio n. 17
0
 public async Task Run()
 => await CommandsQueue.Wait();
 /// <summary>
 /// Clear the queue.
 /// </summary>
 public void ClearQueue()
 {
     CommandsQueue.Clear();
 }
 /// <summary>
 /// Delete terminal message from queue.
 /// </summary>
 /// <param name="terminalMessage"></param>
 public void Delete(TerminalMessage terminalMessage)
 {
     CommandsQueue.Remove(terminalMessage);
 }
 /// <summary>
 /// Insert terminal message into queue.
 /// </summary>
 /// <param name="terminalMessage"></param>
 public void Insert(TerminalMessage terminalMessage)
 {
     CommandsQueue.Add(terminalMessage);
 }
 /// <summary>
 ///     Find command in queue.
 /// </summary>
 /// <param name="commandSeq"></param>
 /// <param name="commandIndex"></param>
 /// <returns></returns>
 public TerminalMessage FindCommandInQueue(string commandSeq, string commandIndex)
 {
     return(CommandsQueue.FirstOrDefault(x => x.CommandSequence == commandSeq && x.CommandIndex == commandIndex));
 }
        private void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;

            while (true)
            {
                if (bw.CancellationPending)
                {
                    break;
                }
                Thread.Sleep(5);

                //如果没有指令,继续等待
                if (CommandsQueue.Count == 0)
                {
                    Thread.Sleep(50);
                    continue;
                }

                //从队列中将指令取出
                CommandInfo info  = CommandsQueue.Dequeue() as CommandInfo;
                string      value = info.Command.Trim('\0');
                //SetValue(value, info.Client.Client);

                //如果设备未连接,通知客户端
                if (testDevice == null || !testDevice.IsOpen)
                {
                    ServerResultMessage _ServerResultMessage = new ServerResultMessage()
                    {
                        CommandType = CommandType.None,
                        ResultCode  = ResultCode.fail,
                        Data        = "device is disconnect.",
                    };
                    SendData(info, JsonConvert.SerializeObject(_ServerResultMessage));
                    Thread.Sleep(1000);
                    continue;
                }

                ResetType result = ResetType.None;
Start:
                try
                {
                    Command(value, info);
                }
                catch (MotorException ex)
                {
                    Loghelper.WriteLog("发送指令:", ex);
                    switch (result)
                    {
                    case ResetType.None:
                        lock (deviceLock)
                            result = device.ResetComUSB();
                        if (result == ResetType.USBSuccess || result == ResetType.Success)
                        {
                            goto Start;
                        }
                        break;

                    case ResetType.USBSuccess:
                        lock (deviceLock)
                            result = device.ResetCom();
                        if (result == ResetType.Success)
                        {
                            goto Start;
                        }
                        break;

                    case ResetType.Error:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Loghelper.WriteLog("下发错误", ex);
                    ServerResultMessage _ServerResultMessage = new ServerResultMessage()
                    {
                        CommandType = CommandType.None,
                        ResultCode  = ResultCode.fail,
                        Data        = ex.Message,
                    };
                    SendData(info, JsonConvert.SerializeObject(_ServerResultMessage));
                }
                //SetValue(string.Format("队列还剩【{0}】条指令未下发", CommandsQueue.Count), null);
            }
        }