public static void Display()
        {
            LcdConsole.Clear();

            // http://stackoverflow.com/questions/105031/how-do-you-get-total-amount-of-ram-the-computer-has
            // http://stackoverflow.com/questions/3896685/simplest-possible-performance-counter-example
            foreach (var pcCategory in PerformanceCounterCategory.GetCategories())
            {
                LcdConsole.Clear();
                LcdConsole.WriteLine(pcCategory.CategoryName);
                int lineNum = 1;
                int pageNum = 1;
                foreach (var performanceCounter in pcCategory.GetCounters())
                {
                    LcdConsole.WriteLine(performanceCounter.CounterName);
                    LcdConsole.WriteLine("{0}", performanceCounter.RawValue);
                    if ((++lineNum % 5) == 0)
                    {
                        LcdConsole.WriteLine("-----{0} page {1}", pcCategory.CategoryName, pageNum++);
                        EV3KeyPad.ReadKey();
                    }
                }
                LcdConsole.WriteLine("-----End of {0}", pcCategory.CategoryName);
                EV3KeyPad.ReadKey();
            }
        }
Exemple #2
0
 private static void Quit_OnEnterPressed()
 {
     LcdConsole.Clear();
     LcdConsole.WriteLine("Terminating");
     // Wait a bit
     Thread.Sleep(1000);
     TerminateMenu();
 }
Exemple #3
0
        public static void Main(string[] args)
        {
            // http://msdn.microsoft.com/en-us/library/s80a75e5%28VS.80%29.aspx
            // The number of bytes that the associated process has allocated
            // that cannot be shared with other processes.
            Process proc = Process.GetCurrentProcess();

            LcdConsole.WriteLine("PrivateMemorySize {0:N0}", proc.PrivateMemorySize64);

            // http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory.aspx
            // A number that is the best available approximation of the number of
            // bytes currently allocated in managed memory.
            LcdConsole.WriteLine("GC.GetTotalMemory {0:N0}", GC.GetTotalMemory(false));

            // http://mono-project.com/Mono_Performance_Counters
            //OutPerformanceCounterValue("Process", "Virtual Bytes");
            //OutPerformanceCounterValue("Process", "Private Bytes");
            OutPerformanceCounterValue("Mono Memory", "Total Physical Memory");
            //OutPerformanceCounterValue(".NET CLR Memory", "# Bytes in all Heaps");

            EV3KeyPad.ReadKey();

            LcdConsole.Clear();

            var MBytes  = 42;
            var bytes   = MBytes * 1024 * 1024;
            var intsize = sizeof(int);

            LcdConsole.WriteLine("Allocate {0}Mb of memory.", MBytes);
            LcdConsole.WriteLine("Please wait...");
            tst = new int[bytes / intsize];

            MBytes = 0;
            for (int i = 0; i < bytes / intsize; i++)
            {
                tst[i] = i;
                if ((i * intsize % (1024 * 1024)) == 0)
                {
                    LcdConsole.WriteLine("{0} MBytes used", ++MBytes);
                }
            }
            LcdConsole.WriteLine("Finished!");
            LcdConsole.WriteLine("Bytes allocated: {0:N0}", GC.GetTotalMemory(false));

            //EV3KeyPad.ReadKey ();
            //PerformanceContersInfo.Display ();

            EV3KeyPad.ReadKey();
            LcdConsole.WriteLine("Memory deallocation.");
            LcdConsole.WriteLine("Please wait...");
        }
Exemple #4
0
        public CharacterDisplay(ArduinoBoard board)
        {
            _controller = board.CreateGpioController();
            _display    = new Lcd1602(8, 9, new int[] { 4, 5, 6, 7 }, -1, 1.0f, -1, _controller);
            _display.BlinkingCursorVisible  = false;
            _display.UnderlineCursorVisible = false;
            _display.Clear();

            _textController = new LcdConsole(_display, "SplC780", false);
            _textController.Clear();
            LcdCharacterEncodingFactory f = new LcdCharacterEncodingFactory();
            var cultureEncoding           = f.Create(CultureInfo.CurrentCulture, "SplC780", '?', _display.NumberOfCustomCharactersSupported);

            _textController.LoadEncoding(cultureEncoding);
        }
Exemple #5
0
        public static void Main(string[] args)
        {
            const string to       = "*****@*****.**";
            const string from     = "*****@*****.**";
            const string password = "******";

            ManualResetEvent terminateProgram = new ManualResetEvent(false);
            var          colorSensor          = new EV3ColorSensor(SensorPort.In1);
            ButtonEvents buts        = new ButtonEvents();
            SmtpClient   smptpClient = new SmtpClient("smtp.gmail.com", 587);

            smptpClient.EnableSsl             = true;
            smptpClient.UseDefaultCredentials = false;
            smptpClient.Credentials           = new NetworkCredential(from, password);
            smptpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
            ServicePointManager.ServerCertificateValidationCallback =
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            { return(true); };
            MailMessage message = new MailMessage();

            message.To.Add(to);
            message.From    = new MailAddress(from);
            message.Subject = "Color mail from my EV3";
            LcdConsole.Clear();
            LcdConsole.WriteLine("Use color on port1");
            LcdConsole.WriteLine("Enter send mail");
            LcdConsole.WriteLine("Esc. terminate");
            buts.EscapePressed += () => {
                terminateProgram.Set();
            };
            buts.EnterPressed += () => {
                LcdConsole.WriteLine("Sending email");
                try{
                    message.Body = "EV3 read color: " + colorSensor.ReadColor();
                    smptpClient.Send(message);
                    LcdConsole.WriteLine("Done sending email");
                }
                catch (Exception e)
                {
                    LcdConsole.WriteLine("Failed to send email");
                    Console.WriteLine(e.StackTrace);
                }
            };
            terminateProgram.WaitOne();
            message = null;
        }
Exemple #6
0
        static void Main(string[] args)
        {
            // for number conversion
            Thread.CurrentThread.CurrentCulture   = System.Globalization.CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InstalledUICulture;

            ButtonEvents buttons = new ButtonEvents();
            TcpListener  server  = null;
            TcpClient    client  = null;
            bool         run     = true;

            buttons.EscapePressed += () =>
            {
                if (server != null)
                {
                    server.Stop();
                }
                if (client != null)
                {
                    client.Close();
                }

                run = false;
            };

            LcdConsole.WriteLine("EV3Scanner 3.0");

            float mainRatio      = 1.667f;
            float secondaryRatio = 3.0f;
            float handRatio      = 1f;

#if DUMPLOGS
            StringBuilder logs = new StringBuilder();
#endif
            // stop here
            if (!run)
            {
                return;
            }

            // main loop
            LcdConsole.WriteLine("Starting...");

            try
            {
                using (IRobot robot = new ScannerRobot()
                {
                })
                {
                    // apply settings
                    robot.RatioSettings[RobotSetup.XPort]   = mainRatio;
                    robot.RatioSettings[RobotSetup.YPort]   = secondaryRatio;
                    robot.RatioSettings[RobotSetup.PenPort] = handRatio;

                    // printer
                    // robot.SpeedSettings[RobotSetup.XPort] = 64;
                    // robot.SpeedSettings[RobotSetup.YPort] = 113; // adjust Y motor speed as X motor produces almost twice as much speed (0.56)
                    // robot.SpeedSettings[RobotSetup.PenPort] = 127;

                    // scanner
                    robot.SpeedSettings[RobotSetup.XPort]   = 16;
                    robot.SpeedSettings[RobotSetup.YPort]   = 113; // adjust Y motor speed as X motor produces almost twice as much speed (0.56)
                    robot.SpeedSettings[RobotSetup.PenPort] = 127;

                    // calibrate robot
                    LcdConsole.WriteLine("Calibrating...");
                    robot.Calibrate(() => { return(!run); });

                    // Set the TcpListener on port 13000.
                    Int32 port = 13000;

                    // TcpListener server = new TcpListener(port);
                    server = new TcpListener(IPAddress.Any, port);

                    // Start listening for client requests.
                    server.Start();

                    // Buffer for reading data
                    Byte[] bytes = new Byte[256];

                    // Enter the listening loop.
                    while (run)
                    {
                        LcdConsole.WriteLine("Waiting for a connection... ");

                        // blinking green
                        Buttons.LedPattern(4);

                        // Perform a blocking call to accept requests.
                        // You could also user server.AcceptSocket() here.
                        client = server.AcceptTcpClient();
                        LcdConsole.WriteLine("Connected!");

                        // turn off
                        Buttons.LedPattern(0);

                        // Get a stream object for reading and writing
                        NetworkStream stream = client.GetStream();

                        // if robot is sending data, publish to network channel
                        EventHandler <DataEventArgs> dataCB = (o, e) => {
                            try
                            {
                                byte[] msg = System.Text.Encoding.ASCII.GetBytes(e.Data);
                                stream.Write(msg, 0, msg.Length);
                            }
                            catch (IOException)
                            {
                                // disconnected
                                robot.Off();
                            }
                        };

                        robot.OnData += dataCB;

#if DUMPLOGS
                        // DEBUG
                        byte[] logBuffer = Encoding.ASCII.GetBytes(logs.ToString());
                        client.GetStream().Write(logBuffer, 0, logBuffer.Length);
#endif
                        try
                        {
                            string data = null;

                            int    read;
                            string message = "";
                            // Loop to receive all the data sent by the client.
                            while (run && (read = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                // Translate data bytes to a ASCII string.
                                data = System.Text.Encoding.ASCII.GetString(bytes, 0, read);
                                for (int i = 0; i < read; i++)
                                {
                                    char c = data[i];
                                    if (c != '\0')
                                    {
                                        message += c;
                                    }
                                    else
                                    {
                                        // get message type
                                        IRobotCommand command = RobotCommandFactory.Create(message);
                                        if (command != null)
                                        {
                                            robot.Queue(command);
                                        }
                                        //
                                        message = "";
                                    }
                                }
                            }
                        }
                        catch (IOException)
                        {
                            LcdConsole.Clear();
                            LcdConsole.WriteLine("Disconnected!");

                            // stop sending data
                            robot.OnData -= dataCB;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                /*
                 #if DEBUG
                 * // Set the TcpListener on port 13000.
                 * int port = 13000;
                 *
                 * // TcpListener server = new TcpListener(port);
                 * TcpListener debugServer = new TcpListener(IPAddress.Any, port);
                 *
                 * // Start listening for client requests.
                 * debugServer.Start();
                 *
                 * LcdConsole.WriteLine("Wait debugger");
                 *
                 * // Perform a blocking call to accept requests.
                 * // You could also user server.AcceptSocket() here.
                 * using (TcpClient debugClient = debugServer.AcceptTcpClient())
                 * {
                 *  // Get a stream object for reading and writing
                 *  NetworkStream stream = debugClient.GetStream();
                 *
                 *  foreach (String it in Assembly.GetExecutingAssembly().GetManifestResourceNames())
                 *  {
                 *      byte[] msg = System.Text.Encoding.ASCII.GetBytes(it + "\n");
                 *      // Send back a response.
                 *      stream.Write(msg, 0, msg.Length);
                 *  }
                 *
                 *  while (ex != null)
                 *  {
                 *      byte[] msg = System.Text.Encoding.ASCII.GetBytes(ex.Message + "\n");
                 *      // Send back a response.
                 *      stream.Write(msg, 0, msg.Length);
                 *
                 *      msg = System.Text.Encoding.ASCII.GetBytes(ex.StackTrace + "\n");
                 *      // Send back a response.
                 *      stream.Write(msg, 0, msg.Length);
                 *      ex = ex.InnerException;
                 *  }
                 * }
                 *
                 * // Stop listening for new clients.
                 * debugServer.Stop();
                 #else
                 * throw;
                 #endif
                 */
                throw;
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }
        }
Exemple #7
0
        /// <summary>
        /// Write stuff to the display.
        /// </summary>
        /// <param name="lcd">The display driver</param>
        public static void WriteTest(ICharacterLcd lcd)
        {
            LcdConsole console = new LcdConsole(lcd, "A00", false);

            console.LineFeedMode = LineWrapMode.Truncate;
            Console.WriteLine("Nowrap test:");
            console.Write("This is a long text that should not wrap and just extend beyond the display");
            console.WriteLine("This has CRLF\r\nin it and should \r\n wrap.");
            console.Write("This goes to the last line of the display");
            console.WriteLine("This isn't printed, because it's off the screen");
            Console.ReadLine();
            Console.WriteLine("Autoscroll test:");
            console.LineFeedMode = LineWrapMode.Wrap;
            console.WriteLine();
            console.WriteLine("Now the display should move up.");
            console.WriteLine("And more up.");
            for (int i = 0; i < 20; i++)
            {
                console.WriteLine($"This is line {i + 1}/{20}, but longer than the screen");
                Thread.Sleep(10);
            }

            console.LineFeedMode = LineWrapMode.Wrap;
            console.WriteLine("Same again, this time with full wrapping.");
            for (int i = 0; i < 20; i++)
            {
                console.Write($"This is string {i + 1}/{20} longer than the screen");
                Thread.Sleep(10);
            }

            Console.ReadLine();
            Console.WriteLine("Intelligent wrapping test");
            console.LineFeedMode = LineWrapMode.WordWrap;
            console.WriteLine("Now intelligent wrapping should wrap this long sentence at word borders and ommit spaces at the start of lines.");
            Console.WriteLine("Not wrappable test");
            Console.ReadLine();
            console.WriteLine("NowThisIsOneSentenceInOneWordThatCannotBeWrapped");
            Console.ReadLine();
            Console.WriteLine("Individual line test");
            console.Clear();
            console.LineFeedMode = LineWrapMode.Truncate;
            console.ReplaceLine(0, "This is all garbage that will be replaced");
            console.ReplaceLine(0, "Running clock test");
            int  left      = console.Size.Width;
            Task?alertTask = null;

            // Let the current time move trought the display on line 1
            while (!Console.KeyAvailable)
            {
                DateTime now       = DateTime.Now;
                String   time      = String.Format(CultureInfo.CurrentCulture, "{0}", now.ToLongTimeString());
                string   printTime = time;
                if (left > 0)
                {
                    printTime = new string(' ', left) + time;
                }
                else if (left < 0)
                {
                    printTime = time.Substring(-left);
                }

                console.ReplaceLine(1, printTime);
                left--;
                // Each full minute, blink the display (but continue writing the time)
                if (now.Second == 0 && alertTask == null)
                {
                    alertTask = console.BlinkDisplayAsync(3);
                }

                if (alertTask != null && alertTask.IsCompleted)
                {
                    // Ensure we catch any exceptions (there shouldn't be any...)
                    alertTask.Wait();
                    alertTask = null;
                }

                Thread.Sleep(500);
                // Restart when the time string has left the display
                if (left < -time.Length)
                {
                    left = console.Size.Width;
                }
            }

            alertTask?.Wait();
            Console.ReadKey();
            Console.WriteLine("Culture Info Test");
            LcdCharacterEncoding encoding = LcdConsole.CreateEncoding(CultureInfo.CreateSpecificCulture("de-CH"), "A00", '?', 8);

            console.LoadEncoding(encoding);
            console.Clear();
            console.ScrollUpDelay = TimeSpan.FromSeconds(1);
            console.LineFeedMode  = LineWrapMode.WordWrap;
            console.WriteLine(@"Die Ratten im Gemäuer, englischer Originaltitel ""The Rats in the Walls"" " +
                              "ist eine phantastische Kurzgeschichte des amerikanischen Schriftstellers H. P. Lovecraft. Das etwa " +
                              "8000 Wörter umfassende Werk wurde zwischen August und September 1923 verfasst und erschien erstmals " +
                              "im März 1924 im Pulp-Magazin Weird Tales. Der Titel bezieht sich auf das Rascheln von Ratten in den " +
                              "Gemäuern des Familienanwesens, das der Erzähler Delapore nach 300 Jahren auf den Ruinen des Stammsitzes " +
                              "seiner Vorfahren neu errichtet hat. Im Verlauf der Erzählung führen die Ratten Delapore zur Entdeckung " +
                              "des grausigen Geheimnisses der Gruft seines Anwesens und der finsteren Vergangenheit seiner Familie. " +
                              "Nach Lovecraft entstand die Grundidee für die Geschichte, als eines späten Abends seine Tapete zu knistern begann. " +
                              "(von https://de.wikipedia.org/wiki/Die_Ratten_im_Gem%C3%A4uer, CC-BY-SA 3.0)");
            console.WriteLine("From A00 default map: ");
            console.WriteLine("Code: [{|}]^_\\");
            console.WriteLine("Greek: Ωαβεπθμ");
            console.WriteLine("Others: @ñ¢");
            console.WriteLine("Math stuff: ∑÷×∞");

            console.WriteLine("German code page");
            console.WriteLine("Umlauts: äöüßÄÜÖ");
            console.WriteLine("Äußerst ölige, überflüssige Ölfässer im Großhandel von Ützhausen.");
            console.WriteLine("Currency: ¥€£$");
            encoding = LcdConsole.CreateEncoding(CultureInfo.CreateSpecificCulture("fr-fr"), "A00", '?', 8);
            console.LoadEncoding(encoding);
            console.Clear();
            console.WriteLine("Le français est une langue indo-européenne de la famille des langues romanes. " +
                              "Le français s'est formé en France. Le français est déclaré langue officielle en France en 1539. " +
                              "Après avoir été sous l'Ancien Régime la langue des cours royales et princières, " +
                              "des tsars de Russie aux rois d'Espagne et d'Angleterre en passant par les princes de l'Allemagne, " +
                              "il demeure une langue importante de la diplomatie internationale aux côtés de l'anglais. ");

            encoding = LcdConsole.CreateEncoding(CultureInfo.CreateSpecificCulture("da-da"), "A00", '?', 8);
            console.LoadEncoding(encoding);
            console.Clear();
            console.WriteLine("Dansk er et nordgermansk sprog af den østnordiske (kontinentale) gruppe, " +
                              "der tales af ca. seks millioner mennesker. Det er stærkt påvirket af plattysk. Dansk tales " +
                              "også i Sydslesvig (i Flensborg ca. 20 %) samt PÅ FÆRØER OG GRØNLAND.");

            Console.ReadLine();
            Console.WriteLine("Japanese test");
            encoding = LcdConsole.CreateEncoding(CultureInfo.CreateSpecificCulture("ja-ja"), "A00", '?', 8);
            console.LoadEncoding(encoding);
            console.WriteLine("What about some japanese?");
            console.WriteLine("イロハニホヘト");
            console.WriteLine("チリヌルヲ");
            console.WriteLine("ワカヨタレソ");
            console.WriteLine("ツネナラム");
            console.WriteLine("ウヰノオクヤマ");
            console.WriteLine("ケフコエテ");
            console.WriteLine("アサキユメミシ");
            console.WriteLine("ヱヒモセス");
            console.Clear();
            console.Write("Test finished");
            console.Dispose();
        }
Exemple #8
0
        private static bool Start(Lcd lcd, Buttons btns)
        {
            if (taskID == taskFind)
            {
                t = new Find();
            }
            else if (taskID == taskEscape)
            {
                t = new Escape();
            }
            else
            {
                //unknown task ID
                return(false);
            }

            //clear previous log messages
            LcdConsole.Clear();

            //set enemy color
            t.enemyColor = enemyColor;

            //init
            int oldLog = Log.level;

            Log.level = Log.LEVEL_ERROR;

            lcd.Clear();
            Rectangle textRect = new Rectangle(new Point(0, Lcd.Height - (int)font.maxHeight - 2), new Point(Lcd.Width, Lcd.Height - 2));

            lcd.WriteTextBox(font, textRect, "initializing...", true, Lcd.Alignment.Center);
            lcd.Update();

            t.Init();

            InfoDialog InitFinishedDialog = new InfoDialog(font, lcd, btns, "Press ENTER to start", true, "Init finished");

            InitFinishedDialog.Show();

            Log.level = oldLog;
            running   = true;

            ButtonEvents be = new ButtonEvents();

            be.EscapePressed += Stop;

            try {
                t.Start();
            }
            catch (Exception e) {
                InfoDialog dialog = new InfoDialog(font, lcd, btns, e + " Exception caught.", true, "Init finished");
                dialog.Show();
                return(false);
            }

            //wait for task to finish
            while (running)
            {
                Thread.Sleep(50);
            }

            be.EscapePressed -= delegate() {
                t.Stop();
                running = false;
            };

            //unregister event
            be.EscapePressed -= Stop;
            //let the GC free the memory
            t = null;

            return(true);
        }
Exemple #9
0
 public void Do(IRobot robot)
 {
     LcdConsole.Clear();
 }
Exemple #10
0
        /// <summary>
        /// Starts the SuperCar
        /// </summary>
        public void Start()
        {
            // Program stop event
            ManualResetEvent terminateProgram = new ManualResetEvent(false);

            // Welcome messages
            LcdConsole.WriteLine("SuperCar running");
            LcdConsole.WriteLine("Enter to start");
            LcdConsole.WriteLine("Left to steer left");
            LcdConsole.WriteLine("Right to steer right");
            LcdConsole.WriteLine("Esc to terminate");

            // Button events
            ButtonEvents buts = new ButtonEvents();

            // Enter button
            buts.EnterPressed += () =>
            {
                LcdConsole.WriteLine("Application Started");
                sensorUpdateThread.Start();
                steerPID.Start();
                driveThread.Start();
                lCDThread.Start();
            };

            // Right button
            buts.RightPressed += () =>
            {
            };

            // Left button
            buts.LeftPressed += () =>
            {
            };

            // Escape button
            buts.EscapePressed += () =>
            {
                Lcd.Clear();
                LcdConsole.Clear();
                LcdConsole.WriteLine("Application Terminating...");

                // Termina il thread di aggiornamento dei sensori
                stopSensorUpdate.Set();
                if (sensorUpdateThread.IsAlive)
                {
                    // Ne attende la terminazione se è vivo
                    sensorUpdateThread.Join();
                }
                LcdConsole.WriteLine("Sensors update thread terminated.");

                // Termina il thread di sterzata
                steerPID.Stop();
                LcdConsole.WriteLine("Steer thread terminated.");

                // Termina il thread di guida
                stopDrive.Set();
                if (driveThread.IsAlive)
                {
                    // Ne attende la terminazione se è vivo
                    driveThread.Join();
                }
                LcdConsole.WriteLine("Drive thread thread terminated.");

                // Termina il Thread di update del LCD
                stopLCDThread.Set();
                if (lCDThread.IsAlive)
                {
                    // Ne attende la terminazione
                    lCDThread.Join();
                }
                LcdConsole.WriteLine("LCD thread thread terminated.");
                LcdConsole.WriteLine("Application terminated.");

                // Spegne tutti i motori
                leftEngine.Off();
                rightEngine.Off();
                steerWheel.Off();

                // Aspetta un pochino
                Thread.Sleep(1000);

                // E termina
                terminateProgram.Set();
            };

            terminateProgram.WaitOne();
        }