Пример #1
0
 /// <summary>
 /// Инициализация контрола
 /// </summary>
 /// <param name="remoteConsole"></param>
 /// <param name="networkAddress"></param>
 public void Initialize(RemoteConsole remoteConsole, int networkAddress)
 {
     this.vktConsole                = new Vkt5Console(remoteConsole);
     this.vktConsole.WriteLog      += this.WriteLog;
     this.vktConsole.RequestError  += new EventHandler(vktConsole_RequestError);
     this.vktConsole.NetworkAddress = networkAddress;
 }
Пример #2
0
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="remoteConsole"></param>
        public Vkt5Console(RemoteConsole remoteConsole)
        {
            this.NetworkAddress = 0;

            this.remoteConsole = remoteConsole;
            this.remoteConsole.DeviceDataReceived += new EventHandler <DeviceDataEventArgs>(remoteConsole_DeviceDataReceived);
        }
        public RemoteConsole getConsole()
        {
            RemoteConsole rc = new RemoteConsole();


            VirtualMachineMksTicket ticket = testMks();

            //Console.WriteLine( "Ticket dump:" );
            //Console.WriteLine( "  host: " + ticket.host );
            //Console.WriteLine( "  port: " + ticket.port );
            //Console.WriteLine( "  port specified: " + ticket.portSpecified );
            //Console.WriteLine( "  ssl: " + ticket.sslThumbprint );
            //Console.WriteLine( "  ticket: " + ticket.ticket );
            //Console.WriteLine( "  cfgFile: " + ticket.cfgFile );
            //Console.WriteLine( "  string: " + ticket.ToString() );

            String hostname   = "192.168.1.3:9443";
            String serverGuid = "11111111-1111-1111-1111-111111111111";

            serverGuid = "22222222-2222-2222-2222-222222222222";       // TODO do this proceduraly :-|
            String host = "192.168.1.3:443";
            //debugAllProperties();
            String vmId          = vmmor.Value;
            String sessionTicket = "cst-VCT-" + ticket.ticket + "--tp-" + ticket.sslThumbprint.Replace(":", "-");  // TODO find/replace : with -
            String url           = "https://" + hostname + "/vsphere-client/webconsole.html?vmId=" + vmId + "&vmName=" + getName() + "&serverGuid=" + serverGuid + "&locale=en_US&host=" + host + "&sessionTicket=" + sessionTicket + "&thumbprint=" + ticket.sslThumbprint;


            //Console.WriteLine( url );

            rc.url = url;
            return(rc);
        }
Пример #4
0
        /// <summary>
        /// Nothrow guarantee.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            UnregisterEventListeners();

            if (disposing)
            {
                if (connectionPoller != null)
                {
                    connectionPoller.Change(Timeout.Infinite, Timeout.Infinite);
                    connectionPoller.Dispose();
                    connectionPoller = null;
                }

                if (RemoteConsole != null)
                {
                    RemoteConsole.DisconnectAndDispose();
                    RemoteConsole = null;
                }

                Log.DebugFormat("Set Pending Vnc connection to null");
                SetPendingVNCConnection(null);
            }

            base.Dispose(disposing);
        }
Пример #5
0
        public async Task ServerPowerShell(CommandContext ctx, string serverName, [RemainingText] string script)
        {
            await ctx.TriggerTypingAsync();

            if (!script.StartsWith("```\n") && !script.EndsWith("```"))
            {
                await ctx.RespondAsync(embed : EmbedTemplates.CreateErrorEmbed("PowerShell",
                                                                               "**No script found!** Example Script: ```\necho 'test'\n```"));

                return;
            }

            if (!(Server.GetServers(true, serverName)[0] is Server server))
            {
                await ctx.RespondAsync(embed : EmbedTemplates.CreateErrorEmbed("Server Not Found",
                                                                               $"{serverName} could not be found."));

                return;
            }

            server.FileSystemService.CreateTextFile(@"C:\\DiscordScripts\\script.ps1",
                                                    Encoding.ASCII.GetBytes(script.Replace("```\n", string.Empty).Replace("```", string.Empty)));
            var console = new RemoteConsole(server, @"C:\\Windows\\System32\\cmd.exe",
                                            "/c powershell \"C:\\DiscordScripts\\script.ps1\"", "Powershell - Script", true);

            await ctx.RespondAsync(embed : EmbedTemplates.CreateInfoEmbed("Live Output",
                                                                          $"To start the command, click [here]({console.GetUrl()})"));
        }
Пример #6
0
        public LanguageServer(IRPCServer rpcServer)
        {
            this.rpcServer = rpcServer;
            rpcServer.RegisterRequestMethod(CodeActionRequest.Type, CallCodeAction);
            rpcServer.RegisterRequestMethod(CodeLensRequest.Type, CallCodeLens);
            rpcServer.RegisterRequestMethod(CodeLensResolveRequest.Type, CallCodeLensResolve);
            rpcServer.RegisterRequestMethod(CompletionRequest.Type, CallCompletion);
            rpcServer.RegisterRequestMethod(CompletionResolveRequest.Type, CallCompletionResolve);
            rpcServer.RegisterRequestMethod(DocumentHighlightRequest.Type, CallDocumentHighlight);
            rpcServer.RegisterRequestMethod(DocumentSymbolRequest.Type, CallDocumentSymbol);
            rpcServer.RegisterRequestMethod(DocumentFormattingRequest.Type, CallDocumentFormatting);
            rpcServer.RegisterRequestMethod(DocumentOnTypeFormattingRequest.Type, CallDocumentOnTypeFormatting);
            rpcServer.RegisterRequestMethod(DocumentRangeFormattingRequest.Type, CallDocumentRangeFormatting);
            rpcServer.RegisterRequestMethod(DefinitionRequest.Type, CallDefinition);
            rpcServer.RegisterRequestMethod(HoverRequest.Type, CallHoverRequest);
            rpcServer.RegisterRequestMethod(InitializeRequest.Type, CallInitialize);
            rpcServer.RegisterRequestMethod(ReferencesRequest.Type, CallReferences);
            rpcServer.RegisterRequestMethod(RenameRequest.Type, CallRename);
            rpcServer.RegisterRequestMethod(ShutdownRequest.Type, CallShutdown);
            rpcServer.RegisterRequestMethod(SignatureHelpRequest.Type, CallSignatureHelp);
            rpcServer.RegisterRequestMethod(WorkspaceSymbolRequest.Type, CallWorkspaceSymbol);
            rpcServer.RegisterNotificationMethod(DidChangeConfigurationNotification.Type, CallDidChangeConfiguration);
            rpcServer.RegisterNotificationMethod(ExitNotification.Type, CallExit);
            rpcServer.RegisterNotificationMethod(DidChangeWatchedFilesNotification.Type, CallDidChangeWatchedFiles);
            rpcServer.RegisterNotificationMethod(DidChangeTextDocumentNotification.Type, CallDidChangeTextDocument);
            rpcServer.RegisterNotificationMethod(DidCloseTextDocumentNotification.Type, CallDidCloseTextDocument);
            rpcServer.RegisterNotificationMethod(DidOpenTextDocumentNotification.Type, CallDidOpenTextDocument);

            RemoteConsole = new RemoteConsole(rpcServer);
            RemoteWindow = new RemoteWindow(rpcServer);
        }
Пример #7
0
        public RemoteConsole getConsole()
        {
            update();
            RemoteConsole rc = new RemoteConsole();

            if (getState() != VirtualMachineState.POWERED_ON)
            {
                return(rc);
            }


            var request = new RestRequest();

            request.Resource      = "/applications/" + applicationId + "/vms/" + vmId + "/vncUrl";
            request.Method        = Method.GET;
            request.RequestFormat = DataFormat.Json;

            var response = restClient.Execute(request);

            rc.url = response.Content;

            //RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();

            //RavelloVm vm = deserial.Deserialize<RavelloVm>( response );


            return(rc);
        }
Пример #8
0
 public void Pause()
 {
     if (RemoteConsole != null)
     {
         wasPaused = true;
         RemoteConsole.Pause();
     }
 }
Пример #9
0
 public void Unpause()
 {
     if (RemoteConsole != null)
     {
         wasPaused = false;
         RemoteConsole.Unpause();
     }
 }
Пример #10
0
        public void SendCAD()
        {
            Program.AssertOnEventThread();

            if (RemoteConsole != null)
            {
                RemoteConsole.SendCAD();
            }
        }
Пример #11
0
        internal Image Snapshot()
        {
            if (RemoteConsole != null)
            {
                return(RemoteConsole.Snapshot());
            }

            return(null);
        }
Пример #12
0
 private void CallReceiveMissingCopies(NotificationType notificationType, object parameters)
 {
     try
     {
         OnDidReceiveMissingCopies((MissingCopiesParams)parameters);
     }
     catch (Exception e)
     {
         RemoteConsole.Error(String.Format("Error while handling notification {0} : {1}", notificationType.Method, e.Message));
     }
 }
Пример #13
0
        public override void OnDidCloseTextDocument(DidCloseTextDocumentParams parameters)
        {
            Uri objUri = new Uri(parameters.textDocument.uri);

            if (objUri.IsFile)
            {
                typeCobolWorkspace.CloseSourceFile(objUri);

                // DEBUG information
                RemoteConsole.Log("Closed source file : " + objUri.LocalPath);
            }
        }
Пример #14
0
        // -- Files synchronization : maintain a list of opened files, apply all updates to their content --

        public override void OnDidOpenTextDocument(DidOpenTextDocumentParams parameters)
        {
            Uri objUri = new Uri(parameters.uri);

            if (objUri.IsFile)
            {
                string fileName = Path.GetFileName(objUri.LocalPath);
                typeCobolWorkspace.OpenSourceFile(fileName, parameters.text);

                // DEBUG information
                RemoteConsole.Log("Opened source file : " + fileName);
            }
        }
Пример #15
0
        public override void OnDidCloseTextDocument(TextDocumentIdentifier parameters)
        {
            Uri objUri = new Uri(parameters.uri);

            if (objUri.IsFile)
            {
                string fileName = Path.GetFileName(objUri.LocalPath);
                typeCobolWorkspace.CloseSourceFile(fileName);

                // DEBUG information
                RemoteConsole.Log("Closed source file : " + fileName);
            }
        }
Пример #16
0
        //----
#if NETCF && REMOTE_CONSOLE
        void RemoteConsole_Click(object sender, EventArgs e)
        {
            if (!ReadYesNo("Connect to Remote console (port " + RemoteConsole.Port + ")", false))
            {
                return;
            }
            if (_secondConsole != null)
            {
                var msg = "Remote Console already active!";
                SafeMsgBox(msg, "Warning", MsgBoxStyle.Information);
                return;
            }
            _secondConsole = new RemoteConsole(this);
        }
Пример #17
0
        internal void CaptureKeyboardAndMouse()
        {
            if (RemoteConsole != null)
            {
                RemoteConsole.Activate();
                if (autoCaptureKeyboardAndMouse)
                {
                    SetKeyboardAndMouseCapture(true);
                }
                Unpause();
            }

            DisableMenuShortcuts();
        }
Пример #18
0
        public override void OnDidOpenTextDocument(DidOpenTextDocumentParams parameters)
        {
            Uri objUri = new Uri(parameters.textDocument.uri);

            if (objUri.IsFile)
            {
                //Subscribe to diagnostics event
                typeCobolWorkspace.MissingCopiesEvent += MissingCopiesDetected;
                typeCobolWorkspace.DiagnosticsEvent   += DiagnosticsDetected;

                typeCobolWorkspace.OpenSourceFile(objUri,
                                                  parameters.text != null ? parameters.text : parameters.textDocument.text, Workspace.LsrTestOptions);

                // DEBUG information
                RemoteConsole.Log("Opened source file : " + objUri.LocalPath);
            }
        }
Пример #19
0
        public async Task ServerCmd(CommandContext ctx, string serverName, [RemainingText] string script)
        {
            await ctx.TriggerTypingAsync();

            if (!(Server.GetServers(true, serverName)[0] is Server server))
            {
                await ctx.RespondAsync(embed : EmbedTemplates.CreateErrorEmbed("Server Not Found",
                                                                               $"{serverName} could not be found."));

                return;
            }

            var console = new RemoteConsole(server, @"C:\\Windows\\System32\\cmd.exe", "/c " + script,
                                            "Command Prompt - Script", true);

            await ctx.RespondAsync(embed : EmbedTemplates.CreateInfoEmbed("Live Output",
                                                                          $"To start the command, click [here]({console.GetUrl()})"));
        }
        public RemoteConsole getConsole()
        {
            //update();
            //RemoteConsole rc = new RemoteConsole();

            //if( getState() != VirtualMachineState.POWERED_ON )
            //    return rc;


            //var request = new RestRequest();
            //request.Resource = "/applications/" + applicationId + "/vms/" + vmId + "/vncUrl";
            //request.Method = Method.GET;
            //request.RequestFormat = DataFormat.Json;

            //var response = restClient.Execute( request );

            //rc.url = response.Content;

            ////RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();

            ////RavelloVm vm = deserial.Deserialize<RavelloVm>( response );


            //return rc;
            String token = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(getId()));

            token = token.Replace("=", "");
            token = token.Replace("-", "+");
            token = token.Replace("_", "/");

            String        url = String.Format("https://kimchiserver:8001/plugins/kimchi/novnc/vnc_auto.html?port=8001&path=websockify?token={0}&encrypt=1", token);
            RemoteConsole rc  = new RemoteConsole();

            rc.url = url;
            return(rc);
        }
Пример #21
0
        static void Main(string[] args)
        {
            Logger.SetupLogger();

            Logger.Log("Chino-chan handler loading...");
            ConfigEditor = new ConfigEditor();

loadConfig:
            Logger.Log("Loading config...");
            Config = LoadConfig(ConfigPath);
            Logger.Log("Config loaded!", Color: ConsoleColor.Green);
            if (Config.IsNewConfig())
            {
                Config.SaveConfig();
                Logger.Log("Your config is outdated! Please check your configuration to avoid future crashes, and press enter!", Color: ConsoleColor.Cyan);
                ConfigEditor.FillEmpty(Config);
                goto loadConfig;
            }

            Logger.Log("Checking libraries...");
            if (!CheckLibraries())
            {
                Logger.Log("Please install the libraries / runtimes mentioned above! Press enter to exit!", Color: ConsoleColor.Red);
                Console.ReadLine();
                Environment.Exit(1);
            }
            Logger.Log("Checking libraries done!", Color: ConsoleColor.Green);

            Logger.Log("Initializing Webhook manager...");
            Manager = new WebhookManager(Config);
            Logger.Log("Webhook manager initialized!", Color: ConsoleColor.Green);

            Logger.Log("Initializing Bot handler...");
            BotHandler = new BotHandler(Config);
            Logger.Log("Handler initialized!", Color: ConsoleColor.Green);

            Logger.Log("Initializing updater...");
            Updater    = new Updater(Config);
            BotUpdate += () =>
            {
                Updater.Update(true);
            };
            HandlerUpdate += () =>
            {
                Updater.Update(false);
            };
            Logger.Log("Updater initialized!", Color: ConsoleColor.Green);

            Logger.Log("Initializing Remote Console...");
            RemoteConsole = new RemoteConsole(Config);
            Logger.Log("Remote Console initialized!", Color: ConsoleColor.Green);


            Logger.Log("Initializing menu...");
            MenuHandler = new MenuHandler();
            MenuHandler.Add("Start", () =>
            {
                BotHandler.Start();
                ShowMenu = false;
            });
            MenuHandler.Add("Edit Config", () =>
            {
                ConfigEditor.EditAll(Config);
                Logger.Log("Restart the program for the changes to take effect.");
            });
            MenuHandler.Add("Exit", () =>
            {
                BotHandler.Quit();
                Environment.Exit(0);
            });
            Console.Clear();

            Logger.Log("Starting Webhook manager...");
            if (Manager.Start())
            {
                Logger.Log("Webhook manager successfully started!", Color: ConsoleColor.Green);
                Console.Clear();
            }
            RemoteConsole.Start();
            Console.WriteLine();
            HandleCommands();
        }
Пример #22
0
        // wago - 192.168.1.111
        // gate - 192.168.1.121
        // 4.3" - 192.168.1.122
        // 10" - 192.168.1.131
        // stm32 - 192.168.1.141

        // wago test modules

        static void Main()
        {
            //var journal = new ConsoleJournal();//journalService.GetJournal();
            //var journal = new SqLiteJournal {IsConsoleEnable = true};//journalService.GetJournal();
            //var journal = new JournalClient("127.0.0.1");

            //Console.OutputEncoding = System.Text.Encoding.GetEncoding(1251);
            //Console.OutputEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //Console.OutputEncoding = System.Text.Encoding.GetEncoding(866);
            bool debug = false;

            bool oldPanel43 = false;

            var mJServer = new JournalService(true);

            mJServer.Start();
            var journal = mJServer.GetJournal();

            var mMsgLvlSys = MessageLevel.System;

            journal.Warning("Старт работы PCproc", mMsgLvlSys);

            var signals = new SignalsFactory(journal);

            ConfigureSignalFactory(signals);
            journal.Warning("Запуск и конфигурирование Фабрики сигналов", mMsgLvlSys);
            //ModBusWago();

            var wago = new Coupler(journal, "192.168.1.111");


            //if (CouplerConfigurator.W750493_flag == false) wago.SetBaseAddr(524);
            CouplerConfigurator.Init(wago, signals);
            journal.Warning("Инициализация Ваго", mMsgLvlSys);
            List <ITask> tasklets;
            //if (oldPanel43) {
            var local = new RemoteConsole(journal, signals, 5000);

            journal.Warning(" Подключение к порту журнала на 5000 ", mMsgLvlSys);
            tasklets = new List <ITask> {
                local, wago, signals
            };
            //} else tasklets = new List<ITask> { wago, signals };


            /* This code added to support Qt GUI version of 4.3 Panel*/
            var qt = new qt(ref mJServer, ref signals, ref journal, true);

            qt.startLiterner();

            /* This code added to support Qt GUI version of 4.3 Panel*/

            try
            {
                //signals.GetSignal(SensorName.Keyboard()).OnChange += signal => Console.WriteLine("Keyboard: {0}", signal.Value);

                //signals.GetSignal(SensorName.Tank(SignalName.Level)).OnUpdate += signal => journal.Debug(string.Format("Level: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal("encoder.point").OnUpdate += signal => journal.Info(string.Format("Angle: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Tank(SignalName.Temperature)).OnChange += signal => Console.WriteLine("Temp: {0}", signal.Value);

                //signals.GetSignal(SensorName.Cabel(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Cabel: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Filter(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Filter: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Steering(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Steering: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Brake(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Brake: {0}", signal.Value), MessageLevel.User);

                //var pStatus = signals.GetSignal(SensorName.Derivative(SystemName.Pump, SignalName.Status));
                //var uz2Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 2, SignalName.Status));
                //var uz3Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 3, SignalName.Status));
                //var uz4Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 4, SignalName.Status));
                //var uz5Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 5, SignalName.Status));
                //var cStatus = signals.GetSignal(SensorName.Derivative(SystemName.Conveyor, SignalName.Status));
                //var code = 0;
                //cStatus.Update(code);
                //code++;

                //if (code > 2)
                //    code = 0;

                int first_cycle = 0;
                int show_delay  = 0;
                int MotoSeconds = 0;
                int MotoMinutes = 0;
                int MotoDays    = 0;
                //float TotalMotoHours = 0;
                float MotoHours = signals.GetSignal("system.settings.MotoHours").Value;
                //float TotalMotoHours = signals.GetSignal("system.settings.TotalMotoHours").Value;
                using (new SystemContol(journal, signals))
                {
                    //signals.PrintInfo(); //отладка сигналов в процессоре

                    foreach (var task in tasklets)
                    {
                        task.Start();
                    }

                    while (true)
                    {
                        Thread.Sleep(1000);
                        //проверка состояния насоса маслостанции
                        var signalPump = signals.GetSignal("derivative.pump.status").Value;
                        if (debug)
                        {
                            if (signalPump == 0)
                            {
                                Console.WriteLine("Pump stopped: " + signalPump);
                            }
                        }

                        //debug signalPump=1
                        signalPump = 1;
                        //Debug 1sec = 1min
                        MotoMinutes = MotoSeconds;

                        if (signalPump == 1)
                        {
                            //насос включен
                            if (debug)
                            {
                                Console.WriteLine("Pump started: " + signalPump);
                            }

                            //первый проход забрали из базы и прибавили к текущему время
                            if (debug)
                            {
                                Console.WriteLine(">>>>>> Moto hours from DB: " + MotoHours);
                            }
                            //first_cycle = 1;
                            //if (first_cycle == 1) MotoHours = MotoHours + MotoSeconds / 120;

                            //Считаем секунды
                            MotoSeconds++;
                            if (MotoSeconds == 60) //одна минута
                            {
                                MotoSeconds = 0;   //сброс секунд
                                MotoMinutes = MotoMinutes + 1;
                            }


                            if (debug)
                            {
                                Console.WriteLine("Moto seconds: " + MotoSeconds);
                                Console.WriteLine("Moto Minutes: " + MotoMinutes);
                            }

                            //Считаем минуты
                            if (MotoMinutes == 60)
                            {
                                //Сброс минут по накоплении одного часа
                                MotoMinutes = 0;
                                //Cчитаем часы
                                MotoHours = MotoHours + 1;
                                //MotoHours = MotoHours + 100;

                                if (debug)
                                {
                                    Console.WriteLine("Moto seconds: " + MotoSeconds);
                                    Console.WriteLine("Moto Minutes: " + MotoMinutes);
                                    Console.WriteLine(">>>>>> Moto hours now: " + MotoHours);
                                }
                                signals.Update("system.settings.MotoHours", MotoHours);
                            }


                            //Защита от переполнения счетчика
                            if (MotoHours >= 250000) // Т.е. 250 000 часов это 28 лет
                            {
                                MotoHours = 0;
                                if (debug)
                                {
                                    Console.WriteLine(">>>>>> Moto hours now: " + MotoHours);
                                }
                            }

                            //if (MotoHours >= 200) //Замена масла через 200 М.ч.
                        }
                        show_delay++;
                        if (show_delay == 3)
                        {
                            // signals.PrintInfo(); //отладка сигналов в процессоре
                            //signals.WriteInfo(@"/mnt/sdcard/failsignals.raw"); //отладка сигналов в процессоре rwfs директория для перезаписи
                            show_delay = 0; //сброс таймера задержки

                            //Учет входа в меню сервисантов и инжинеров
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                journal.Fatal(ex.ToString(), MessageLevel.System);
            }


            #region stop tasks
            tasklets.Reverse();
            foreach (var task in tasklets)
            {
                task.Stop();
            }
            #endregion
        }
Пример #23
0
        static void Main()
        {
            //ConfiguratorTest();


            log4net.Config.XmlConfigurator.Configure();
            var journal = new Journal(LogManager.GetLogger("logger"));
            var signals = new SignalsFactory(journal);

            var wago = new Coupler(journal, signals, "192.168.1.111");

            CouplerConfigurator.Init(wago);

            var local = new RemoteConsole(journal, signals, 5000);

            //var invertors = new InvertorsService(journal, signals, "COM7");
            //var invertors = new InvertorsService(journal, signals, "/dev/ttySP1");

            signals.PrintInfo();

            #region start
            //var tasklets = new List<ITask> { invertors, local, wago, signals };
            var tasklets = new List <ITask> {
                local, wago, signals
            };

            foreach (var task in tasklets)
            {
                task.Start();
            }
            #endregion


            #region test & dump
            {
                Thread.Sleep(500);
                //TestRelay(signals);

                TestKeyboard(signals);

                //signals.SensorInfo();
                //signals.OutputInfo();
            }
            #endregion

            while (true)
            {
                Thread.Sleep(100);
            }


            //using (new SystemContol(journal, invertors, signals))
            {
                //Console.WriteLine("press Enter to stop");
                //Console.ReadLine();
                while (true)
                {
                    Thread.Sleep(100);
                }
            }

            #region stop tasks
            tasklets.Reverse();
            foreach (var task in tasklets)
            {
                task.Stop();
            }
            #endregion
        }
Пример #24
0
        public override void OnDidChangeTextDocument(DidChangeTextDocumentParams parameters)
        {
            var fileCompiler = GetFileCompilerFromStringUri(parameters.uri, false); //Text Change do not have to trigger node phase, it's only a another event that will do it

            if (fileCompiler == null)
            {
                return;
            }

            Uri objUri = new Uri(parameters.uri);

            #region Convert text changes format from multiline range replacement to single line updates

            TextChangedEvent textChangedEvent = new TextChangedEvent();
            foreach (var contentChange in parameters.contentChanges)
            {
                // Split the text updated into distinct lines
                List <string> lineUpdates = null;
                bool          replacementTextStartsWithNewLine = false;

                if (!string.IsNullOrEmpty(contentChange.text))
                {
                    replacementTextStartsWithNewLine = contentChange.text[0] == '\r' ||
                                                       contentChange.text[0] == '\n';
                    //Allow to know if a new line was added
                    //Split on \r \n to know the number of lines added
                    lineUpdates = contentChange.text.Replace("\r", "").Split('\n').ToList();
                    if (string.IsNullOrEmpty(lineUpdates.FirstOrDefault()) && replacementTextStartsWithNewLine)
                    {
                        lineUpdates.RemoveAt(0);
                    }
                }

                // Document cleared
                if (contentChange.range == null)
                {
                    //JCM: I have noticed that if the entire text has changed, is better to reload the entire file
                    //To avoid crashes.
                    try
                    {
                        typeCobolWorkspace.OpenSourceFile(objUri, contentChange.text, this.Workspace.LsrTestOptions);
                        return;
                    }
                    catch (Exception e)
                    {
                        //Don't rethow an exception on save.
                        RemoteConsole.Error(string.Format("Error while handling notification {0} : {1}",
                                                          "textDocument/didChange", e.Message));
                        return;
                    }
                }
                // Document updated
                else
                {
                    // Get original lines text before change
                    string originalFirstLineText =
                        fileCompiler.CompilationResultsForProgram.CobolTextLines[contentChange.range.start.line]
                        .Text;
                    string originalLastLineText = originalFirstLineText;


                    // Check if the first line was inserted
                    int firstLineIndex = contentChange.range.start.line;
                    int firstLineChar  = contentChange.range.start.character;
                    if (replacementTextStartsWithNewLine &&
                        !(contentChange.range.start.character < originalLastLineText.Length))
                    {
                        firstLineIndex++;
                        firstLineChar = 0;
                    }
                    else if (replacementTextStartsWithNewLine)
                    //Detected that the add line appeared inside an existing line
                    {
                        lineUpdates.Add(lineUpdates.First());
                        //Add the default 7 spaces + add lineUpdates in order to update the current line and add the new one.
                    }

                    // Check if the last line was deleted
                    int lastLineIndex = contentChange.range.end.line;
                    if (contentChange.range.end.line > contentChange.range.start.line &&
                        contentChange.range.end.character == 0)
                    {
                        //Allows to detect if the next line was suppressed
                    }
                    if (contentChange.text?.Length == 0)
                    {
                        lineUpdates = new List <string>();
                    }

                    if (lastLineIndex > firstLineIndex)
                    {
                        originalLastLineText =
                            fileCompiler.CompilationResultsForProgram.CobolTextLines[
                                Math.Min(lastLineIndex,
                                         fileCompiler.CompilationResultsForProgram.CobolTextLines.Count - 1)].Text;
                    }

                    // Text not modified at the beginning of the first replaced line
                    string startOfFirstLine = null;
                    if (firstLineChar > 0)
                    {
                        if (originalFirstLineText.Length >= contentChange.range.start.character)
                        {
                            startOfFirstLine = originalFirstLineText.Substring(0,
                                                                               contentChange.range.start.character);
                        }
                        else
                        {
                            startOfFirstLine = originalFirstLineText.Substring(0, originalFirstLineText.Length) +
                                               new string(' ',
                                                          contentChange.range.start.character - originalFirstLineText.Length);
                        }
                    }

                    // Text not modified at the end of the last replaced line
                    string endOfLastLine = null;
                    if (contentChange.range.end.character < originalLastLineText.Length)
                    {
                        endOfLastLine = originalLastLineText.Substring(contentChange.range.end.character);
                    }

                    // Remove all the old lines
                    for (int i = firstLineIndex; i <= lastLineIndex; i++)
                    {
                        var textChange = new TextChange(TextChangeType.LineRemoved, firstLineIndex, null);
                        textChangedEvent.TextChanges.Add(textChange);
                        //Mark the index line to be removed. The index will remains the same for each line delete, because text change are apply one after another
                    }

                    // Insert the updated lines
                    if (!(startOfFirstLine == null && lineUpdates == null && endOfLastLine == null))
                    {
                        int lineUpdatesCount = (lineUpdates != null && lineUpdates.Count > 0)
                            ? lineUpdates.Count
                            : 1;
                        for (int i = 0; i < lineUpdatesCount; i++)
                        {
                            string newLine = (lineUpdates != null && lineUpdates.Count > 0)
                                ? lineUpdates[i]
                                : string.Empty;
                            if (i == 0)
                            {
                                newLine = startOfFirstLine + newLine;
                            }
                            if (i == lineUpdatesCount - 1)
                            {
                                newLine = newLine + endOfLastLine;
                            }
                            var textChange = new TextChange(TextChangeType.LineInserted, firstLineIndex + i,
                                                            new TextLineSnapshot(firstLineIndex + i, newLine, null));
                            textChangedEvent.TextChanges.Add(textChange);
                        }
                    }
                }
            }

            #endregion

            // Update the source file with the computed text changes
            typeCobolWorkspace.UpdateSourceFile(objUri, textChangedEvent);

            // DEBUG information
            RemoteConsole.Log("Udpated source file : " + objUri.LocalPath);
            foreach (var textChange in textChangedEvent.TextChanges)
            {
                RemoteConsole.Log(" - " + textChange.ToString());
            }
        }
Пример #25
0
        static void Main()
        {
            //var journal = new ConsoleJournal();//journalService.GetJournal();
            //var journal = new SqLiteJournal {IsConsoleEnable = true};//journalService.GetJournal();
            //var journal = new JournalClient("127.0.0.1");

            //Console.OutputEncoding = System.Text.Encoding.GetEncoding(1251);
            //Console.OutputEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //Console.OutputEncoding = System.Text.Encoding.GetEncoding(866);
            bool debug = false;

            bool oldPanel43 = false;

            var mJServer = new JournalService(true);

            mJServer.Start();
            var journal = mJServer.GetJournal();

            var mMsgLvlSys = MessageLevel.System;

            journal.Warning("Старт работы PCproc", mMsgLvlSys);

            var signals = new SignalsFactory(journal);

            ConfigureSignalFactory(signals);
            journal.Warning("Запуск и конфигурирование Фабрики сигналов", mMsgLvlSys);
            //ModBusWago();

            var wago = new Coupler(journal, "192.168.1.111");


            //if (CouplerConfigurator.W750493_flag == false) wago.SetBaseAddr(524);
            CouplerConfigurator.Init(wago, signals);
            journal.Warning("Инициализация Ваго", mMsgLvlSys);
            List <ITask> tasklets;
            //if (oldPanel43) {
            var local = new RemoteConsole(journal, signals, 5000);

            journal.Warning(" Подключение к порту журнала на 5000 ", mMsgLvlSys);
            tasklets = new List <ITask> {
                local, wago, signals
            };
            //} else tasklets = new List<ITask> { wago, signals };


            /* This code added to support Qt GUI version of 4.3 Panel*/
            var qt = new qt(ref mJServer, ref signals, ref journal, true);

            qt.startLiterner();

            /* This code added to support Qt GUI version of 4.3 Panel*/

            try
            {
                //signals.GetSignal(SensorName.Keyboard()).OnChange += signal => Console.WriteLine("Keyboard: {0}", signal.Value);

                //signals.GetSignal(SensorName.Tank(SignalName.Level)).OnUpdate += signal => journal.Debug(string.Format("Level: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal("encoder.point").OnUpdate += signal => journal.Info(string.Format("Angle: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Tank(SignalName.Temperature)).OnChange += signal => Console.WriteLine("Temp: {0}", signal.Value);

                //signals.GetSignal(SensorName.Cabel(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Cabel: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Filter(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Filter: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Steering(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Steering: {0}", signal.Value), MessageLevel.User);
                //signals.GetSignal(SensorName.Brake(SignalName.Pressure)).OnUpdate += signal => journal.Debug(string.Format("Brake: {0}", signal.Value), MessageLevel.User);

                //var pStatus = signals.GetSignal(SensorName.Derivative(SystemName.Pump, SignalName.Status));
                //var uz2Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 2, SignalName.Status));
                //var uz3Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 3, SignalName.Status));
                //var uz4Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 4, SignalName.Status));
                //var uz5Status = signals.GetSignal(SensorName.Derivative(SystemName.Uz, 5, SignalName.Status));
                //var cStatus = signals.GetSignal(SensorName.Derivative(SystemName.Conveyor, SignalName.Status));
                //var code = 0;
                //cStatus.Update(code);
                //code++;
                // проверяем не включена ли сейчас станция
                //foilstationstate = checkValueAsBool(signals.GetSignal("relay.kv11.k1").Value);
                // подписываемся на событие ОС по маслостанции, чтобы ставить флаг ее работы (так быстрее, чем постоянно спрашивать сигнал)
                signals.GetSignal("relay.kv11.k1").OnChange += sensor => oilStationState(sensor);

                int MotoSeconds = 0;
                int OilSeconds  = 0;
                //float TotalMotoHours = 0;
                float Moto = signals.GetSignal("system.settings.MotoHours").Value;
                float Oil  = signals.GetSignal("system.settings.OilHours").Value;
                //float TotalMotoHours = signals.GetSignal("system.settings.TotalMotoHours").Value;
                using (new SystemContol(journal, signals))
                {
                    //signals.PrintInfo(); //отладка сигналов в процессоре

                    foreach (var task in tasklets)
                    {
                        task.Start();
                    }

                    while (true)
                    {
                        Thread.Sleep(5000);
                        //проверка состояния насоса маслостанции
                        //var signalPump = signals.GetSignal("derivative.pump.status").Value;

                        //foilstationstate = true;
                        if (foilstationstate)
                        {
                            //насос включен
                            //Считаем секунды
                            MotoSeconds += 5;
                            if (MotoSeconds >= 60 * 15) //одна минута
                            {
                                MotoSeconds = 0;        //сброс секунд
                                Moto        = signals.GetSignal("system.settings.MotoHours").Value;
                                Moto       += 0.25f;
                                signals.Update("system.settings.MotoHours", Moto);
                            }
                            OilSeconds += 5;
                            if (OilSeconds >= 60 * 15) //одна минута
                            {
                                OilSeconds = 0;        //сброс секунд
                                Oil        = signals.GetSignal("system.settings.OilHours").Value;
                                Oil       += 0.25f;
                                signals.Update("system.settings.OilHours", Oil);
                            }

                            //if (MotoHours >= 200) //Замена масла через 200 М.ч.
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                journal.Fatal(ex.ToString(), MessageLevel.System);
            }


            #region stop tasks
            tasklets.Reverse();
            foreach (var task in tasklets)
            {
                task.Stop();
            }
            #endregion
        }
Пример #26
0
        /// <summary>
        /// Performs initialisation of the scene, such as loading configuration from disk.
        /// </summary>
        protected override void StartupSpecific()
        {
            m_log.Info("====================================================================");
            m_log.Info("========================= STARTING OPENSIM =========================");
            m_log.Info("====================================================================");
            m_log.InfoFormat("[OPENSIM MAIN]: Running ");
            //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
            // http://msdn.microsoft.com/en-us/library/bb384202.aspx
            //GCSettings.LatencyMode = GCLatencyMode.Batch;
            //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString());

            if (m_gui) // Driven by external GUI
                m_console = new CommandConsole("Region");
            else
            {
                switch (m_consoleType)
                {
                case "basic":
                    m_console = new CommandConsole("Region");
                    break;
                case "rest":
                    m_console = new RemoteConsole("Region");
                    ((RemoteConsole)m_console).ReadConfig(m_config.Source);
                    break;
                default:
                    m_console = new LocalConsole("Region");
                    break;
                }
            }

            MainConsole.Instance = m_console;

            RegisterConsoleCommands();

            base.StartupSpecific();

            MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler());
            MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this));
            if (userStatsURI != String.Empty)
                MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this));

            if (m_console is RemoteConsole)
            {
                if (m_consolePort == 0)
                {
                    ((RemoteConsole)m_console).SetServer(m_httpServer);
                }
                else
                {
                    ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort));
                }
            }

            //Run Startup Commands
            if (String.IsNullOrEmpty(m_startupCommandsFile))
            {
                m_log.Info("[STARTUP]: No startup command script specified. Moving on...");
            }
            else
            {
                RunCommandScript(m_startupCommandsFile);
            }

            // Start timer script (run a script every xx seconds)
            if (m_timedScript != "disabled")
            {
                m_scriptTimer = new Timer();
                m_scriptTimer.Enabled = true;
                m_scriptTimer.Interval = 1200*1000;
                m_scriptTimer.Elapsed += RunAutoTimerScript;
            }

            // Hook up to the watchdog timer
            Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler;

            PrintFileToConsole("startuplogo.txt");

            // For now, start at the 'root' level by default
            if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it
                ChangeSelectedRegion("region",
                                     new string[] {"change", "region", m_sceneManager.Scenes[0].RegionInfo.RegionName});
            else
                ChangeSelectedRegion("region", new string[] {"change", "region", "root"});
        }
Пример #27
0
        public override void OnDidChangeTextDocument(DidChangeTextDocumentParams parameters)
        {
            Uri objUri = new Uri(parameters.uri);

            if (objUri.IsFile)
            {
                string fileName     = Path.GetFileName(objUri.LocalPath);
                var    fileCompiler = typeCobolWorkspace.OpenedFileCompilers[fileName];

                #region Convert text changes format from multiline range replacement to single line updates

                // THIS CONVERSION STILL NEEDS MORE WORK : much more complicated than you would think

                TextChangedEvent textChangedEvent = new TextChangedEvent();
                foreach (var contentChange in parameters.contentChanges)
                {
                    // Split the text updated into distinct lines
                    string[] lineUpdates = null;
                    bool     replacementTextStartsWithNewLine = false;
                    if (contentChange.text != null && contentChange.text.Length > 0)
                    {
                        replacementTextStartsWithNewLine = contentChange.text[0] == '\r' || contentChange.text[0] == '\n';
                        lineUpdates = contentChange.text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    }

                    // Document cleared
                    if (contentChange.range == null)
                    {
                        var textChange = new TextChange(TextChangeType.DocumentCleared, 0, null);
                        textChangedEvent.TextChanges.Add(textChange);
                        if (lineUpdates != null)
                        {
                            for (int i = 0; i < lineUpdates.Length; i++)
                            {
                                textChange = new TextChange(TextChangeType.LineInserted, i, new TextLineSnapshot(i, lineUpdates[i], null));
                                textChangedEvent.TextChanges.Add(textChange);
                            }
                        }
                    }
                    // Document updated
                    else
                    {
                        // Check if the first line was inserted
                        int firstLineIndex = contentChange.range.start.line;
                        int firstLineChar  = contentChange.range.start.character;
                        if (replacementTextStartsWithNewLine)
                        {
                            firstLineIndex++;
                            firstLineChar = 0;
                        }

                        // Check if the last line was deleted
                        int  lastLineIndex   = contentChange.range.end.line;
                        bool lastLineDeleted = false;
                        if (contentChange.range.end.line > contentChange.range.start.line && contentChange.range.end.character == 0)
                        {
                            lastLineIndex--;
                            lastLineDeleted = true;
                        }
                        if (!lastLineDeleted && contentChange.text.Length == 0)
                        {
                            lineUpdates = new string[0];
                        }

                        // Get original lines text before change
                        string originalFirstLineText = fileCompiler.CompilationResultsForProgram.CobolTextLines[contentChange.range.start.line].Text;
                        string originalLastLineText  = originalFirstLineText;
                        if (lastLineIndex > firstLineIndex)
                        {
                            originalLastLineText = fileCompiler.CompilationResultsForProgram.CobolTextLines[lastLineIndex].Text;
                        }

                        // Text not modified at the beginning of the first replaced line
                        string startOfFirstLine = null;
                        if (firstLineChar > 0)
                        {
                            startOfFirstLine = originalFirstLineText.Substring(0, contentChange.range.start.character);
                        }

                        // Text not modified at the end of the last replaced line
                        string endOfLastLine = null;
                        if (!lastLineDeleted && contentChange.range.end.character < originalLastLineText.Length)
                        {
                            endOfLastLine = originalLastLineText.Substring(contentChange.range.end.character);
                        }

                        // Remove all the old lines
                        for (int i = firstLineIndex; i <= lastLineIndex; i++)
                        {
                            var textChange = new TextChange(TextChangeType.LineRemoved, firstLineIndex, null);
                            textChangedEvent.TextChanges.Add(textChange);
                        }

                        // Insert the updated lines
                        if (!(startOfFirstLine == null && lineUpdates == null && endOfLastLine == null))
                        {
                            int lineUpdatesCount = (lineUpdates != null && lineUpdates.Length > 0) ? lineUpdates.Length : 1;
                            for (int i = 0; i < lineUpdatesCount; i++)
                            {
                                string newLine = (lineUpdates != null && lineUpdates.Length > 0) ? lineUpdates[i] : String.Empty;
                                if (i == 0)
                                {
                                    newLine = startOfFirstLine + newLine;
                                }
                                if (i == lineUpdatesCount - 1)
                                {
                                    newLine = newLine + endOfLastLine;
                                    if (lastLineDeleted)
                                    {
                                        break;
                                    }
                                }
                                var textChange = new TextChange(TextChangeType.LineInserted, firstLineIndex + i, new TextLineSnapshot(firstLineIndex + i, newLine, null));
                                textChangedEvent.TextChanges.Add(textChange);
                            }
                        }
                    }
                }
                #endregion

                // Update the source file with the computed text changes
                typeCobolWorkspace.UpdateSourceFile(fileName, textChangedEvent);

                // DEBUG information
                RemoteConsole.Log("Udpated source file : " + fileName);
                foreach (var textChange in textChangedEvent.TextChanges)
                {
                    RemoteConsole.Log(" - " + textChange.ToString());
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Performs initialisation of the scene, such as loading configuration from disk.
        /// </summary>
        protected override void StartupSpecific()
        {
            m_log.Info("====================================================================");
            m_log.Info("========================= STARTING OPENSIM =========================");
            m_log.Info("====================================================================");

            //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
            // http://msdn.microsoft.com/en-us/library/bb384202.aspx
            //GCSettings.LatencyMode = GCLatencyMode.Batch;
            //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString());

            if (m_gui) // Driven by external GUI
            {
                m_console = new CommandConsole("Region");
            }
            else
            {
                switch (m_consoleType)
                {
                case "basic":
                    m_console = new CommandConsole("Region");
                    break;

                case "rest":
                    m_console = new RemoteConsole("Region");
                    ((RemoteConsole)m_console).ReadConfig(Config);
                    break;

                default:
                    m_console = new LocalConsole("Region");
                    break;
                }
            }

            MainConsole.Instance = m_console;

            RegisterCommonAppenders(Config.Configs["Startup"]);
            RegisterConsoleCommands();

            base.StartupSpecific();

            MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler());
            MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this));
            if (userStatsURI != String.Empty)
            {
                MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this));
            }

            if (m_console is RemoteConsole)
            {
                if (m_consolePort == 0)
                {
                    ((RemoteConsole)m_console).SetServer(m_httpServer);
                }
                else
                {
                    ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort));
                }
            }

            // Hook up to the watchdog timer
            Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler;

            PrintFileToConsole("startuplogo.txt");

            // For now, start at the 'root' level by default
            if (SceneManager.Scenes.Count == 1) // If there is only one region, select it
            {
                ChangeSelectedRegion("region",
                                     new string[] { "change", "region", SceneManager.Scenes[0].RegionInfo.RegionName });
            }
            else
            {
                ChangeSelectedRegion("region", new string[] { "change", "region", "root" });
            }

            //Run Startup Commands
            if (String.IsNullOrEmpty(m_startupCommandsFile))
            {
                m_log.Info("[STARTUP]: No startup command script specified. Moving on...");
            }
            else
            {
                RunCommandScript(m_startupCommandsFile);
            }

            // Start timer script (run a script every xx seconds)
            if (m_timedScript != "disabled")
            {
                m_scriptTimer          = new Timer();
                m_scriptTimer.Enabled  = true;
                m_scriptTimer.Interval = m_timeInterval * 1000;
                m_scriptTimer.Elapsed += RunAutoTimerScript;
            }
        }