Advertisement
Guest User

Untitled

a guest
Jul 19th, 2010
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO.Ports;          // Serial stuff in here.
  6.  
  7. namespace Serial
  8. {
  9.     class Program
  10.     {
  11.         static SerialPort port = new SerialPort();  // Serial port object from System.IO.Ports
  12.         static int baud;                            // Storage for the baud of the port
  13.         static string name;                         // Storage for the baud of the port
  14.         static string command;                      // Storage for the command
  15.  
  16.         static void Main(string[] args)             // No args accepted... yet?
  17.         {
  18.             Console.ForegroundColor = ConsoleColor.DarkBlue;    // Change text colour
  19.             Console.WriteLine("Welcome! Please enter a command to begin.");
  20.             Console.ResetColor();                   // Return to normal colour
  21.             Console.WriteLine("");
  22.             Console.WriteLine("/quit to exit program, /help to see more commands");
  23.             for (; ; )                              // Do this for ever
  24.             {
  25.                 Console.WriteLine(" ");             // Gap between each item
  26.                 Console.Write("> ");                // Got to love the chevron
  27.                 command = Console.ReadLine();       // Store the command.
  28.                 try
  29.                 {
  30.                     if (command.ToCharArray()[0] == '/')        // See if it is a function or a message,  you could change this if you'd rather something else
  31.                     {
  32.                         Console.ForegroundColor = ConsoleColor.Green;
  33.                         if (command.ToLower() == "/baud")
  34.                         {
  35.                             Console.WriteLine("Closing Port...");
  36.                             port.Close();                   // Got to do this, or things go kerfooy
  37.                             Console.Write("Baud Rate: ");
  38.                             baud = GetBaudRate();           // Get new baud rate
  39.                             Console.WriteLine("Opening Port...");
  40.                             BeginSerial(baud, name);        // Reopen with old port name kept
  41.                         }
  42.                         if (command.ToLower() == "/showbaud")
  43.                         {
  44.                             Console.ForegroundColor = ConsoleColor.Yellow;      // Information goes in yellow
  45.                             Console.Write("Baud Rate: ");  
  46.                             Console.Write(port.BaudRate.ToString());
  47.                             Console.ResetColor();
  48.                         }
  49.                         if (command.ToLower() == "/showport")
  50.                         {
  51.                             Console.ForegroundColor = ConsoleColor.Yellow;      // Information goes in yellow
  52.                             Console.Write("Port Name: ");
  53.                             Console.Write(port.PortName.ToString());
  54.                             Console.ResetColor();
  55.                         }
  56.                         if (command.ToLower() == "/quit")
  57.                         {
  58.                             if (port.IsOpen)        // See whether it needs closing or not
  59.                             {
  60.                                 Console.WriteLine("Closing Port...");
  61.                                 port.Close();
  62.                             }
  63.                             else
  64.                             {
  65.                                 Console.WriteLine("Port closed already.");
  66.                             }
  67.                             Console.WriteLine("Quitting. Goodbye!");
  68.                             Console.ReadKey();
  69.                             Environment.Exit(Environment.ExitCode);     // Can't use break; because some situations restart this
  70.                                                                         // method inside itself, bad practice, but the easiest
  71.                                                                         // method of doing it.
  72.                         }
  73.                         if (command.ToLower() == "/reconnect")
  74.                         {
  75.                             Console.Title = "Serial Terminal - Connection Closed";
  76.  
  77.                             Console.WriteLine("Restarting...");
  78.                             Console.WriteLine("Closing Port...");
  79.                             port.Close();
  80.                             Console.ResetColor();
  81.                             Main(null);     // Oh look, bad practice, remember Environment.Exit() to close this now...
  82.                             return;         // Ok, so it isn't all bad, at least when the new main finishes this should too...
  83.                         }
  84.                         if (command.ToLower() == "/drop")
  85.                         {
  86.                             Console.WriteLine("Dropping connection");
  87.                             Console.WriteLine("Removing Event...");
  88.                             port.DataReceived -= port_DataReceived;
  89.                             Console.WriteLine("Closing port...");
  90.                             port.Close();
  91.                             Console.WriteLine("Connection Dropped.");
  92.                             Console.Title = "Serial Terminal - Connection Closed";
  93.                         }
  94.                         if (command.ToLower() == "/open")
  95.                         {
  96.                             if (!port.IsOpen)       // We need to open it then!
  97.                             {
  98.                                 Console.WriteLine("Opening connection");
  99.                                 Console.WriteLine("Opening port...");
  100.                                 Console.ForegroundColor = ConsoleColor.Yellow;
  101.                                 Console.WriteLine("Baud: " + baud);
  102.                                 Console.WriteLine("Port: " + name);
  103.                                 Console.ResetColor();
  104.                                 BeginSerial(baud, name);
  105.                                 Console.WriteLine("Connection Opened.");
  106.  
  107.                             }
  108.                             else                    // Awesome, well, lets tell the suckers what is going on... the title should tell them though!
  109.                             {
  110.                                 Console.ForegroundColor = ConsoleColor.Yellow;
  111.                                 Console.WriteLine("Port " + port.PortName + " already open at " + port.BaudRate.ToString() + " baud");
  112.                                 Console.ResetColor();
  113.                             }
  114.                         }
  115.                         if (command.ToLower() == "/rts")
  116.                         {
  117.                             Console.WriteLine("Toggling RTS");
  118.                             port.RtsEnable = !port.RtsEnable;
  119.                             Console.WriteLine("RTS: " + port.RtsEnable.ToString());
  120.                         }
  121.                         if (command.ToLower() == "/dtr")
  122.                         {
  123.                             Console.WriteLine("Toggling DTR - Resets Arduino!");
  124.                             Console.Write("Continue anyway? [y/n] n: ");
  125.                             string choice = Console.ReadLine();         // Aww, aren't I nice? Preventing people from accidently resetting their xxDuino
  126.                             if (choice.ToLower() == "y" || choice.ToLower() == "yes")
  127.                             {
  128.                                 port.DtrEnable = !port.DtrEnable;
  129.                                 Console.WriteLine("DTR: " + port.DtrEnable.ToString());
  130.                             }
  131.                         }
  132.                         if (command.ToLower() == "/][" || command.ToLower() == "/about")    // ][ looks cool OK!
  133.                         {
  134.                             Console.ForegroundColor = ConsoleColor.DarkBlue;
  135.                             Console.BackgroundColor = ConsoleColor.White;
  136.                             Console.Clear();
  137.                             Console.WriteLine("                      == Serial Terminal 1.0 About =="); // Blah blah blah...
  138.                             Console.WriteLine("");
  139.                             Console.WriteLine("By Simon Cooksey, 2010.");
  140.                             Console.WriteLine("");
  141.                             Console.WriteLine("Please, share this program to friends family and strangers too.  Note it comes");
  142.                             Console.WriteLine("  with no waranty what-so-ever and may not be sold or be fit for purpose.  I am");
  143.                             Console.WriteLine("  not responsible for loss of data, software or damage of hardware due to the");
  144.                             Console.WriteLine("  use of this program.  Use it at your own risk!  I don't think it will mess up");
  145.                             Console.WriteLine("  anything though, you should be OK. Press any key to continue.");
  146.                             Console.ReadLine();
  147.                             Console.BackgroundColor = ConsoleColor.Black;
  148.                             Console.Clear();
  149.                         }
  150.                         if (command.ToLower() == "/clear" || command.ToLower() == "/cls")       // cls because it is used in CMD too... people like this stuff.
  151.                         {
  152.                             Console.Clear();    // Ooh but a cluttered console screen looks better... is this really needed
  153.                         }
  154.                         if (command.ToLower() == "/help")
  155.                         {
  156.                             Console.ForegroundColor = ConsoleColor.Yellow;
  157.                             Console.WriteLine("                      == Command Help == ");     // COULD YOU NOT TELL FROM THE CODE :O
  158.                             Console.WriteLine("");
  159.                             Console.WriteLine(" /help              This Menu");
  160.                             Console.WriteLine(" /baud              Set Baud rate");
  161.                             Console.WriteLine(" /showBaud          View Connection Baud Rate");
  162.                             Console.WriteLine(" /showPort          View Connected Port");
  163.                             Console.WriteLine(" /reconnect         Change both port and baud (pretty much resets the program)");
  164.                             Console.WriteLine(" /drop              Closes a connection, but keeps settings");
  165.                             Console.WriteLine(" /open              Opens a connection from settings in memory");
  166.                             Console.WriteLine(" /rts               Toggles RTS");
  167.                             Console.WriteLine(" /dtr               Toggles DTR - Resets an Arduino. Be careful!");
  168.                             Console.WriteLine("");
  169.                             Console.WriteLine(" /quit              Exit this program");
  170.                             Console.ResetColor();
  171.                         }
  172.                         if (command.ToLower() == "/connect")
  173.                         {
  174.                             Connect();      // Duh.
  175.                         }
  176.  
  177.  
  178.                         Console.ResetColor();
  179.                     }
  180.                     else
  181.                     {
  182.                         if (port.IsOpen)
  183.                         {
  184.                             port.Write(command);        // Oh, ok, so it wasn't an instruction to the program?  Ok then.  I can pass on a message...
  185.                         }
  186.                         else
  187.                         {
  188.                             Console.ForegroundColor = ConsoleColor.Red;     // SHIT!
  189.                             Console.WriteLine("Invalid command - port closed. Type /help for a list of commands");  // DOUCHE, open a port first!
  190.                             Console.ResetColor();                           // Few, back to white on black...
  191.                         }
  192.                     }
  193.                 }
  194.                 catch
  195.                 {
  196.                     // Erm.. something went wrong, but face it I can't be bothered to fix it...
  197.                 }
  198.             }   // End of that there for(;;) loop.
  199.         }
  200.  
  201.         static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
  202.         {
  203.             Console.Title = "Serial Terminal - Receiving data...";  // Oooh, perty data... Wonder what it says...
  204.             Console.Write("Received: ");
  205.             /*
  206.             byte[] buffer = new byte[port.BytesToRead];
  207.             int bytesRead = port.Read(buffer, 0, buffer.Length);
  208.  
  209.             // message has successfully been received
  210.             Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytesRead));
  211.              */
  212.            
  213.             for (int i = 0; i < (2000 * port.BytesToRead); i++)
  214.                 ;       //Delay a bit for the serial to catch up, its not as fast as the CPU so if I'm not careful I accidently split packets...
  215.             Console.Write(port.ReadExisting());
  216.            
  217.             Console.Title = "Serial Terminal - Connection Open on " + name + " @ " + baud + " baud";
  218.             Console.WriteLine("");
  219.             Console.Write("> ");
  220.         }
  221.  
  222.         static void BeginSerial(int baud, string name)
  223.         {
  224.             try
  225.             {
  226.                 port = new SerialPort(name, baud);
  227.                 port.Open();
  228.                 port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
  229.                 Console.Title = "Serial Terminal - Connection Open on " + name + " @ " + baud + " baud";
  230.  
  231.             }
  232.             catch (Exception e)
  233.             {
  234.                 Console.Title = "Serial Terminal - Connection Error!";
  235.                 Console.ForegroundColor = ConsoleColor.Red;
  236.                 Console.WriteLine("ERROR! - " + e.Message);
  237.                 Console.ForegroundColor = ConsoleColor.Green;       // ATN this could be cool!
  238.                 Console.WriteLine("                           == Stack Trace ==");
  239.                 Console.ForegroundColor = ConsoleColor.Red;         // AAH! It wasn't, I hate you .NET
  240.                 Console.WriteLine(e.StackTrace);
  241.                 Console.ForegroundColor = ConsoleColor.Yellow;      // OK, getting back to normal...
  242.                 Console.WriteLine("Press any key to resume");
  243.                 Console.ReadKey();                                  // Just press a key and move on...
  244.                 //Console.Clear();
  245.                 Console.ResetColor();                               // Gooood, all done.
  246.                 Console.Title = "Serial Terminal - Connection Closed";
  247.                 Main(null);                                         // BAD to do!
  248.                 return;                                             // OK, could be worse...
  249.                 //goto                                              // Don't even joke about that...
  250.             }
  251.         }
  252.        
  253.         static void Connect()
  254.         {
  255.             Console.Title = "Serial Terminal - Connection Closed";
  256.             Console.ForegroundColor = ConsoleColor.Blue;
  257.             Console.WriteLine("Welcome, enter parameters to begin");
  258.             Console.ResetColor();
  259.             Console.WriteLine(" ");
  260.             Console.ForegroundColor = ConsoleColor.Yellow;
  261.             Console.WriteLine("Available ports:");
  262.             if (SerialPort.GetPortNames().Count() >= 0)
  263.             {
  264.                 foreach (string p in SerialPort.GetPortNames())
  265.                 {
  266.                     Console.WriteLine(p);
  267.                 }
  268.             }
  269.             else
  270.             {
  271.                 Console.WriteLine("No Ports available, press any key to exit.");
  272.                 Console.ReadLine();
  273.                 // Quit
  274.                 return;
  275.             }
  276.             Console.ResetColor();
  277.             Console.Write("Port Name: ");
  278.             name = Console.ReadLine();
  279.             Console.WriteLine(" ");
  280.             Console.Write("Baud rate: ");
  281.             baud = GetBaudRate();
  282.  
  283.             Console.WriteLine(" ");
  284.             Console.WriteLine("Beging Serial...");
  285.             BeginSerial(baud, name);
  286.  
  287.             Console.WriteLine("Serial Started.");
  288.             Console.WriteLine(" ");
  289.         }
  290.  
  291.         static int GetBaudRate()
  292.         {
  293.             try
  294.             {
  295.                 return int.Parse(Console.ReadLine());
  296.             }
  297.             catch
  298.             {
  299.                 Console.ForegroundColor = ConsoleColor.Red;
  300.                 Console.WriteLine("Invalid integer.  Please try again:");
  301.                 Console.ResetColor();
  302.                 return GetBaudRate();
  303.             }
  304.         }
  305.     }
  306. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement