Пример #1
0
        public void Write()
        {
            if (stopwatch.IsRunning)
            {
                stopwatch.Start();
            }

            TimeSpan ts;

            while (run)
            {
                ts = stopwatch.Elapsed;
                string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                   ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                tw.WriteLine("{0},{1}", elapsedTime, source.GetData());
                NetworkTable table = NetworkTable.GetTable("cheetos");
                table.PutString("Data", string.Format("{0},{1}", elapsedTime, source.GetData()));
                SmartConsole.PrintInfo(string.Format("{0},{1}", elapsedTime, source.GetData()));
            }
        }
Пример #2
0
        /// <summary>
        /// Runs the auto handler.
        /// </summary>
        protected override void Main()
        {
            Right1.SetEncoderPostition(0); // Reset the encoder position to 0.
            Left1.SetEncoderPostition(0);  // Reset the eoncoder position to 0.
            // Runs the selected autonomous.
            //AutoHandler.RunAuto(Handler.AutoPosition.Disabled);
            // Both down. 0b00
            if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5)
            {
                SmartConsole.PrintInfo("Currently running disabled autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                AutoHandler.RunAuto(Handler.AutoPosition.Disabled);
            }
            // Left stick down, right stick up. 0b01
            else if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5)
            {
                SmartConsole.PrintInfo("Currently running position 1 autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                AutoHandler.RunAuto(Handler.AutoPosition.Position1);
            }
            // Left stick up, right stick down. 0b10
            else if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5)
            {
                SmartConsole.PrintInfo("Currently running position 2 autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                AutoHandler.RunAuto(Handler.AutoPosition.Position2);

                /*DriveTrain.Move(.65, .70);
                 *
                 * Snooze(2500);
                 *
                 * DriveTrain.StopMotor();
                 *
                 * GearSlot.Set(true);
                 *
                 * while (true) Snooze(1);*/
            }
            // Left stick up, right stick up. 0b11
            else if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5)
            {
                SmartConsole.PrintInfo("Currently running position 3 autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                AutoHandler.RunAuto(Handler.AutoPosition.Position3);
            }
        }
Пример #3
0
        /// <summary>
        ///     Status is sent by everyone as Keep-alive message
        /// </summary>
        /// <param name="messagePackage"></param>
        private void handleStatusMessage(MessagePackage messagePackage)
        {
            StatusMessage message = (StatusMessage)messagePackage.Message;

            // check what node
            lock (clientTracker.lockObject)
            {
                NetworkNode networkNode = clientTracker.GetNodeByID(message.Id);

                networkNode.LastSeen = DateTime.Now;

                UpdateThreadsStatus(networkNode, message);

                // inform backup
                if (networkNode.Type != RegisterType.CommunicationServer)
                {
                    InformBackup(message);
                }

                //if status message was send by TaskManager than check if there are any tasks to divide or merge
                if (networkNode.Type == RegisterType.TaskManager)
                {
                    //Response to TaskManager statusMessage
                    ReactToTaskManagerStatusMessage(networkNode, messagePackage);
                }
                //is staty message was send by computational node than check if there are any partial problems to calculate.
                else if (networkNode.Type == RegisterType.ComputationalNode)
                {
                    ReactToComputationalNodeStatusMessage(networkNode, messagePackage);
                }
                else
                {
                    if (Server.primaryMode)
                    {
                        NoOperationMessage response = new NoOperationMessage(clientTracker.BackupServers);
                        server.Send(messagePackage.Socket, response);
                        SmartConsole.PrintLine("Sent a NoOperation Message", SmartConsole.DebugLevel.Basic);
                    }
                }
            }
        }
Пример #4
0
        /*******************************************************************/
        /************************ PRIVATE METHODS **************************/
        /*******************************************************************/

        private void keepAlive(Object source, ElapsedEventArgs e)
        {
            SmartConsole.PrintLine("Sending Status message", SmartConsole.DebugLevel.Basic);

            try
            {
                Communicate(node.ToStatusMessage());
            }
            catch (SocketException excep)
            {
                if (clientTracker.BackupServers.Length == 0)
                {
                    SmartConsole.PrintLine("No other backup server avaiable", SmartConsole.DebugLevel.Advanced);
                    return;
                }
                BackupCommunicationServer bserver = clientTracker.BackupServers[0];

                // If it is next backup server, switch to primary and remove it from the list
                if (server.Address.ToString().Equals(bserver.address) && server.Port == bserver.port)
                {
                    // TODO Switch only if it is next back up in the list, and decreament the list it self
                    SmartConsole.PrintLine("Switching to primary...", SmartConsole.DebugLevel.Advanced);
                    // stop the timer
                    this.Stop();

                    clientTracker.RemoveBackupServer(0);

                    lock (backupBlockade)
                    {
                        Monitor.Pulse(backupBlockade);
                    }
                    return;
                }
                // connect to next backup server.
                else
                {
                    client.Address = IPAddress.Parse(bserver.address);
                    client.Port    = bserver.port;
                }
            }
        }
Пример #5
0
        /*******************************************************************/
        /************************ PRIVATE METHODS **************************/
        /*******************************************************************/

        /*******************************************************************/
        /************************* PUBLIC METHODS **************************/
        /*******************************************************************/
        public void InitiatePrimary(IPAddress address, int port)
        {
            SmartConsole.PrintHeader("Starting primary server");
            SmartConsole.PrintLine("Address: " + address.ToString() + ":" + port, SmartConsole.DebugLevel.Advanced);

            // Create overall system tracker
            SystemTracker systemTracker = new SystemTracker();

            // Create list of all clients
            ClientTracker clientTracker = new ClientTracker();

            // Start measuring timeout
            clientTracker.StartTimeout();

            // Task Tracker
            TaskTracker taskTracker = new TaskTracker();

            // Start network connection
            NetworkServer server = new NetworkServer(address, port);

            server.Open();

            // Create messageHandler
            MessageHandler messageHandler = new MessageHandler(systemTracker, clientTracker, taskTracker, server);

            // Start message queue
            MessageQueue messageQueue = new MessageQueue(server);

            messageQueue.Start();

            // Start Message processor
            CommunicationServer.MessageCommunication.MessageProcessor messageProcessor = new CommunicationServer.MessageCommunication.MessageProcessor(messageQueue, messageHandler);
            messageProcessor.Start();

            Thread.Sleep(100);

            // Start console manager
            ConsoleManager consoleManager = new ConsoleManager(server);

            consoleManager.Start();
        }
Пример #6
0
        /// <summary>
        /// this function is a response to Computational Node status message
        /// </summary>
        /// <param name="networkNode"></param>
        /// <param name="messagePackage"></param>
        private void ReactToComputationalNodeStatusMessage(NetworkNode networkNode, MessagePackage messagePackage)
        {
            bool messageCheck = false;

            for (int i = 0; i < taskTracker.Tasks.Count; i++)
            {
                if (taskTracker.Tasks[i].Status == Cluster.TaskStatus.Divided && taskTracker.Tasks[i].Type == networkNode.SolvableProblems[0])
                {
                    //  REMEBER TO CHECK IF THERE IS A AVALIABLE THREAD ******************************************************************************************************
                    // check number of avaliable threads
                    int avaliableThreads = AvaliableThreadsCount(networkNode);
                    List <PartialProblem> partialList = new List <PartialProblem>();
                    for (int j = 0; j < taskTracker.Tasks[i].subTasks.Count && avaliableThreads > 0; j++)
                    {
                        if (taskTracker.Tasks[i].subTasks[j].Status == Cluster.TaskStatus.New)
                        {
                            avaliableThreads--;
                            partialList.Add(new PartialProblem((ulong)taskTracker.Tasks[i].ID, taskTracker.Tasks[i].subTasks[j].BaseData, (ulong)(0)));
                            taskTracker.Tasks[i].subTasks[j].Status = Cluster.TaskStatus.Solving;
                            // temporary solution @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                        }
                    }
                    if (partialList.Count > 0)
                    {
                        messageCheck = SendPartialProblemsMessage(i, partialList, messagePackage);
                    }
                    if (messageCheck)
                    {
                        break;
                    }
                }
            }
            if (messageCheck == false && Server.primaryMode)
            {
                NoOperationMessage response = new NoOperationMessage(clientTracker.BackupServers);
                server.Send(messagePackage.Socket, response);

                SmartConsole.PrintLine("Sent a NoOperation Message. 0 subTasks to divide or 0 apropriate computationalNodes", SmartConsole.DebugLevel.Basic);
            }
        }
Пример #7
0
        private T Punish <T>(string parameters) where T : ElevatedAccessUserBasePunishEvent, new()
        {
            string str  = string.Empty;
            string str2 = string.Empty;

            try
            {
                char[] separator = new char[] { ' ' };
                str = parameters.Split(separator)[1];
                char[] chArray2 = new char[] { ' ' };
                str2 = parameters.Split(chArray2)[2];
            }
            catch (Exception)
            {
                SmartConsole.WriteLine("Wrong parameters");
                return(null);
            }
            T local2 = Activator.CreateInstance <T>();

            local2.Uid    = str;
            local2.Reason = str2;
            return(local2);
        }
Пример #8
0
        /// <summary>
        /// in this function solution message with solved partial solution is sent (it checks if all subtasks of task are solved.
        /// It returns true in case of completition of sending the message.
        /// </summary>
        /// <param name="numberOfTask"></param>
        /// <param name="node"></param>
        /// <param name="messagePackage"></param>
        /// <returns></returns>
        private bool isMergeSolutionSent(int numberOfTask, NetworkNode node, MessagePackage messagePackage)
        {
            if (taskTracker.Tasks[numberOfTask].Status != Cluster.TaskStatus.Merging && taskTracker.Tasks[numberOfTask].Status != Cluster.TaskStatus.Merged && taskTracker.Tasks[numberOfTask].subTasks.Count != 0)
            {
                for (int j = 0; j < taskTracker.Tasks[numberOfTask].subTasks.Count; j++)
                {
                    if (taskTracker.Tasks[numberOfTask].subTasks[j].Status != Cluster.TaskStatus.Solved)
                    {
                        return(false);
                    }
                }
            }
            else
            {
                return(false);
            }
            if (taskTracker.Tasks[numberOfTask].Type == node.SolvableProblems[0])
            {
                taskTracker.Tasks[numberOfTask].Status = Cluster.TaskStatus.Merging;
                Solution[] solutions = new Solution[taskTracker.Tasks[numberOfTask].subTasks.Count];
                for (int k = 0; k < solutions.Count(); k++)
                {
                    solutions[k] = new Solution(SolutionsSolutionType.Final);
                }
                for (int j = 0; j < taskTracker.Tasks[numberOfTask].subTasks.Count; j++)
                {
                    solutions[j].Data = taskTracker.Tasks[numberOfTask].subTasks[j].Solutions[0].Data;
                }
                SolutionsMessage solutionMessage = new SolutionsMessage(taskTracker.Tasks[numberOfTask].Type, (ulong)taskTracker.Tasks[numberOfTask].ID, taskTracker.Tasks[numberOfTask].CommonData, solutions);

                server.Send(messagePackage.Socket, solutionMessage);

                SmartConsole.PrintLine("Solution Message has been sent to Task Manager", SmartConsole.DebugLevel.Advanced);
                return(true);
            }
            return(false);
        }
Пример #9
0
        public Variable(string _group, string _name, string _description, bool _console)
        {
            group = _group;
            name  = _name;
            if (group != "")
            {
                name = _group + "." + name;
            }

            description = _description;
            if (vars.ContainsKey(name))
            {
                Debug.LogError("InternalConfig: Attempt to register existing variable, aborting.");
                Debug.Break();
            }
            type      = typeof(T);
            console   = _console;
            value     = new T();
            baseValue = value;
            if (console)
            {
                SmartConsole.RegisterVariable(this);
            }


            if (!groups.ContainsKey(group))
            {
                List <VariableBase> list = new List <VariableBase>();
                groups.Add(group, list);
                list.Add(this);
            }
            else
            {
                groups[group].Add(this);
            }
            vars.Add(name, this);
        }
Пример #10
0
        /*******************************************************************/
        /************************ PRIVATE METHODS **************************/
        /*******************************************************************/

        /// <summary>
        ///     Runs the algorithm for configuration given by constructor
        /// </summary>
        private void psLogic()
        {
            SmartConsole.PrintHeader("PREDICTION STRENGTH");

            // 1) get learning and testing set
            //
            splitTrainingData();

            // 2) compute ps for each k and find the best_k
            best_k = 1;
            double max_strength = 0;

            strengths = new double[max_k];

            for (int k = start_k; k <= max_k; k++)
            {
                double strength = psValue(learningSet, testingSet, k);
                strengths[k - start_k] = strength;
                if (k == start_k)
                {
                    max_strength = strength;
                    best_k       = k;
                }
                else if (STRENGTH_TOL < strength)
                {
                    max_strength = strength;
                    best_k       = k;
                }
                SmartConsole.PrintLine("ps(" + k + ") = " + strength, SmartConsole.DebugLevel.Advanced);
            }

            SmartConsole.PrintHeader("PREDICTION STRENGTH FINISHED: ");
            for (int k = start_k; k <= max_k; k++)
            {
                SmartConsole.PrintLine("ps(" + k + ") = " + strengths[k - start_k], SmartConsole.DebugLevel.Advanced);
            }
        }
 public static void CommandBatch(string parameters)
 {
     parameters = parameters.Remove(0, 4);
     if (File.Exists(Storage.modEntryPath + parameters))
     {
         try {
             int      i        = 0;
             string[] commands = File.ReadAllLines(Storage.modEntryPath + parameters);
             foreach (string s in commands)
             {
                 SmartConsole.WriteLine($"[{i}]: {s}");
                 SmartConsole.ExecuteLine(s);
                 i++;
             }
         }
         catch (Exception e) {
             modLogger.Log(e.ToString());
         }
     }
     else
     {
         SmartConsole.WriteLine($"'{parameters}' {Strings.GetText("error_NotFound")}");
     }
 }
Пример #12
0
        protected void CreateUserItem(string parameters)
        {
            long num  = 0L;
            long num2 = 0L;

            try
            {
                char[] separator = new char[] { ' ' };
                num = long.Parse(parameters.Split(separator)[2]);
                char[] chArray2 = new char[] { ' ' };
                num2 = long.Parse(parameters.Split(chArray2)[1]);
            }
            catch (Exception)
            {
                SmartConsole.WriteLine("Wrong parameter");
                return;
            }
            ElevatedAccessUserCreateItemEvent eventInstance = new ElevatedAccessUserCreateItemEvent {
                Count  = num,
                ItemId = num2
            };

            base.ScheduleEvent(eventInstance, this.user);
        }
Пример #13
0
 public static void CommandBatch(string parameters)
 {
     parameters = parameters.Remove(0, 4);
     if (File.Exists(Mod.modEntryPath + parameters))
     {
         try {
             var i        = 0;
             var commands = File.ReadAllLines(Mod.modEntryPath + parameters);
             foreach (var s in commands)
             {
                 SmartConsole.WriteLine($"[{i}]: {s}");
                 SmartConsole.ExecuteLine(s);
                 i++;
             }
         }
         catch (Exception e) {
             Mod.Error(e);
         }
     }
     else
     {
         SmartConsole.WriteLine($"'{parameters}' Not Found");
     }
 }
        /*******************************************************************/
        /************************ PRIVATE METHODS **************************/
        /*******************************************************************/

        private void keepAliveSolution(Object source, ElapsedEventArgs e)
        {
            SmartConsole.PrintLine("Sending SolutionRequestMessage", SmartConsole.DebugLevel.Basic);

            try
            {
                messageProcessor.Communicate(solutionRequestMessage);
            }
            catch (SocketException excep)
            {
                SmartConsole.PrintLine("Lost connection with primary server, reconnecting to next backup...", SmartConsole.DebugLevel.Advanced);

                if (systemTracker.Node.BackupServers.Length == 0)
                {
                    SmartConsole.PrintLine("No other backup server avaiable", SmartConsole.DebugLevel.Advanced);
                    return;
                }
                BackupCommunicationServer bserver = systemTracker.Node.BackupServers[0];

                // connect to next backup server.
                messageProcessor.client.Address = IPAddress.Parse(bserver.address);
                messageProcessor.client.Port    = bserver.port;
            }
        }
Пример #15
0
        /// <summary>
        ///     SolvePartialProblem is sent by TM
        /// </summary>
        /// <param name="messagePackage"></param>
        private void handleSolvePartialProblemsMessage(MessagePackage messagePackage)
        {
            /* add partial tasks to subTask list in a task */
            SolvePartialProblemsMessage message = (SolvePartialProblemsMessage)messagePackage.Message;

            InformBackup(message);

            Task task = taskTracker.GetTask((int)message.Id);

            task.Status = TaskStatus.Divided;
            for (int i = 0; i < message.PartialProblems.Count(); i++)
            {
                Task subTask = new Task((int)message.Id, message.ProblemType, message.PartialProblems[i].Data);
                subTask.Status = TaskStatus.New;
                task.AddSubTask(subTask);
            }
            /***********************************************/
            if (Server.primaryMode)
            {
                NoOperationMessage response = new NoOperationMessage(clientTracker.BackupServers);
                server.Send(messagePackage.Socket, response);
                SmartConsole.PrintLine("Sent a NoOperation Message", SmartConsole.DebugLevel.Basic);
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            /************ Create node object ************/
            RegisterType type            = RegisterType.TaskManager;
            byte         parallelThreads = 5;

            string[] problems = { "DVRP" };

            NetworkNode node = new NetworkNode(type, parallelThreads, problems);
            //NetworkNode node = new NetworkNode();

            /************ Setup connection ************/
            string inputLine = "";

            foreach (string arg in args)
            {
                inputLine += arg + " ";
            }

            InputParser inputParser = new InputParser(inputLine);

            inputParser.ParseInput();

            IPAddress address = inputParser.Address;
            int       port    = inputParser.Port;

            SmartConsole.PrintLine("I'm a " + node.Type, SmartConsole.DebugLevel.Advanced);
            NetworkClient client = new NetworkClient(address, port);

            /************ Setup Logic modules ************/

            // system tracker
            SystemTracker systemTracker = new SystemTracker(node);

            MessageHandler messageHandler = new MessageHandler(systemTracker, client);

            MessageProcessor messageProcessor = new MessageProcessor(messageHandler, client, node);

            node.MessageProcessor = messageProcessor;

            /************ Init all threads ************/
            for (int i = 0; i < parallelThreads; i++)
            {
                node.TaskThreads[i] = new TaskThread(i, problems[0], messageProcessor, (int)node.Id);
            }

            /************ Register ************/
            client.Connect();
            SmartConsole.PrintLine("Sending Register message", SmartConsole.DebugLevel.Advanced);
            messageProcessor.Communicate(node.ToRegisterMessage());

            KeepAliveTimer keepAliveTimer = new KeepAliveTimer(messageProcessor, systemTracker);

            /************ Start Logic modules ************/
            keepAliveTimer.Start();

            Object mutex = new Object();

            // TODO Thread pool waiting

            lock (mutex)
            {
                Monitor.Wait(mutex);
            }
        }
Пример #17
0
        protected override void Main()
        {
#if DEBUG
            SmartConsole.PrintWarning("Robot running in debug mode.");
#endif

            Handler.AutoPosition position = Handler.AutoPosition.Disabled;

            while (true)
            {
                // Both down. 0b00
                if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5)
                {
                    if (!a0)
                    {
                        SmartConsole.PrintInfo("Currently running disabled autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                        position = Handler.AutoPosition.Disabled;
                        //AutoHandler.RunAuto(Handler.AutoPosition.Disabled);
                        a0 = true;
                        a1 = false;
                        a2 = false;
                        a3 = false;
                    }
                }
                // Left stick down, right stick up. 0b01
                else if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5)
                {
                    if (!a1)
                    {
                        SmartConsole.PrintInfo("Currently running side gear (positon 1) autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                        position = Handler.AutoPosition.Position1;
                        //AutoHandler.RunAuto(Handler.AutoPosition.Position1);
                        a0 = false;
                        a1 = true;
                        a2 = false;
                        a3 = false;
                    }
                }
                // Left stick up, right stick down. 0b10
                else if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) < 0.5)
                {
                    if (!a2)
                    {
                        SmartConsole.PrintInfo("Currently running center gear (positon 2) autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                        position = Handler.AutoPosition.Position2;
                        //AutoHandler.RunAuto(Handler.AutoPosition.Position2);
                        a0 = false;
                        a1 = false;
                        a2 = true;
                        a3 = false;
                    }
                }
                // Left stick up, right stick up. 0b11
                else if (DriveStick_Left.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5 && DriveStick_Right.GetAxis(WPILib.Joystick.AxisType.Z) > 0.5 && position != Handler.AutoPosition.Position3)
                {
                    if (!a3)
                    {
                        SmartConsole.PrintInfo("Currently running position 3 autonomous on the " + DriverStation.Instance.GetAlliance() + " alliance.");
                        position = Handler.AutoPosition.Position3;
                        //AutoHandler.RunAuto(Handler.AutoPosition.Position3);
                        a0 = false;
                        a1 = false;
                        a2 = false;
                        a3 = true;
                    }
                }
            }
        }
Пример #18
0
        /*******************************************************************/
        /************************ PRIVATE METHODS **************************/
        /*******************************************************************/

        private void keepAlive(Object source, ElapsedEventArgs e)
        {
            SmartConsole.PrintLine("Sending Solution Request message", SmartConsole.DebugLevel.Basic);
            messageProcessor.Communicate(solutionRequestMessage);
        }
Пример #19
0
 private static void Initialise(SmartConsole instance)
 {
     if (s_textInput == null)
     {
Пример #20
0
        static void Main(string[] args)
        {
            RegisterType type            = RegisterType.ComputationalClient;
            byte         parallelThreads = 5;

            string[] problems = { "DVRP" };

            SolveRequestMessage solveRequestMessage = new SolveRequestMessage();

            string inputLine = "";

            foreach (string arg in args)
            {
                inputLine += arg + " ";
            }

            InputParser inputParser = new InputParser(inputLine);

            inputParser.ParseInput();

            IPAddress address = inputParser.Address;
            int       port    = inputParser.Port;

            NetworkNode node = new NetworkNode(type, parallelThreads, problems)
            {
                Timeout = CLIENT_REQUEST_FREQUENCY
            };



            SmartConsole.PrintLine("ComputationalClient starting work", SmartConsole.DebugLevel.Advanced);

            NetworkClient client = new NetworkClient(address, port);

            for (; ;)
            {
                /*************** Register *****************/

                doWork = true;

                SmartConsole.PrintLine("Type in a file path", SmartConsole.DebugLevel.Advanced);
                String filePath = Console.ReadLine();
                solveRequestMessage = loadDataFromDisc(filePath);

                /******  setup logic modules *****************/
                SystemTracker    systemTracker    = new SystemTracker(node);
                MessageHandler   messageHandler   = new MessageHandler(systemTracker, client);
                MessageProcessor messageProcessor = new MessageProcessor(messageHandler, client, node);
                KeepAliveTimer   keepAliveTimer   = new KeepAliveTimer(messageProcessor, systemTracker);

                messageHandler.keepAliveTimer = keepAliveTimer;

                node.MessageProcessor = messageProcessor;

                /************ send solve request *****************/
                client.Connect();

                messageProcessor.Communicate(solveRequestMessage);
                COMP_TIME = DateTime.Now;

                while (doWork)
                {
                    Thread.Sleep(1000);
                }

                /*Object mutex = new Object();
                 *
                 * lock (mutex)
                 * {
                 *  Monitor.Wait(mutex);
                 * }*/
            }
        }
Пример #21
0
        /*******************************************************************/
        /************************ PRIVATE METHODS **************************/
        /*******************************************************************/

        private void handleNoOperationMessage(NoOperationMessage message)
        {
            systemTracker.Node.BackupServers = message.BackupCommunicationServers;

            SmartConsole.PrintLine("Current Backup count: " + systemTracker.Node.BackupServers.Length, SmartConsole.DebugLevel.Basic);
        }
Пример #22
0
        /******************************************************************/
        /**************************** REGISTER ****************************/
        /******************************************************************/

        /// <summary>
        ///     Removes a node from the server
        /// </summary>
        /// <param name="message"></param>
        /// <param name="socket"></param>
        private void deregisterNode(RegisterMessage message, Socket socket)
        {
            SmartConsole.PrintLine("Deregister received, removing client...", SmartConsole.DebugLevel.Advanced);
            socket.Disconnect(false);
            clientTracker.RemoveNode(message.Id, message.Type);
        }
Пример #23
0
        public void InitiateBackup(IPAddress myAddress, int myPort, IPAddress masterAddress, int masterPort)
        {
            SmartConsole.PrintHeader("Starting backup server");
            SmartConsole.PrintLine("Address: " + myAddress.ToString() + ":" + myPort, SmartConsole.DebugLevel.Advanced);

            // Create overall system tracker
            SystemTracker systemTracker = new SystemTracker();

            // Create list of all clients
            ClientTracker clientTracker = new ClientTracker();

            // Task Tracker
            TaskTracker taskTracker = new TaskTracker();

            // Start network connection
            NetworkServer server = new NetworkServer(myAddress, myPort);

            // Create messageHandler
            MessageHandler messageHandler = new MessageHandler(systemTracker, clientTracker, taskTracker, server);

            // Start message queue
            MessageQueue messageQueue = new MessageQueue(server);

            // Start Message processor
            CommunicationServer.MessageCommunication.MessageProcessor messageProcessor = new CommunicationServer.MessageCommunication.MessageProcessor(messageQueue, messageHandler);

            // blockade to block untill server is switched to primary mode
            Object backupBlockade = new Object();

            server.Open();
            messageQueue.Start();
            messageProcessor.Start();

            /********************* REGISTER AS NORMAL CLIENT *********************/

            RegisterType type = RegisterType.CommunicationServer;
            NetworkNode  node = new NetworkNode(type);

            systemTracker.Node = node;

            NetworkClient client = new NetworkClient(masterAddress, masterPort);

            client.Connect();
            SmartConsole.PrintLine("Sending Register message...", SmartConsole.DebugLevel.Advanced);

            CommunicationServer.MessageCommunication.KeepAliveTimer keepAliveTimer = new
                                                                                     CommunicationServer.MessageCommunication.KeepAliveTimer(messageHandler,
                                                                                                                                             client,
                                                                                                                                             server,
                                                                                                                                             systemTracker,
                                                                                                                                             node,
                                                                                                                                             clientTracker,
                                                                                                                                             backupBlockade);
            keepAliveTimer.Communicate(node.ToRegisterMessage());

            /********************* START COMMUNICATING WITH PRIMARY SERVER *********************/
            SmartConsole.PrintLine("Backup Server starting work", SmartConsole.DebugLevel.Advanced);

            keepAliveTimer.Start();

            // This will hold untill server is switched to primary mode
            lock (backupBlockade)
            {
                Monitor.Wait(backupBlockade);
            }

            /********************* SWITCH TO PRIMARY SERVER *********************/

            SmartConsole.PrintHeader("SWITCHING TO PRIMARY");

            Server.primaryMode = true;

            client.Disconnect();

            clientTracker.RefreshTimeout();

            // Start measuring timeout
            clientTracker.StartTimeout();

            // Start console manager
            ConsoleManager consoleManager = new ConsoleManager(server);

            consoleManager.Start();
        }
Пример #24
0
        private static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.Unicode;
            Console.InputEncoding  = System.Text.Encoding.Unicode;

            BorderCharacters.FromJson(@".\Configs\borderCharacters.json");
            CommandTree.FromJsonFolder(@".\Configs\Commands");
            Settings.FromJson(@".\Configs\settings.json");
            CellBorders.FromJson(@".\Configs\cellBorders.json");

            var document = new Document();
            var app      = new App();

            InstanceMap.Instance.Add(() => app);
            InstanceMap.Instance.Add(() => document);
            InstanceMap.Instance.Add(() => document.GetActiveTable());
            InstanceMap.Instance.Add(() => document.GetActiveTable().GetSelectedCells());

            //foreach (var cell in table.Cells)
            //{
            //if (cell.Position.X % 3 == 0)
            //{
            //cell.ForegroundColor = ConsoleColor.Black;
            //cell.BackgroundColor = ConsoleColor.White;
            //}
            //}


            //document.GetActiveTable().Header[0].AppendRightEllipsis(456);

            //document.GetActiveTable()[0, 0].BorderForegroundColor = ConsoleColor.Yellow;
            //document.GetActiveTable()[1, 0].ForegroundColor = ConsoleColor.Red;
            //document.GetActiveTable()[1, 0].BackgroundColor = ConsoleColor.Cyan;
            //document.GetActiveTable()[0, 1].BorderForegroundColor = ConsoleColor.Yellow;
            //document.GetActiveTable()[1, 1].BorderBackgroundColor = ConsoleColor.White;
            //document.GetActiveTable()[0, 2].BorderForegroundColor = ConsoleColor.Red;
            //document.GetActiveTable()[1, 0].SetContent("T");
            //document.GetActiveTable()[1, 0].VertialAlignment = VertialAlignment.Top;
            //document.GetActiveTable()[1, 1].SetContent("B");
            //document.GetActiveTable()[1, 1].VertialAlignment = VertialAlignment.Bottom;
            //table[1, 1].SetContent("C");
            //table[1, 1].VertialAlignment = VertialAlignment.Center;
            //table[1, 2].SetContent("C");
            //table[1, 2].VertialAlignment = VertialAlignment.Center;
            //table[1, 3].SetContent("B");
            //table[1, 3].VertialAlignment = VertialAlignment.Bottom;
            //table[1, 0].HorizontalAlignment = HorizontalAlignment.Right;
            //table[2, 0].Content = "AAAAAAAAAAA";
            //table.SetColumnWidth(1, 0);
            //table[0, 0].GivenSize = new Size(25, 1);

            //Console.WriteLine(JsonConvert.SerializeObject(viewOptions));

            do
            {
                try
                {
                    SmartConsole.Render(document);

                    //var rawCommand = Console.ReadLine().Trim();
                    var rawCommand = SmartConsole.ReadInputString();

                    var command = Command.FromString(rawCommand);

                    command.Execute(InstanceMap.Instance.GetInstances(command.Reference.ClassName, out _));

                    SmartConsole.LastHelp = "Enter command to execute";
                }
                catch (ParameterCountException ex)
                {
                    SmartConsole.ShowHelp(ex.RawCommand, null, ex.CommandReference, ex.Message);
                }
                catch (IncompleteCommandException ex)
                {
                    SmartConsole.ShowHelp(ex.RawCommand, ex.AvailableKeys, null, ex.Message);
                }
                catch (PartialKeyException ex)
                {
                    SmartConsole.ShowHelp(ex.RawCommand, null, null, ex.Message);
                }
                catch (HelpRequestedException ex)
                {
                    SmartConsole.ShowHelp(ex.RawCommand, ex.AvailableKeys, ex.CommandReference, ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.Message} -> {ex}");
                    Console.Write("Press any key to continue");
                    Console.ReadKey();
                }

                Console.Clear();
            }while (true);
        }
 public static void Register()
 {
     SmartConsole.RegisterCommand("beep", "", "Plays the 'beep' system sound.", new SmartConsole.ConsoleCommandFunction(SmartConsoleCommands.Beep));
     SmartConsole.RegisterCommand("bat", "bat fileName", "Executes commands from a file in the Bag of Tricks folder.", new SmartConsole.ConsoleCommandFunction(SmartConsoleCommands.CommandBatch));
 }
Пример #26
0
        public override byte[] MergeSolution(byte[][] solutions)
        {
            int start_k = 1;
            int max_k   = 5;

            BinaryFormatter formatter = new BinaryFormatter();

            int size = solutions.Length;

            Result[] partialSolutions = new Result[size];
            List <List <Result> > partialSolutionsByID = new List <List <Result> >();

            for (int i = 0; i < max_k; i++)
            {
                partialSolutionsByID.Add(new List <Result>());
            }

            for (int i = 0; i < size; i++)
            {
                Result result = (Result)formatter.Deserialize(new MemoryStream(solutions[i]));
                partialSolutionsByID[result.ID - 1].Add(result);
            }

            List <int[]> finalRoutes     = new List <int[]>();
            List <int>   finalRoutesSize = new List <int>();

            List <float> finalDistances = new List <float>();

            List <List <int> > nextDays = new List <List <int> >();

            for (int i = 0; i < partialSolutionsByID.Count; i++)
            {
                finalRoutesSize.Add(0);
                finalDistances.Add(0);
            }

            for (int i = 0; i < partialSolutionsByID.Count; i++)
            {
                for (int j = 0; j < partialSolutionsByID[i].Count; j++)
                {
                    Result result = partialSolutionsByID[i][j];

                    finalDistances[i]  += result.length;
                    finalRoutesSize[i] += result.route.Length;
                }
                finalRoutesSize[i] += partialSolutionsByID[i].Count - 1;
            }

            for (int i = 0; i < partialSolutionsByID.Count; i++)
            {
                int[] route = new int[finalRoutesSize[i]];
                finalRoutes.Add(route);
            }


            for (int i = 0; i < partialSolutionsByID.Count; i++)
            {
                nextDays.Add(new List <int>());

                int finalRouteIndex = 0;

                for (int j = 0; j < partialSolutionsByID[i].Count; j++)
                {
                    Result result = partialSolutionsByID[i][j];

                    nextDays[i].AddRange(result.nextDay);

                    int[] route = result.route;

                    for (int l = 0; l < route.Length; l++)
                    {
                        finalRoutes[i][finalRouteIndex++] = route[l];
                    }

                    if (j != partialSolutionsByID[i].Count - 1)
                    {
                        finalRoutes[i][finalRouteIndex++] = -1;
                    }
                }
            }

            // print
            for (int i = 0; i < finalRoutes.Count; i++)
            {
                int[] finalRoute    = finalRoutes[i];
                float finalDistance = finalDistances[i];

                int k = i + 1;
                SmartConsole.PrintHeader(" RESULT FOR K = " + k);

                SmartConsole.PrintLine("Distance: " + finalDistance, SmartConsole.DebugLevel.Advanced);
                string msg = "";

                for (int l = 0; l < finalRoute.Length; l++)
                {
                    if (finalRoute[l] == -1)
                    {
                        msg += "\n";
                    }
                    else
                    {
                        msg += finalRoute[l] + ", ";
                    }
                }

                SmartConsole.PrintLine("Path: \n" + msg, SmartConsole.DebugLevel.Advanced);

                string nextDayStr = "";
                for (int l = 0; l < nextDays[i].Count; l++)
                {
                    nextDayStr += nextDays[i][l] + ", ";
                }
                if (!nextDayStr.Equals(""))
                {
                    SmartConsole.PrintLine("Next Day: \n" + nextDayStr, SmartConsole.DebugLevel.Advanced);
                }
            }

            // Find min
            int   minIndex = 0;
            float min      = finalDistances[minIndex];

            for (int i = 0; i < finalDistances.Count; i++)
            {
                float dinstance = finalDistances[i];
                if (min > dinstance)
                {
                    min      = dinstance;
                    minIndex = i;
                }
            }

            Result finalSolution = new Result(finalRoutes[minIndex], finalDistances[minIndex], nextDays[minIndex]);

            byte[] data = DataSerialization.ObjectToByteArray(finalSolution);
            return(data);
        }