WriteLine() public method

public WriteLine ( string str ) : void
str string
return void
 public static string SMSDevice_Status(string comPort)
 {
     SerialPort port = new SerialPort();
     String operatorString = "Error";
     try
     {
         port.PortName = comPort;
         if (!port.IsOpen)
         {
             port.Open();
         }
         port.WriteLine("AT+CREG?\r");
         Thread.Sleep(2000);
         operatorString = port.ReadExisting();
         return operatorString;
     }
     catch
     {
         return operatorString;
     }
     finally
     {
         port.Close();
     }
 }
Ejemplo n.º 2
0
 public bool demarcateHumidity(double value)
 {
     ReadData();
     if (yqxh == "xce_100")
     {
         string valuestring = (value * 10).ToString("0000");
         ComPort_1.WriteLine("B");
         int    len            = valuestring.Length;
         int    len1           = 4 - len;
         byte[] ledStringArray = System.Text.Encoding.Default.GetBytes(valuestring.Trim());
         for (int i = 0; i < len1; i++)
         {
             ComPort_1.WriteLine("0");
         }
         for (int i = 0; i < len; i++)
         {
             ComPort_1.Write(ledStringArray, i, 1);
         }
         ComPort_1.WriteLine("P");
         return(true);
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 3
0
 private void trackBar2_ValueChanged(object sender, EventArgs e)
 {
     if (com != null)
     {
         com.WriteLine("UD" + angel[Convert.ToInt16(trackBar2.Value)]);
     }
 }
Ejemplo n.º 4
0
        public static bool connectDisplay(SerialPort serial)
        {
            if (serial == null || !serial.IsOpen)
            {
                throw new Exception(StringResource.E00001);
            }

            string accessString = "";
            try
            {
                accessString = serial.ReadLine();
            }
            catch (Exception)
            {
                //if Display is idle. Try to close it and reconnect
                serial.WriteLine("close:");

                try
                {
                    accessString = serial.ReadLine();
                }
                catch (TimeoutException)
                {
                    return false;
                }
            }

            if (accessString == DisplayToAppAccessString)
            {

                serial.WriteLine(AppToDisplayAccessString);
                return true;
            }
            return false;
        }
Ejemplo n.º 5
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "Снять показания")
            {
                switch (comboBox2.Text)
                {
                case "1":
                    Serial.WriteLine("1");
                    break;

                case "2":
                    Serial.WriteLine("2");
                    break;

                case "3":
                    Serial.WriteLine("3");
                    break;

                case "4":
                    Serial.WriteLine("4");
                    break;
                }

                button3.Enabled = true;



                comboBox2.Enabled = false;
                button1.Enabled   = false;


                textBox1.Text = " ";
                textBox2.Text = " ";
                textBox3.Text = " ";
                textBox4.Text = " ";
                textBox5.Text = " ";



                button2.Text = "Остановить";
            }
            else
            {
                try
                {
                    Serial.WriteLine("1");
                    Thread.Sleep(10);


                    button3.Enabled   = false;
                    comboBox2.Enabled = true;
                    button1.Enabled   = true;
                    button2.Text      = "Снять показания";
                }
                catch { }
            }
        }
Ejemplo n.º 6
0
        private void _output()
        {
            string empty = string.Empty;
            bool   flag  = false;

            while (_thread_active)
            {
                try
                {
                    if (!_ser_out.IsOpen)
                    {
                        if (_sending_active)
                        {
                            try
                            {
                                _ser_out.Open();
                                _ser_out.NewLine = string.Empty + (object)'\r';
                                _ser_out.WriteLine("!Timeout=05");
                            }
                            catch
                            {
                            }
                        }
                    }
                    if (_ser_out.IsOpen)
                    {
                        if (_horn != flag)
                        {
                            flag = _horn;
                            if (_ser_out.IsOpen)
                            {
                                if (flag)
                                {
                                    _ser_out.WriteLine("!On");
                                }
                                else
                                {
                                    _ser_out.WriteLine("!Off");
                                }
                            }
                        }
                        else
                        {
                            Thread.Sleep(_refresh_interval);
                        }
                    }
                    else
                    {
                        Thread.Sleep(_refresh_interval);
                    }
                }
                catch
                {
                }
            }
        }
Ejemplo n.º 7
0
        private void btnStartStopLogging_Click(object sender, RoutedEventArgs e)
        {
            if (((string)btnStartStopLogging.Content) == "Start")
            {//starting logging
                if (txtFileName.Text.Length > 0)
                {
                    if (!System.IO.Directory.Exists("Results"))
                    {
                        System.IO.Directory.CreateDirectory("Results");
                    }
                    if (!System.IO.Directory.Exists("Results\\" + txtFileName.Text + "\\"))
                    {
                        System.IO.Directory.CreateDirectory("Results\\" + txtFileName.Text + "\\");
                    }

                    string fName = "Results\\" + txtFileName.Text + "\\" + iSetUpDown.Value.ToString() + ".csv";
                    if (System.IO.File.Exists(fName))
                    {
                        MessageBoxResult result = MessageBox.Show("Overwrite Existing File?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.No)
                        {
                            return;
                        }
                    }
                    //if we get here then the user is okay to overwrite the file
                    currentFile = fName;
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(currentFile, false))//no append here
                    {
                        sw.WriteLine(String.Format("Recording,{0}", txtFileName.Text));
                        sw.WriteLine(String.Format("Current Setpoint,{0}", iSetUpDown.Value));
                        sw.WriteLine(String.Format("Low Voltage Stop,{0}", vStopUpDown.Value));
                        sw.WriteLine("Seconds, Voltage, Current, mAh, mWh");
                    }
                    startTime = DateTime.Now;

                    _serialPort.WriteLine("set " + iSetUpDown.Value.ToString());
                    _serialPort.WriteLine("uvlo " + vStopUpDown.Value.ToString());
                    iSetUpDown.IsEnabled  = false;
                    vStopUpDown.IsEnabled = false;
                    pastReadings.Clear();
                    chart.DataContext           = pastReadings;
                    btnStartStopLogging.Content = "Stop";
                    fileStarted = true; filePaused = false;
                }
            }
            else
            {//stopping logging
                fileStarted = false; filePaused = false;
                _serialPort.WriteLine("set 0");
                iSetUpDown.IsEnabled        = true;
                vStopUpDown.IsEnabled       = true;
                btnStartStopLogging.Content = "Start";
            }
        }
Ejemplo n.º 8
0
 public void SendData()
 {
     if (serialPort.IsOpen)
     {
         if (IsWrite)
         {
             serialPort.Write(ScreenText);
         }
         else
         {
             serialPort.WriteLine(ScreenText);
         }
     }
 }
Ejemplo n.º 9
0
        private bool identify(ref Dictionary<string, Arduino> _ArduinoMap, string _potentialArduino) {
            if (!_ArduinoMap.ContainsKey(_potentialArduino)) {
                SerialPort temp;
                try {
                    temp = new SerialPort(_potentialArduino);
                    temp.Open();
                    string toWrite = Arduino_Codes.IDENTITY_QUERY;
                    temp.DiscardOutBuffer();
                    temp.DiscardInBuffer();
                    Thread.Sleep(100);
                    temp.WriteLine(toWrite);
                    Thread.Sleep(200);
                    temp.WriteLine(toWrite);
                    Thread.Sleep(200);
                    string ID = temp.ReadExisting();
                    if (ID.Contains(Arduino_Codes.ARM_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.ARM_IDENTITY, new Arduino(temp, Arduino_Codes.ARM_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.HAND_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.HAND_IDENTITY, new Arduino(temp, Arduino_Codes.HAND_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.DRIVEFRONT_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.DRIVEFRONT_IDENTITY, new Arduino(temp, Arduino_Codes.DRIVEFRONT_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.DRIVEBACK_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.DRIVEBACK_IDENTITY, new Arduino(temp, Arduino_Codes.DRIVEBACK_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.PT_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.PT_IDENTITY, new Arduino(temp, Arduino_Codes.PT_IDENTITY));
                        return true;
                    }

                    temp.Dispose(); //Gets rid of safe handle issue! Or at least appears to!
                }
                catch {
                    return false;
                }
            }
            return false;
        }
Ejemplo n.º 10
0
        public static void setLCDText(SerialPort serial, string text)
        {
            if (serial == null || !serial.IsOpen)
            {
                throw new Exception(StringResources.E00001);
            }

            string[] splitedStr = text.Split('\n');
            serial.WriteLine("lcd:print:" + splitedStr.Length);
            serial.WriteLine(splitedStr[0]);
            if (splitedStr.Length > 1)
            {
                serial.WriteLine(splitedStr[1]);
            }
        }
Ejemplo n.º 11
0
        private void Wyslij(string numer, string wiadomosc)
        {
            //inicjalizacja zmiennej port z domyślnymi wartościami
            port = new SerialPort();
            //ustawienie timeoutów aby program się nie wieszał
            port.ReadTimeout  = 500;
            port.WriteTimeout = 500;

            sPortName = textBox3.Text;
            string sBaud   = "9600";
            string sData   = "8";
            string sParity = "None";
            string sStop   = "One";

            port.PortName = sPortName;
            port.BaudRate = Int32.Parse(sBaud);
            port.DataBits = Int32.Parse(sData);
            port.Parity   = (Parity)Enum.Parse(typeof(Parity), sParity);
            port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), sStop);

            port.Open();
            Pauza();
            port.Write("at" + (char)13); // TODO: przy pierwszej komendzie ATodem zwraca "ERROR" zamiast "OK" ?
            Pauza();
            port.Write("at+cmgf=1" + (char)13);
            Pauza();
            port.Write("at+cmgs=" + (char)34 + numer + (char)34 + (char)13);
            Pauza();
            port.WriteLine(wiadomosc + (char)26 + (char)13);
            Pauza();
            port.Close();
        }
Ejemplo n.º 12
0
        public void Connect()
        {
            try
            {
                m_serialPort = new SerialPort(Properties.Settings.Default.LambdaZupAddress);
                m_serialPort.BaudRate = 9600;
                m_serialPort.Parity = Parity.None; 
                m_serialPort.DataBits = 8;
                m_serialPort.StopBits = StopBits.One;
                m_serialPort.Handshake = Handshake.XOnXOff;
                m_serialPort.ReadTimeout = 2000;
                m_serialPort.WriteTimeout = 1000;

                m_serialPort.DtrEnable = true;
                m_serialPort.RtsEnable = true;


                m_serialPort.Open();
                m_serialPort.WriteLine(":ADR01;:MDL?;");
            }
            catch (Exception ex)
            {
                 throw new SBJException("Cannot Connect to LambdaZup device", ex);
            }
        }
        public JanelaPrincipal()
        {
            InitializeComponent();

            // Atribui o valor zero a posição
            posicao = 0;

            /* Cria um novo objeto SerialPort
             * Que conecta a porta "COM3"
             * E utiliza um Baud Rate (Taxa de Transmissão de dados) de 9600
             */
            porta = new SerialPort("COM3", 9600);

            //Verifica se a porta não está aberta
            if (!porta.IsOpen)
            {
                // Abre a porta
                porta.Open();

                /* Envia o valor "000", para que o
                 * motor volte para a possição 0
                 */
                porta.WriteLine("000");
            }
        }
Ejemplo n.º 14
0
        //ready
        //c_G?RS??FjS? fJ[??
        //[Vendor: www.ai-thinker.com Version:0.9.2.4]
        //OK
        //ready
        //FAIL
        private static string getIP(SerialPort sp)
        {
            string cmd = "AT+CIFSR";
            string result;
            string tmp;
            while (true) {
                do {
                    tmp = sp.ReadExisting();
                    Console.WriteLine(tmp);
                } while (tmp != "");
                sp.WriteLine(cmd);
                Thread.Sleep(1000);
                int end = 0, findMsg = 0; ;
                int resultReadCnt = 10;
                while ((findMsg == 0 || end == 0) && resultReadCnt-- > 0) {
                    result = sp.ReadExisting();
                    if (result.Contains(cmd)) findMsg = 1;
                    Console.WriteLine(result);
                    if (findMsg != 0 && ( result.Contains("192.168.16.") || result.Contains("192.168.137.") || result.Contains("192.168.10."))) return result; //Nieładnie, ale na razie - czekamy na IP
                    if (findMsg != 0 && result.Contains("0.0.0.0")) { Thread.Sleep(1000); break; } //Ponawiamy
                    Thread.Sleep(1000);
                }
                Thread.Sleep(5000);
            }

            return null;
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            //SerialPort com4 = new SerialPort("COM4", 4800, Parity.None, 8, StopBits.One);
            _com4 = new SerialPort("COM4", 38400, Parity.None, 8, StopBits.One);
            _com4.DataReceived += (sender1, e1) =>
            {
                SerialPort port = sender1 as SerialPort;
                string line = port.ReadLine();
                Console.WriteLine(line);
            };
            _com4.Open();

            //drive one reading from each measure available
            Exec("$ID");

            Console.ReadLine();
            Console.WriteLine("start reading:");
            Exec("$MM,2"); //slope distance
            Exec("$GO");
            Exec("$MM,4"); //height
            Exec("$GO");
            Console.ReadLine();
            Exec("$MM,5");
            Exec("$MM");
            Exec("$GO");
            Console.WriteLine("done");
            Console.ReadLine();

            string input;
            while ((input = Console.ReadLine()) != null)
            {
                _com4.WriteLine(input + "\r\n");
            }
        }
Ejemplo n.º 16
0
        static string Call(string port_name)
        {
            try
            {
                Serial = new SerialPort(port_name, 38400, System.IO.Ports.Parity.None, 8, StopBits.One);

                Serial.Open();
                Thread.Sleep(10);

                Serial.WriteLine("0");
                Serial.ReadTimeout = 1000;
            }
            catch {
            }
            try
            {
                string ans = Serial.ReadLine();
                Serial.Close();
                ans = ans.Trim();
                return(ans);
            }
            catch
            {
                return("0");
            }
        }
Ejemplo n.º 17
0
        public static void Main(String[] Arguments)
        {
            foreach (var _COMPort in SerialPort.GetPortNames())
                Console.WriteLine(_COMPort);

            COMPort = new SerialPort("COM14", 9600, Parity.None, 8, StopBits.One);
            COMPort.DataReceived += (s, e) => Console.Write(COMPort.ReadExisting());
            COMPort.ReadTimeout  = 4000;
            COMPort.WriteTimeout = 6000;

            try
            {
                COMPort.Open();
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine(e.Message);
            }

            do
            {
                var CursorLeftPosition = Console.CursorLeft;
                var line = Console.ReadLine();
                Console.SetCursorPosition(CursorLeftPosition, Console.CursorTop -1);
                COMPort.WriteLine(line);
                Thread.Sleep(250);
            } while (true);
        }
Ejemplo n.º 18
0
 public HamegOsziAdapter(string port, int baudrate)
 {
     try{
     log.Info("Try to connecto to measurment device on port " + port + " with baud rate " + baudrate.ToString());
         dataPort = new SerialPort(port, baudrate);
         dataPort.Open();
         if(!dataPort.IsOpen)
         {
             log.Error("Could not open comport on " + port + " with baudrate " + baudrate);
             dataPort.Close();
             return;
         }
         dataPort.WriteLine("*IDN?");
         System.DateTime start = DateTime.Now;
         while(dataPort.BytesToRead == 0)
         {
             if((DateTime.Now - start).TotalMilliseconds > 1000)
             {
                 log.Error("No device response to *IDN? within 1s!");
                 dataPort.Close();
                 return;
             }
         }
         deviceInfo = dataPort.ReadExisting();
         log.Info("Connected to device " + deviceInfo);
     }
     catch(Exception ex)
     {
         log.Error(ex);
     }
 }
        public double ReadData()
        {
            double Output = 0;

            try
            {
                SerialPortLaser.Open();
                SerialPortLaser.WriteLine("F");
                string input = SerialPortLaser.ReadLine();
                int    index = input.IndexOf("m");
                if (index > 0)
                {
                    input = input.Substring(0, index);
                }

                index  = input.LastIndexOf(":") + 2;
                input  = (input.Substring(index, input.Length - index));
                input  = input.Replace(".", ",");
                Output = Double.Parse(input);
            }
            catch (Exception ex)
            {
                //Ignore
            }
            SerialPortLaser.Close();
            return(Output);
        }
Ejemplo n.º 20
0
        public void ToggleLight(SerialPort oCon)
        {
            oCon.NewLine = "\r\n";
            oCon.ReadTimeout = 1500;

            oCon.WriteLine("ToggleLight!");
        }
Ejemplo n.º 21
0
        public void initComm(string portname)
        {
            if (ComPort != null)
            {
                ComPort.Close();
                state = State.notConnected;
            }

            this.portname = portname;
            try
            {
                ComPort = new SerialPort(this.portname, this.baudrate);
                ComPort.Open();
                state = State.connected;
                ComPort.WriteLine(RESET);
                state = State.reset;
                ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived);
            }
            catch (Exception)
            {
                OnIncomingErrorEvent("WrongComPort");
                try { ComPort.Close(); } catch (Exception) { } // probeer om de ComPort wel te sluiten.
                state = State.notConnected;
            }


        }
Ejemplo n.º 22
0
        /// <summary>
        /// Determines whether [is device connected].
        /// </summary>
        public static bool IsDeviceConnected(string portName)
        {
            using (var sp = new System.IO.Ports.SerialPort(portName, baudRates, parity, dataBits, stopBits))
            {
                sp.Open();

                sp.WriteLine(SendAcknoledge);

                int byteToRead = sp.BytesToRead;
                var inputData  = new byte[byteToRead];

                sp.Read(inputData, 0, byteToRead);



                var readData = System.Text.Encoding.Default.GetString(inputData);

                Console.WriteLine(string.Format(PortFoundMessage, sp.PortName));
                Console.WriteLine(readData);

                var result = readData.StartsWith(ReceivedAcknoledge);

                if (result)
                {
                    SetupDevice(sp, SetupMode.OneData);
                }

                sp.Close();

                return(result);
            }
        }
Ejemplo n.º 23
0
        public static void clearLED(SerialPort serial)
        {
            if (serial == null || !serial.IsOpen)
            {
                throw new Exception(StringResources.E00001);
            }

            serial.WriteLine("led:clear:");
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This is the zMain method.
        /// </summary>
        /// <remarks>
        /// Some more info about zMain.
        /// </remarks>
        public static void Main()
        {
            string name;
            string message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread readThread = new Thread(Read);

            // Create a RegistryKey, which will access the HKEY_USERS
            // key in the registry of this machine.
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey sk = rk.OpenSubKey("SYSTEM\\CURRENTCONTROLSET\\ENUM\\USB");

            // Print out the keys.
            // UPrintKeys("  ", sk);

            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort( "COM6" );

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 1000;
            _serialPort.WriteTimeout = 1000;

            _serialPort.Open();
            _continue = true;
            readThread.Start();

            Console.Write("Name: ");
            name = Console.ReadLine();

            Console.WriteLine("Type QUIT to exit");

            while (_continue)
            {
                message = Console.ReadLine();

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                  try
                  {
                    _serialPort.WriteLine(
                      String.Format("<{0}>: {1}", name, message));
                  }
                  catch
                  {
                    Console.WriteLine("Write Timeout");
                  }
                }
            }

            readThread.Join();
            _serialPort.Close();
        }
Ejemplo n.º 25
0
 public static void close(SerialPort serial)
 {
     if (serial.IsOpen)
     {
         clearLED(serial);
         serial.WriteLine("close:");
         serial.Close();
     }
     PSCloseDevice();
 }
Ejemplo n.º 26
0
 public void WriteLine(string data)
 {
     if (!serialport.IsOpen)
     {
         Open();
     }
     if (serialport.IsOpen)
     {
         serialport.WriteLine(data);
     }
 }
Ejemplo n.º 27
0
        private void m_wndRead_Click(object sender, EventArgs e)
        {
            //端口名、波特率、奇偶校验位、数据位和停止位
            m_Receiver = new System.IO.Ports.SerialPort(m_wndPortNames.SelectedItem.ToString(), 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
            m_Receiver.DataReceived += m_Receiver_DataReceived;
            if (!m_Receiver.IsOpen)
            {
                m_Receiver.Open();
            }

            m_Receiver.WriteLine(m_wndText.Text.Trim());
        }
Ejemplo n.º 28
0
        public void SerialPortSetup()
        {
            string         name;
            string         message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread         readThread     = new Thread(Read);

            // Allow the user to set the appropriate properties.
            //_serialPort.PortName = SetPortName(_serialPort.PortName);
            //_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
            //_serialPort.Parity = SetPortParity(_serialPort.Parity);
            //_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
            //_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
            //_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

            // Set the read/write timeouts
            _serialPort.ReadTimeout  = 500;
            _serialPort.WriteTimeout = 500;

            // Attach a method to be called when there
            // is data waiting in the port's buffer
            _serialPort.DataReceived += new
                                        SerialDataReceivedEventHandler(port_DataReceived);
            // Begin communications
            _serialPort.Open();
            _continue = true;
            readThread.Start();

            System.Diagnostics.Debug.Write("Name: ");
            //name = Console.ReadLine();
            name = "ABC";

            System.Diagnostics.Debug.WriteLine("Type QUIT to exit");

            while (_continue)
            {
                //message = Console.ReadLine();
                message = "Helloe";

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    _serialPort.WriteLine(
                        System.String.Format("<{0}>: {1}", name, message));
                }
            }

            readThread.Join();
            _serialPort.Close();
        }
Ejemplo n.º 29
0
        private void UpdateAyam()
        {
            try
            {
                System.ComponentModel.IContainer components = new System.ComponentModel.Container();
                myport = new SerialPort(components);
                myport.BaudRate = 9600;
                myport.PortName = portname;
                myport.Open();

                string RXstring = myport.ReadLine();
                myport.WriteLine("5");
                ayam.suhu = RXstring + " °C";
                myport.WriteLine("6");
                RXstring = myport.ReadLine();
                ayam.kelembaban = RXstring + " %";
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 30
0
 private void button1_Click(object sender, EventArgs e)
 {
     string[] allport = null;
     try
     {
         allport = SerialPort.GetPortNames();
     }
     catch (Exception ex)
     {
     }
     for (int i = 180; i > 0; i--)
     {
         angel.Add(i);
     }
     if (com != null)
     {
         com.Close();
         com = null;
     }
     com = new System.IO.Ports.SerialPort(allport[allport.Length - 1].ToString(), 9600);//初始化串口对象
     try
     {
         com.Open();
         trackBar1.Visible = true;
         trackBar1.Enabled = true;
         trackBar2.Visible = true;
         trackBar2.Enabled = true;
     }
     catch (Exception a)
     {
         MessageBox.Show(a.ToString());
     }
     if (com != null)
     {
         com.WriteLine("UD" + 90);
         Thread.Sleep(200);
         com.WriteLine("LR" + 90);
         com.WriteLine("B");
     }
 }
Ejemplo n.º 31
0
        public void Open()
        {
            if (myPort != null)
            {
                throw new Exception("Already opened. Call close first.");
            }

            foreach(string s in SerialPort.GetPortNames())
            {
                try
                {
                    myPort = new SerialPort(s, 9600);
                    myPort.NewLine = "\r";
                    myPort.Open();
                    myPort.WriteTimeout = 300;
                    myPort.WriteLine("at");
                    myPort.WriteLine("at");
                    myPort.WriteLine("at");  ValidateResponse("ok", 300);
                    myPort.WriteLine("AT+CMGF=1"); ValidateResponse("ok", 300);
                    myPort.WriteLine("AT+CSCS=\"HEX\""); ValidateResponse("ok", 300);
                    myPort.WriteLine("AT+CSMP=17,167,0,8"); ValidateResponse("ok", 300);

                    return;
                }
                catch
                {
                    Close();
                }
            }

            throw new Exception("Cannot find modem.");
        }
Ejemplo n.º 32
0
        private void butCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (!clsBarCode.CheckTxt(txtBarcode.Text.Trim()))
                {
                    txtState1.Text += clsLog.writeLog("条形码格式有误!");
                    scrollToCurrentRow(txtState1);

                    MessageBox.Show("条形码格式有误!", "提示");
                    return;
                }
                txtState1.Text += clsLog.writeLog("条形码:" + txtBarcode.Text);

                if (!ComInfo(FlagCom))
                {
                    return;
                }

                string str1 = "blackTest -p" + Environment.NewLine;
                //byte[] data = Encoding.Unicode.GetBytes(str1);
                //str1 = Convert.ToBase64String(data);
                ComPort.WriteLine(str1);

                txtState2.Text += clsLog.writeLog(str1);
                scrollToCurrentRow(txtState2);

                txtResult.Text = "Testing...";
                indexItem      = 0;
                timer1.Start();

                butPause.Enabled = true;
                butCheck.Enabled = false;
            }
            catch (Exception ex)
            {
                txtState1.Text += clsLog.writeLog(ex.Message);
                scrollToCurrentRow(txtState1);
            }
        }
        public static string Find_Operator_Name(string comPorts)
        {
            string operator_name;
            SerialPort port = new SerialPort();
            try
            {
                port.PortName = comPorts;
                if (!port.IsOpen)
                {
                    port.Open();
                }
                Thread.Sleep(100);
                port.WriteLine("AT+COPS?\r");
                Thread.Sleep(500);
                String operatorString = port.ReadExisting();

                string[] sub = operatorString.Split('\"');
                if (sub[1] == "41301")
                {
                    //port.WriteLine("AT+CUSD=1,\"AA180C3652281A\",15\r");
                    //System.Threading.Thread.Sleep(5000);
                    //operator_name=port.ReadExisting();
                    operator_name = "Mobitel";
                }

                else if (sub[1] == "41302" || sub[1]=="SRI DIALOG")
                {
                    //    Console.WriteLine("dialog");
                    //    port.WriteLine("AT+CUSD=1,\"AA11AD661B291A\",15\r");
                    //    System.Threading.Thread.Sleep(5000);
                    //    port.WriteLine("AT+CMGF=1\r");
                    //    port.WriteLine("ATZ\r");
                    //    operator_name=port.ReadExisting();
                    operator_name = "Dialog";
                }
                else
                {
                    operator_name = "Unknown";
                }
            }
            catch
            {
                operator_name = "Error";
            }
            finally
            {

                port.Close();
            }

            return operator_name;
        }
Ejemplo n.º 34
0
 private void button1_Click(object sender, EventArgs e)
 {
     System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
     port.PortName     = "COM" + textBox1.Text;
     port.WriteTimeout = 500;
     port.ReadTimeout  = 500;
     port.BaudRate     = 9600;
     port.Parity       = Parity.None;
     port.DataBits     = 8;
     port.StopBits     = StopBits.One;
     port.Handshake    = Handshake.RequestToSend;
     port.DtrEnable    = true;
     port.RtsEnable    = true;
     port.NewLine      = System.Environment.NewLine;
     try
     {
         port.Open();
     }
     catch
     {
         MessageBox.Show("Не могу открыть порт");
         return;
     }
     try
     {
         System.Threading.Thread.Sleep(500);
         port.WriteLine("AT+CMGF=1");
         port.WriteLine("AT+CMGS=" + (char)(34) + textBox2.Text + (char)(34) + ",145");
         port.WriteLine(textBox3.Text + System.Environment.NewLine + (char)(26));
     }
     catch
     {
         MessageBox.Show("Нету связи с модемом");
         port.Close();
         return;
     }
     MessageBox.Show("SMS отправлено, вроде бы... :)");
     port.Close();
 }
Ejemplo n.º 35
0
 public String SendSMS(string phoneNo, string message)
 {
     System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort("COM1", 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
     try
     {
         port.Open();
         port.Write("AT\r\n");
         System.Threading.Thread.Sleep(1000);
         port.WriteLine("AT+CMGF=1\r\n");
         System.Threading.Thread.Sleep(1000);
         port.WriteLine("AT+CMGS=\"+60121212121\"\r\n");
         port.WriteLine("AT+CMGS=\"" + phoneNo + "\"\r\n");
         System.Threading.Thread.Sleep(1000);
         port.WriteLine("Testing SMS\r\n" + '\x001a');
         port.WriteLine(message + "\r\n" + '\x001a');
         return("done");
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
        public static void Main()
        {
            string name;
            string message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread readThread = new Thread(Read);

            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort();

            // Allow the user to set the appropriate properties.
            _serialPort.PortName = SetPortName(_serialPort.PortName);
            _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
            _serialPort.Parity = SetPortParity(_serialPort.Parity);
            _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
            _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
            _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            _continue = true;
            readThread.Start();

            Console.Write("Name: ");
            name = Console.ReadLine();

            Console.WriteLine("Type QUIT to exit");

            while (_continue)
            {
                message = Console.ReadLine();

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    _serialPort.WriteLine(
                        String.Format("<{0}>: {1}", name, message));
                }
            }

            readThread.Join();
            _serialPort.Close();

            Console.ReadKey();
        }
Ejemplo n.º 37
0
        public COM_Bike(String com_port) 
        {
            serial = new SerialPort
            {
                PortName = com_port,
                DataBits = 8,
                StopBits = StopBits.One,
                ReadTimeout = 2000,
                WriteTimeout = 100
            };

            serial.Open();
            serial.WriteLine("CM");
        }
Ejemplo n.º 38
0
 private void btnCashDrawer_Click(object sender, EventArgs e)
 {
     SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
     try
     {
         port.Open();
         port.WriteLine("0000000000");
         port.Close();
     }
     catch (Exception)
     {
         port.Close();
     }
 }
Ejemplo n.º 39
0
 public void OpenCash()
 {
     SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
     try
     {
         port.Open();
         port.WriteLine("0000000000");
         port.Close();
     }
     catch (Exception)
     {
         port.Close();
     }
 }
Ejemplo n.º 40
0
 private void CutPaper()
 {
     try
     {
         SerialPort sp = new SerialPort(ConfigurationManager.AppSettings["PRINTERPORT"].ToString(), 9600);
         sp.Open();
         sp.ReadTimeout = 500;
         sp.WriteLine("F");
         sp.Close();
     }
     catch
     {
     }
 }
Ejemplo n.º 41
0
        public override string Invoke(string args, int maxResultSize)
        {
            SerialPort _serialPort;

            _serialPort = new SerialPort();
            _serialPort.PortName = "COM17";
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            _serialPort.WriteLine(args);
            _serialPort.Close();
            return args;
        }
Ejemplo n.º 42
0
        ///<summary>
        ///This will send a string message straight to the COM port. (For Debug use)
        ///</summary>
        public static bool SendMessageToSerial(String Message, int COMPortNumber, int baudRate)//Change Bool for routing to SE log file.
        {
            bool success = false;
            //string textToSend = string.Format("\x02{0}\x03", Message);
            string textToSend = string.Format("<{0}>", Message);

            serialPort1.BaudRate = baudRate;
            serialPort1.PortName = "COM" + COMPortNumber;

            if (serialPort1.IsOpen)
            {
                serialPort1.WriteLine(textToSend);
                success = true;
            }
            else
            {
                serialPort1.Open();
                serialPort1.WriteLine(textToSend);
                success = true;
            }
            serialPort1.Close();
            return(success);
        }
Ejemplo n.º 43
0
        public static void Main()
        {
            string         name;
            string         message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread         readThread     = new Thread(Read);

            // Create a new SerialPort object with default settings.
            _serialPort = new System.IO.Ports.SerialPort();

            // Allow the user to set the appropriate properties.
            _serialPort.PortName  = SetPortName(_serialPort.PortName);
            _serialPort.BaudRate  = SetPortBaudRate(_serialPort.BaudRate);
            _serialPort.Parity    = SetPortParity(_serialPort.Parity);
            _serialPort.DataBits  = SetPortDataBits(_serialPort.DataBits);
            _serialPort.StopBits  = SetPortStopBits(_serialPort.StopBits);
            _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

            // Set the read/write timeouts
            _serialPort.ReadTimeout  = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            _continue = true;
            readThread.Start();

            Console.Write("Name: ");
            name = Console.ReadLine();

            Console.WriteLine("Type QUIT to exit");

            while (_continue)
            {
                message = Console.ReadLine();

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    _serialPort.WriteLine(
                        String.Format("<{0}>: {1}", name, message));
                }
            }

            readThread.Join();
            _serialPort.Close();
        }
Ejemplo n.º 44
0
		public static string ReadDescription(SerialPort port)
		{
			port.ReadTimeout = 100;
			port.NewLine = "\r\n";
			string desc = "";
			try {
				port.Open();
				port.WriteLine("R");
				Thread.Sleep(1000);
				desc = port.ReadLine();
			} catch (TimeoutException) {
			}
			port.Close();
			return desc;
		}
Ejemplo n.º 45
0
  public static void Init(string portname)
  {
      port = new SerialPort(portname, 115200, Parity.None, 8, StopBits.One);
      
      port.Open();
      port.WriteLine("ATZ");
      log("ATZ Command send");
      string response = port.ReadExisting();
      if (!response.Contains("ATZ"))
      {
          log("Response: " + response);
          throw new Exception("ATZ (reset) failed.");
      }
 
    
  }
Ejemplo n.º 46
0
        public static bool connectDisplay(SerialPort serial)
        {
            if (serial == null || !serial.IsOpen)
            {
                throw new Exception(StringResources.E00001);
            }

            string accessString = serial.ReadLine();

            if (accessString == DisplayToAppAccessString)
            {

                serial.WriteLine(AppToDisplayAccessString);
                return true;
            }
            return false;
        }
Ejemplo n.º 47
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                serialPort1.Open();
            }

            if (!serialPort2.IsOpen)
            {
                serialPort2.Open();
            }

            serialPort1.WriteLine("READ?\r\n");
            this.Invoke(new EventHandler(sportRCV1));
            serialPort2.WriteLine("READ?\r\n");
            this.Invoke(new EventHandler(sportRCV2));
        }
Ejemplo n.º 48
0
        private static void LockDoor(bool lockIt)
        {
            using (SerialPort serialPort1 = new SerialPort())
            {
                serialPort1.PortName = "COM4"; //set the port name you see in arduino IDE
                serialPort1.BaudRate = 9600;   //set the Baud you see in arduino IDE

                serialPort1.Open();

                Thread.Sleep(5);
                if (serialPort1.IsOpen)
                {
                    //Console.WriteLine(lockIt ? "l" : "u");
                    serialPort1.WriteLine(lockIt ? "u" : "l");
                    serialPort1.Close();
                }
            }
        }
Ejemplo n.º 49
0
 private void btnConnectToReLoad_Click(object sender, RoutedEventArgs e)
 {
     if (CBPortsSelection.SelectedIndex >= 0)
     {
         if (((string)btnConnectToReLoad.Content) == "Connect")
         {
             string portName = (string)CBPortsSelection.Items[CBPortsSelection.SelectedIndex];
             _serialPort = new SerialPort(portName, 115200);
             _serialPort.DataReceived += _serialPort_DataReceived;
             _serialPort.Open();
             DateTime start = DateTime.Now;
             while (lastReading == null || (DateTime.Now - lastReading).TotalSeconds > 3)
             {
                 if ((DateTime.Now - start).TotalSeconds > 3)
                 {
                     _serialPort.WriteLine("monitor 1000");//send the monitor command
                 }
                 if ((DateTime.Now - start).TotalSeconds > 10)
                 {
                     _serialPort.Close();
                     return;
                 }
                 System.Threading.Thread.Sleep(1000);
             }
             vStopUpDown.IsEnabled         = true;
             iSetUpDown.IsEnabled          = true;
             btnStartStopLogging.IsEnabled = true;
             btnpause.IsEnabled            = true;
             btnConnectToReLoad.Content    = "Disconnect";
             portOpened = true;
         }
         else
         {
             _serialPort.DataReceived -= _serialPort_DataReceived;
             lock (_serialPort)
             {
                 _serialPort.Close();
                 _serialPort = null;
             }
             portOpened = false;
             btnConnectToReLoad.Content = "Connect";
         }
     }
 }
Ejemplo n.º 50
0
        //public bool SendData(byte[] send)
        public bool SendData(string send)
        {
            bool flag = false;

            try
            {
                //Console.WriteLine(send);
                // _spPot1.Write(send, 0, send.Length);
                // flag = true;

                _spPot1.WriteLine(send);
                flag = true;
            }
            catch (Exception)
            {
                MessageBox.Show("串口未打开", "提示");
            }
            return(flag);
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Read one line off of the serial port, and hopefully populate a sensormodel
        /// </summary>
        /// <returns>SensorModel or Null if malformed</returns>
        public SensorModel SensorReadLine(SerialPort oCon)
        {
            string sInput = string.Empty;
            try
            {
                //--------------------------------------------------------
                // Format of the string that the base station sends us via serial.
                // Temprature(F)/Humidity(%)/Fire(bit)/distance(cm int)
                // T78:H40:F0:W1
                //--------------------------------------------------------
                oCon.NewLine = "\r\n";
                oCon.ReadTimeout = 1500;

                oCon.WriteLine("GimmieDaSensors!"); // Send request command
                sInput = oCon.ReadLine(); // Catch the reply

                var asSplitInput = sInput.Split(':'); // [T78][H40][F0][W1][D0]

                var oModel = new SensorModel();

                for (int i = 0; i < asSplitInput.Length; i++)
                {
                    asSplitInput[i] = asSplitInput[i].Remove(0, 1); //Removing the data piece identifyer
                }
                oModel.Temperature = int.Parse(asSplitInput[0]); //Load up the model
                oModel.Humidity = int.Parse(asSplitInput[1]);
                if (asSplitInput[2] == "1")
                {
                    oModel.FireAlarm = true;
                } // bool defaults to false
                if (asSplitInput[3] == "1")
                {
                    oModel.WaterAlarm = true;
                }

                return oModel;
            }
            catch (Exception x)
            {
                //Let the controller deal with it
                throw x;
            }
        }
Ejemplo n.º 52
0
        public void DisplayMessage(string Msg)
        {
            m_sp.Open();

            //客显初始化
            byte[] byChar = new byte[1];
            byChar[0] = Convert.ToByte(31);
            m_sp.Write(byChar, 0, 1);

            //显示位置设置
            byte[] byChar1 = new byte[2];
            byChar1[0] = Convert.ToByte(16);
            byChar1[1] = Convert.ToByte(1);
            m_sp.Write(byChar1, 2, 0);

            m_sp.WriteLine(Msg);

            m_sp.Close();
        }
Ejemplo n.º 53
0
        //=========================================================================

        //=========================================================================
        /// <summary>
        /// Opens a connection to the port specified in <see cref="SerialPortName"/>
        /// (if it is not open) and sends the <paramref name="instructionString"/> to
        /// the device.
        /// </summary>
        /// <param name="instructionString"></param>
        public void SendInstructions(string instructions, bool addNewline)
        {
            //---- if the port isn't open yet, open it.
            if (!this._serialPort.IsOpen)
            {
                this._serialPort.Open();
            }

            if (addNewline)
            {
                //---- send the string over the serial port
                // note: writeline adds a newline character to the end which tells
                // the chip when the string is terminated.
                _serialPort.WriteLine(instructions);
            }
            else
            {
                _serialPort.Write(instructions);
            }
        }
        public static String SendSerialCommand(SerialCommand cmd)
        {
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(cmd.Command));
            System.Diagnostics.Debug.Assert(cmd.SerialPort != 0);

            using (SerialPort serialPort = new SerialPort(cmd.SerialPortString, cmd.BaudRate, cmd.Parity, cmd.DataBits, cmd.StopBits))
            {
                try
                {
                    serialPort.ReadTimeout = 1000;

                    serialPort.Open();
                    if (cmd.Hex)
                    {
                        byte[] buffer = HexStringToBytes(cmd.Command);
                        serialPort.Write(buffer, 0, buffer.Length);
                    }
                    else
                        serialPort.WriteLine(cmd.Command + "\r");   // Add a carriage return because most devices want one

                    string actualResponse = String.Empty;
                    foreach (char c in cmd.ExpectedResponse)
                    {
                        char rcvdChar = (char)serialPort.ReadChar();
                        actualResponse += rcvdChar;
                        if (rcvdChar != c)
                        {
                            actualResponse += serialPort.ReadExisting();
                            return actualResponse + "!=" + cmd.ExpectedResponse;
                        }
                    }

                    //System.Threading.Thread.Sleep(cmd.SleepTime);
                    return actualResponse;
                }
                finally
                {
                    serialPort.Close();
                }
            }
        }
Ejemplo n.º 55
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (!comport.IsOpen)
            {
                MessageBox.Show("串口没有打开,请打开串口!");
                return;
            }
            string textToSend = m_syntaxRichTextBox.Text;
            int    nflag      = textToSend.IndexOf("\n");
            int    rflag      = textToSend.IndexOf("\r");
            int    iNewline   = -1;

            if (nflag >= 0 && rflag >= 0)
            {
                iNewline = Math.Min(nflag, rflag);
            }
            else
            {
                if (nflag >= 0)
                {
                    iNewline = nflag;
                }
                if (rflag >= 0)
                {
                    iNewline = rflag;
                }
            }
            if (iNewline < 0)
            {
                iNewline = textToSend.Length;
            }
            textToSend = textToSend.Substring(0, iNewline) + "\r\n";

            int n = 0;

            //16进制发送
            if (checkBoxHexSend.Checked)
            {
                //正则得到有效的十六进制数
                if (!Regex.IsMatch(textToSend, @"[\da-fA-F]{0,1024}"))
                {
                    MessageBox.Show("输入的内容并不是十六进制数字");
                    return;
                }
                MatchCollection mc = Regex.Matches(textToSend, @"(?i)[\da-f]{2}");
                //MatchCollection mc = Regex.Matches(txt_Send.Text, @"(?i)[\da-f]{2}");
                List <byte> buf = new List <byte>();//填充到这个临时列表中
                //依次添加到列表中
                foreach (Match m in mc)
                {
                    buf.Add(Byte.Parse(m.ToString(), System.Globalization.NumberStyles.HexNumber));
                }
                //  ;
                //转换列表为数组后发送
                comport.Write(buf.ToArray(), 0, buf.Count);
                //记录发送的字节数
                n = buf.Count;

                //this.txt_showinfo.Text += "\r\n发送:";
                //this.txt_showinfo.Text += textToSend;
            }
            else//ascii编码直接发送
            {
                string str0;
                str0 = textToSend;
                comport.WriteLine(str0);
                n = textToSend.Length;
                //this.txt_showinfo.Text += "\r\n发送:";
                //this.txt_showinfo.Text += str0;
            }
            send_count += n;
            //累加发送字节数
            this.lblSentCount.Text = send_count.ToString();
        }
Ejemplo n.º 56
0
        }                         // Main

        public static void Init() //can cause uncaught exception in system.dll if comports are not open
        {                         // another good reason to use device id's
            /*============================================================================================\
            | *Preconditions: Serial Ports are addressed to 255==LHand and 256==Rhand in A4 Fast CSV mode |
            | *PostConditions: Leaves hands in 500,500,500,500 position with COM PORTS in BAUD 115200     |
            \============================================================================================*/


            string s2 = "";
            string s1 = "";

            writeThread = new Thread(() => WriteToHands(s1, s2));
            writeThread.Start();


            handPortL = new SerialPort("\\\\.\\COM255", 115200);
            handPortR = new SerialPort("\\\\.\\COM256", 115200);


            if (!handPortL.IsOpen)
            {
                try
                {
                    handPortL.Open();
                    handPortL.DtrEnable = true;
                    handPortL.BaudRate  = 115200;
                    handPortL.WriteLine("H2");
                    ClearBuffers("LeftHand");
                    var i = 1;
                    UnityEngine.Debug.Log("End of handPortL init(), which executed a total of " + i + " times.");
                    i++;
                }
                catch (Exception e)
                {
                    UnityEngine.Debug.Log("Could not open comport for hands." + e);
                }
            }

            if (!handPortR.IsOpen)
            {
                try
                {
                    handPortR.Open();
                    handPortR.DtrEnable = true;
                    handPortR.BaudRate  = 115200;
                    handPortR.WriteLine("H1");
                    ClearBuffers("RightHand");
                    var i = 1;
                    UnityEngine.Debug.Log("End of handPortR init(), which executed a total of" + i + " times.");
                    i++;
                }
                catch (Exception e)
                {
                    UnityEngine.Debug.Log("Could not open comport for hands" + e);
                }
            }
            try
            {
                UnityEngine.Debug.Log("Init()'s WriteLine() Try Block Begin");
                handPortL.Write("500,500,500,500\n");
                handPortR.Write("500,500,500,500\n");
                ClearBuffers("BothHands");
                var i = 1;
                UnityEngine.Debug.Log("Wrote to L and R in Init() " + i + " Times");
                i++;
            }
            catch (Exception e)
            {
                UnityEngine.Debug.Log("Caught error in Init()'s WriteLine Try Block" + e);
            }
        }                                                                // Init
Ejemplo n.º 57
0
        //发送按钮
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (cbTimeSend.Checked)
            {
                tmSend.Enabled = true;
            }
            else
            {
                tmSend.Enabled = false;
            }

            if (!sp1.IsOpen) //如果没打开
            {
                MessageBox.Show("请先打开串口!", "Error");
                return;
            }

            String strSend = txtSend.Text;

            if (radio1.Checked == true) //“HEX发送” 按钮
            {
                //处理数字转换
                string sendBuf         = strSend;
                string sendnoNull      = sendBuf.Trim();
                string sendNOComma     = sendnoNull.Replace(',', ' ');   //去掉英文逗号
                string sendNOComma1    = sendNOComma.Replace(',', ' ');  //去掉中文逗号
                string strSendNoComma2 = sendNOComma1.Replace("0x", ""); //去掉0x
                strSendNoComma2.Replace("0X", "");                       //去掉0X
                string[] strArray = strSendNoComma2.Split(' ');

                int byteBufferLength = strArray.Length;
                for (int i = 0; i < strArray.Length; i++)
                {
                    if (strArray[i] == "")
                    {
                        byteBufferLength--;
                    }
                }
                // int temp = 0;
                byte[] byteBuffer = new byte[byteBufferLength];
                int    ii         = 0;
                for (int i = 0; i < strArray.Length; i++)        //对获取的字符做相加运算
                {
                    Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray[i]);

                    int decNum = 0;
                    if (strArray[i] == "")
                    {
                        //ii--;     //加上此句是错误的,下面的continue以延缓了一个ii,不与i同步
                        continue;
                    }
                    else
                    {
                        decNum = Convert.ToInt32(strArray[i], 16); //atrArray[i] == 12时,temp == 18
                    }

                    try    //防止输错,使其只能输入一个字节的字符
                    {
                        byteBuffer[ii] = Convert.ToByte(decNum);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("字节越界,请逐个字节输入!", "Error");
                        tmSend.Enabled = false;
                        return;
                    }

                    ii++;
                }
                sp1.Write(byteBuffer, 0, byteBuffer.Length);
            }
            else                             //以字符串形式发送时
            {
                sp1.WriteLine(txtSend.Text); //写入数据
            }
        }
Ejemplo n.º 58
0
 public void WriteLine(string line)
 {
     ComPort.WriteLine(line);
 }
Ejemplo n.º 59
0
        /// <summary>
        /// ZPL 코드를 라벨발행기로 출력
        /// </summary>
        /// <param name="strPort">발행포트</param>
        /// <param name="strZPL">ZPL내용</param>
        /// <returns></returns>
        public static void PrintZPL(string strPort, string strZPL)
        {
            switch (strPort.Substring(0, 3))
            {
            case "USB":
                RawPrinterHelper.SendStringToPrinter(strPort, strZPL);
                break;

            case "COM":
                SerialPort SP = new System.IO.Ports.SerialPort(strPort, 9600, Parity.None, 8, StopBits.One);
                try
                {
                    SP.Open();
                }
                catch (Exception ex)
                {
                    return;
                }
                StringBuilder DataString = new StringBuilder();
                try
                {
                    if (!SP.IsOpen)
                    {
                        SP.Open();
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
                DataString.Append(strZPL);
                try
                {
                    SP.WriteLine(DataString.ToString());
                }
                catch (Exception ex)
                {
                    return;
                }
                break;

            case "LPT":
                TextWriter sw = new StreamWriter(@"C:\ZPL.TXT");
                sw.WriteLine(strZPL);
                sw.Close();

                System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName         = "CMD.exe";
                startInfo.WorkingDirectory = @"D:\";

                startInfo.UseShellExecute        = false;
                startInfo.RedirectStandardInput  = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError  = true;
                startInfo.CreateNoWindow         = true;
                startInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;

                process.EnableRaisingEvents = false;
                process.StartInfo           = startInfo;
                process.Start();
                process.StandardInput.Write(@"COPY C:\ZPL.TXT " + strPort + Environment.NewLine);
                process.StandardInput.Close();

                process.WaitForExit();
                process.Close();
                break;

            case "SCR":
                MsgBox.Show(strZPL, "ZPL 출력 내용", MessageBoxButtons.OK);
                break;

            default:
                RawPrinterHelper.SendStringToPrinter(strPort, strZPL);
                break;
            }
        }
Ejemplo n.º 60
0
        public static void Main()
        {
            var  commands = new Commands();
            Ping ping     = new Ping();

            Console.WriteLine("*** Copyright (c) Gavin Isgar 2018\n\n*** Please type in a command:");
            var com = Console.ReadLine();

            if (commands.commands.Contains(com))
            {
                if (com == "localnettest")
                {
                    Console.WriteLine("\n*** Please input an I.P or web address:");
                    var ip = Console.ReadLine();
                    try {
                        PingReply reply = ping.Send(ip);
                        if (reply.Status.ToString() == "Success")
                        {
                            Console.WriteLine("\n*** " + ip + " connectivity is normal.");
                            resetMainScreen();
                        }
                        else
                        {
                            Console.WriteLine("\n**PROBLEM** Connectivity is abnormal; received " + reply.Status.ToString());
                            resetMainScreen();
                        }
                    }
                    catch (Exception) {
                        Console.WriteLine("\n**ERROR** An exception was caught during the process. Stopping request.");
                        resetMainScreen();
                    }
                }

                if (com == "localhardstats")
                {
                    Console.Clear();
                    try {
                        // HARDWARE
                        using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_BASEBOARD")) {
                            var BASEBOARD = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                            var num       = 0;
                            foreach (var type in BASEBOARD)
                            {
                                Console.WriteLine("\n----------Motherboard {0}----------", num++);
                                Console.WriteLine("\n*** Manufacturer: {0}", type.GetPropertyValue("Manufacturer").ToString());
                                Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                                Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                                Console.WriteLine("\n*** Serial Number: {0}", type.GetPropertyValue("SerialNumber").ToString());
                                Console.WriteLine("\n*** Product: {0}", type.GetPropertyValue("Product").ToString());
                            }
                        }
                        using (var searcher = new ManagementObjectSearcher("SELECT * FROM CIM_CHIP")) {
                            var CHIP = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                            var num  = 0;
                            foreach (var type in CHIP)
                            {
                                Console.WriteLine("\n----------Chip {0}----------", num++);
                                Console.WriteLine("\n*** Manufacturer: {0}", type.GetPropertyValue("Manufacturer").ToString());
                                Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                                Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                                Console.WriteLine("\n*** Serial Number: {0}", type.GetPropertyValue("SerialNumber").ToString());
                            }
                        }
                        using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_FAN")) {
                            var FAN = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                            var num = 0;
                            foreach (var type in FAN)
                            {
                                Console.WriteLine("\n----------Fan {0}----------", num++);
                                Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                                Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                                Console.WriteLine("\n*** System Name: {0}", type.GetPropertyValue("SystemName").ToString());
                                Console.WriteLine("\n*** Device ID: {0}", type.GetPropertyValue("DeviceID").ToString());
                                Console.WriteLine("\n*** Availability: {0}", ComponentStatuses.Availability.ElementAt(Convert.ToInt32(type.GetPropertyValue("Availability"))));
                                Console.WriteLine("\n*** Config Code: {0}", ComponentStatuses.ConfigManagerErrorCode.ElementAt(Convert.ToInt32(type.GetPropertyValue("ConfigManagerErrorCode"))));
                            }
                        }
                        using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_KEYBOARD")) {
                            var KEYBOARD = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                            var num      = 0;
                            foreach (var type in KEYBOARD)
                            {
                                Console.WriteLine("\n----------Keyboard {0}----------", num++);
                                Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                                Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                                Console.WriteLine("\n*** Layout: {0}", type.GetPropertyValue("Layout").ToString());
                                Console.WriteLine("\n*** System Name: {0}", type.GetPropertyValue("SystemName").ToString());
                                Console.WriteLine("\n*** Device ID: {0}", type.GetPropertyValue("DeviceID").ToString());
                                Console.WriteLine("\n*** PnP Device ID: {0}", type.GetPropertyValue("PNPDeviceID").ToString());
                                Console.WriteLine("\n*** Availability: {0}", ComponentStatuses.Availability.ElementAt(Convert.ToInt32(type.GetPropertyValue("Availability"))));
                                Console.WriteLine("\n*** Config Code: {0}", ComponentStatuses.ConfigManagerErrorCode.ElementAt(Convert.ToInt32(type.GetPropertyValue("ConfigManagerErrorCode"))));
                            }
                        }
                        using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_POINTINGDEVICE")) {
                            var POINTINGDEVICE = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                            var num            = 0;
                            foreach (var type in POINTINGDEVICE)
                            {
                                Console.WriteLine("\n----------Mouse {0}----------", num++);
                                Console.WriteLine("\n*** Manufacturer: {0}", type.GetPropertyValue("Manufacturer").ToString());
                                Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                                Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                                Console.WriteLine("\n*** System Name: {0}", type.GetPropertyValue("SystemName").ToString());
                                Console.WriteLine("\n*** Device ID: {0}", type.GetPropertyValue("DeviceID").ToString());
                                Console.WriteLine("\n*** PnP Device ID: {0}", type.GetPropertyValue("PNPDeviceID").ToString());
                                Console.WriteLine("\n*** Availability: {0}", ComponentStatuses.Availability.ElementAt(Convert.ToInt32(type.GetPropertyValue("Availability"))));
                                Console.WriteLine("\n*** Config Code: {0}", ComponentStatuses.ConfigManagerErrorCode.ElementAt(Convert.ToInt32(type.GetPropertyValue("ConfigManagerErrorCode"))));
                            }
                        }
                        using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_DESKTOPMONITOR")) {
                            var DESKTOPMONITOR = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                            var num            = 0;
                            foreach (var type in DESKTOPMONITOR)
                            {
                                Console.WriteLine("\n----------Monitor {0}----------", num++);
                                Console.WriteLine("\n*** Manufacturer: {0}", type.GetPropertyValue("MonitorManufacturer").ToString());
                                Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                                Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                                Console.WriteLine("\n*** Type: {0}", type.GetPropertyValue("MonitorType").ToString());
                                Console.WriteLine("\n*** System Name: {0}", type.GetPropertyValue("SystemName").ToString());
                                Console.WriteLine("\n*** Device ID: {0}", type.GetPropertyValue("DeviceID").ToString());
                                Console.WriteLine("\n*** PnP Device ID: {0}", type.GetPropertyValue("PNPDeviceID").ToString());
                                Console.WriteLine("\n*** Availability: {0}", ComponentStatuses.Availability.ElementAt(Convert.ToInt32(type.GetPropertyValue("Availability"))));
                            }
                        }
                        Console.WriteLine("\n----------------------------------------");
                        resetMainScreen();
                    }
                    catch (Exception) {
                        Console.WriteLine("\n**ERROR** An exception was caught during the process. Stopping request.");
                        resetMainScreen();
                    }
                }

                if (com == "localsoftstats")
                {
                    Console.Clear();
                    using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_BIOS")) {
                        var BIOS = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                        var num  = 0;
                        foreach (var type in BIOS)
                        {
                            Console.WriteLine("\n----------BIOS {0}----------", num++);
                            Console.WriteLine("\n*** Manufacturer: {0}", type.GetPropertyValue("Manufacturer").ToString());
                            Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                            Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                            Console.WriteLine("\n*** Version: {0}", type.GetPropertyValue("Version").ToString());
                            Console.WriteLine("\n*** Serial Number: {0}", type.GetPropertyValue("SerialNumber").ToString());
                        }
                    }
                    using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_OPERATINGSYSTEM")) {
                        var OPERATINGSYSTEM = searcher.Get().Cast <ManagementBaseObject>().ToArray();
                        var num             = 0;
                        foreach (var type in OPERATINGSYSTEM)
                        {
                            Console.WriteLine("\n----------OPERATING SYSTEM {0}----------", num++);
                            Console.WriteLine("\n*** Manufacturer: {0}", type.GetPropertyValue("Manufacturer").ToString());
                            Console.WriteLine("\n*** Name: {0}", type.GetPropertyValue("Name").ToString());
                            Console.WriteLine("\n*** Description: {0}", type.GetPropertyValue("Description").ToString());
                            Console.WriteLine("\n*** Version: {0}", type.GetPropertyValue("Version").ToString());
                            Console.WriteLine("\n*** Build Number: {0}", type.GetPropertyValue("BuildNumber").ToString());
                            Console.WriteLine("\n*** Serial Number: {0}", type.GetPropertyValue("SerialNumber").ToString());
                            Console.WriteLine("\n*** Build Type: {0}", type.GetPropertyValue("BuildType").ToString());
                            Console.WriteLine("\n*** System Drive: {0}", type.GetPropertyValue("SystemDrive").ToString());
                            Console.WriteLine("\n*** OS Architecture: {0}", type.GetPropertyValue("OSArchitecture").ToString());
                            Console.WriteLine("\n*** OS Type: {0}", type.GetPropertyValue("OSType").ToString());
                            Console.WriteLine("\n*** Organization: {0}", type.GetPropertyValue("Organization").ToString());
                        }
                    }
                }

                if (com == "comactivecheck")
                {
                    var ports = SerialPort.GetPortNames();
                    foreach (string port in ports)
                    {
                        Console.WriteLine("\n*** Visible Port: {0}", port);
                        resetMainScreen();
                    }
                }

                if (com == "comtest")
                {
                    if (comPort == "")
                    {
                        Console.WriteLine("\n**PROBLEM** No communication port has been set.");
                        resetMainScreen();
                    }
                    else
                    {
                        try {
                            using (var sp = new System.IO.Ports.SerialPort(comPort, 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One)) {
                                // Raspberry Pi Program must contain code to connect to COM as well
                                sp.Open();
                                sp.WriteLine("\n*** Communication test from Administrative diagnostic computer.");
                                Console.WriteLine("\n**MESSAGE** From Client: {0}", sp.ReadLine());
                                sp.Close();
                                resetMainScreen();
                            }
                        }
                        catch (Exception) {
                            Console.WriteLine("\n**ERROR** An exception was caught during the process. Stopping request.");
                            resetMainScreen();
                        }
                    }
                }

                if (com == "comset")
                {
                    Console.WriteLine("\n*** Type in the name of the port needed for communication:");
                    var portname = Console.ReadLine();
                    try {
                        comPort = portname;
                        Console.WriteLine("\n*** The communication port has been set to '{0}'.", comPort);
                        resetMainScreen();
                    }
                    catch (Exception) {
                        Console.WriteLine("\n**ERROR** An exception was caught during the process. Stopping request.");
                        resetMainScreen();
                    }
                }
            }
            else
            {
                Console.WriteLine("\n**ERROR** '{0}' is not a valid command.", com);
                resetMainScreen();
            }
        }