ReadExisting() public méthode

public ReadExisting ( ) : string
Résultat string
 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();
     }
 }
Exemple #2
0
 public byte[] ReceiveCountedBinary(int Count)
 {
     try
     {
         if (sp != null && sp.IsOpen)
         {
             lock (SyncLock)
             {
                 int    count    = 0;
                 string recieved = "";
                 while (recieved.Length < Count)
                 {
                     recieved += sp.ReadExisting();
                     Thread.Sleep(1);
                     count++;
                     if (count == sp.ReadTimeout)
                     {
                         throw new TimeoutException();
                     }
                 }
                 return(encoding.GetBytes(recieved));
             }
         }
         return(null);
     }
     catch (Exception Ex)
     {
         Common.Log.LogMessage(Common.DriverId, "ReceiveCountedBinary() failed " + Ex.Message);
         throw;
     }
 }
Exemple #3
0
        private void TrySerial()
        {
            /* to understand if the keyboard is serial or ps/2 */
            if (serialPort.BytesToRead > 0)
            {
                serialPort.ReadExisting();
            }

            if (PosConfiguration.IntegrationMode != IntegrationMode.S60D_KEYBOARD)
            {
                //below bytes creates bytes to read if keyboard is serial
                HY_Write(new byte[] { 0xBA, 0x03, 0x98, 0x02, 0x00 }, 0, 5);

                //clear keyboard immediately, because if keyboar is not serial, unwanted characters occurs on the display
                serialPort.Write(initializeDisplay, 0, 3);
                System.Threading.Thread.Sleep(150);
                //if (serialPort.BytesToRead == 0)
                //    throw new NotSerialException();
            }
            else
            {
                Write(initLCD, 0, initLCD.Length);
            }

            /* if serial read bytes to read */
            serialPort.ReadExisting();
        }
        //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;
        }
Exemple #5
0
 private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     if (AlwaysUpdateChb)
     {
         ScreenReceiveText = serialPort.ReadExisting();
     }
     else if (AddToOldDataChb)
     {
         ScreenReceiveText += serialPort.ReadExisting();
     }
 }
        private void Nullbtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.elecsport = Properties.Settings.Default.elecserobj;

                elecsport.Write(elecstartcmd + "\r\n");
                elecsport.ReadExisting();
                Thread.Sleep(20000);
                elecsport.Write(elecnullcmd + "\r\n");
                elecsport.ReadExisting();
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
        }
        private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DateTime dt  = DateTime.Now;
            String   dtn = dt.ToShortTimeString();

            String     temzp    = sport.ReadExisting();
            dataSetter selector = DataAssigner();

            if (selector == dataSetter.xDegree)
            {
                ActualX = Convert.ToDouble(sport.ReadExisting());
                txtReceive.AppendText("[" + dtn + "] " + "X_Degree: " + ActualX.ToString() + "\n");
            }
            if (selector == dataSetter.yDegree)
            {
                ActualY = Convert.ToDouble(sport.ReadExisting());
                txtReceive.AppendText("[" + dtn + "] " + "Y_Degree: " + ActualX.ToString() + "\n");
            }
            if (cntr == 2)
            {
                DegreeValue temp = new DegreeValue(ActualX, ActualY, dt);
                portDoc.DegreeValues.Add(temp);
            }
            if (selector == dataSetter.other || selector == dataSetter.error)
            {
                txtReceive.AppendText("[" + dtn + "] " + "Received: " + sport.ReadExisting() + "\n");
            }
        }
        static void Main(string[] args)
        {
            sp = new SerialPort();
            sp.PortName = "COM14";
            Console.WriteLine("Com port: " + sp.PortName.ToString());
            sp.BaudRate = 200000000;
            Console.WriteLine("Baud rate: " +sp.BaudRate.ToString());
            Console.WriteLine("dataBits: " + sp.DataBits.ToString());
            Console.WriteLine("Stop bit: " + sp.StopBits.ToString());
            Console.WriteLine("Parity bit: " + sp.Parity.ToString());
            Console.WriteLine("Read Timeout: " + sp.ReadTimeout.ToString());
            sp.Handshake = Handshake.RequestToSend;
            sp.DtrEnable = true;    // Data-terminal-ready
            sp.RtsEnable = true;    // Request-to-send
            Console.WriteLine("Press enter to exit");
            Console.WriteLine("\rPackets Recd: ");
            Console.WriteLine("\rTime: " );
            Console.WriteLine("\rMoving Avg: " );
            Console.WriteLine("\rTotal Avg:" );
            sp.ErrorReceived += Sp_ErrorReceived;
            sp.Open();
            sp.DataReceived += sp_DataReceived;

            packetcount = 0;
            DT = DateTime.Now;
            string test = sp.ReadExisting(); // give it a kickstart
            Timer t = new Timer();
            t.Interval = 1000;
            t.Elapsed += T_Elapsed;
            t.Start();
            Console.ReadLine();

               sp.Close();
        }
        public void elecserialport_connect(String port, int baudrate, Parity parity, int databits, StopBits stopbits, Handshake flowcontrol)
        {
            DateTime dt  = DateTime.Now;
            String   dtn = dt.ToShortTimeString();


            try
            {
                elecsport = new System.IO.Ports.SerialPort(
                    port, baudrate, parity, databits, stopbits);
                elecsport.Handshake    = flowcontrol;
                elecsport.ReadTimeout  = 2000;
                elecsport.WriteTimeout = 2000;
                elecsport.Open();
                elecClose.IsEnabled   = true;
                elecConnect.IsEnabled = false;
                var serialnum = "";

                try
                {
                    elecsport.Write("SER" + "\r\n");
                    Thread.Sleep(55);
                    serialnum = Convert.ToString(elecsport.ReadExisting());
                } catch { }

                electxtReceive.AppendText("[" + dtn + "] " + "Connected\n");
                electxtReceive.AppendText("[" + dtn + "] " + "Serial Number: " + serialnum + "\n");
                //elecsport.DataReceived += new SerialDataReceivedEventHandler(elecsport_DataReceived);
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
        }
Exemple #10
0
        public string ReadResponse(SerialPort port, int timeout)
        {
            string buffer = string.Empty;
            do
            {
                if (receiveNow.WaitOne(timeout, false))
                {
                    string t = port.ReadExisting();
                    buffer += t;
                }
                else
                {

                    port.DiscardOutBuffer();
                    port.DiscardInBuffer();
                    receiveNow.Reset();
                    if (buffer.Length > 0)
                        throw new ApplicationException("Response received is incomplete - " + buffer);
                    else
                        throw new ApplicationException("No data received from phone.");
                }
            }
            while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
            return buffer;
        }
Exemple #11
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.WriteLine(toWrite);
             Thread.Sleep(300);
             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.WRIST_IDENTITY_RESPONSE))
             {
                 _ArduinoMap.Add(Arduino_Codes.WRIST_IDENTITY, new Arduino(temp, Arduino_Codes.WRIST_IDENTITY));
                 return true;
             }
             temp.Dispose(); //Gets rid of safe handle issue! Or at least appears to!
         }
         catch {
             return false;
         }
     }
     return false;
 }
Exemple #12
0
        /// <summary>
        /// 串口接收数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void f_dataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(300);
            receiveContent = m_port.ReadExisting().Replace("\r\n", "");


            foreach (WebSocketSession session in currentSessionPool.Values)
            {
                if (session != null && session.Connected)
                {
                    //推送回发送了获取重量指令的client,也就是订阅了获取重量
                    //消息的client
                    Dictionary <String, Object> pushData = new Dictionary <string, object>();
                    pushData.Add("key", "com_weighting");
                    //主要用于称重,兼容旧的业务以及新的扩展
                    //多客户端推送

                    pushData.Add("Key", "comSendCommand");

                    pushData.Add("weighting", receiveContent);
                    pushData.Add("value", receiveContent);

                    String jsonStr = JsonConvert.SerializeObject(pushData);
                    session.Send(jsonStr);
                }
            }
        }
Exemple #13
0
        private string readData()
        {
            string msg = "";

            try
            {
                //read data waiting in the buffer
                msg = _comPort.ReadExisting();
            }
            catch (System.TimeoutException exc)
            {
                // ignore timeout, finish read-out
            }

            if (msg != "")
            {
                //raise the event, and pass data to next layer
                if (onDataReceived != null)
                {
                    onDataReceived(this,
                                   new SerialPortEventArgs(msg));
                }
                LogHelper.Log(LogLevel.Debug, "(readData) Message received:" + msg.Trim().Replace('\r', '-'));
            }

            return(msg);
        }
        private void test( )
        {
            DateTime dt  = DateTime.Now;
            String   dtn = dt.ToShortTimeString();

            txtReceive.AppendText("[" + dtn + "] " + "Received: " + sport.ReadExisting() + "\n");
        }
Exemple #15
0
        static void Main(string[] args)
        {
            int i = 0;
            SerialPort SP = null;
            Console.WriteLine("Specify which comport you want to connect to:");
            
            foreach (string s in SerialPort.GetPortNames())
            {
                Console.WriteLine($"{i++,2} {s}");
            }
            int PortNo = int.Parse(Console.ReadLine());
            try
            {
                SP = new SerialPort(SerialPort.GetPortNames()[PortNo]);
                SP.Open();
                while(true)
                {
                    Console.Write(SP.ReadExisting());
                }
            }
            finally
            {
                if (SP.IsOpen)
                {
                    SP.Close();
                }
            }

            Console.Read();
        }
Exemple #16
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);
        }
 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);
     }
 }
        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string s = port.ReadExisting();

            byte[] bytes = Encoding.ASCII.GetBytes(s);
            bufferedBytes.Enqueue(bytes);
        }
Exemple #19
0
        private void MonitedPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string        data    = MonitedPort.ReadExisting();
                StringBuilder builder = new StringBuilder();
                for (int n = 0; n < data.Length; n++)
                {
                    builder.Append($"{((byte)data[n]).ToString("X2")} ");
                }

                Dispatcher.Invoke(() =>
                {
                    ascii_show_run.Text += data;
                    ascii_show_box.ScrollToEnd();
                    hex_show_run.Text += builder.ToString();
                    hex_show_box.ScrollToEnd();
                    UpdateSerialPortAssistantCount();
                });
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
        }
Exemple #20
0
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;
            string indata = sp.ReadExisting();

            Console.WriteLine($"Serial Port Data Received: {indata}");
        }
Exemple #21
0
        private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DateTime dt  = DateTime.Now;
            String   dtn = dt.ToShortTimeString();

            txtReceive.AppendText("[" + dtn + "]" + "Received: " + sport.ReadExisting() + "\n");
        }
Exemple #22
0
 public static string getComPort()
 {
     try {
         string[] str = SerialPort.GetPortNames();
         string recieved = "";
         string com = "";
         serialPort = new SerialPort();
         foreach (string value in str) {
             Console.WriteLine(value);
             serialPort.PortName = value;
             serialPort.BaudRate = 9600;
             serialPort.Parity = 0;
             serialPort.DataBits = 8;
             serialPort.ReadTimeout = 5000;
             serialPort.WriteTimeout = 500;
             serialPort.Open();
             serialPort.Write(comTest, 0, comTest.Length);
             Thread.Sleep(100);
             recieved = serialPort.ReadExisting();
             if (recieved.Equals("\u001by")) {
                 Console.WriteLine(value);
                 com = value;
             }
             serialPort.Close();
         }
         return com;
     } catch(Exception e) {
         Console.WriteLine(e);
         return "";
     }
 }
Exemple #23
0
        ////uncomment for default
        private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //textBox1.Text = sport.ReadExisting();
            string rfid_data = sport.ReadExisting();

            char[] asciiBytes = rfid_data.ToCharArray();
            string rfid_no    = "";


            //textBox1.Text = "";// comment this


            foreach (char ch in asciiBytes)
            {
                int    i        = (int)ch;
                string myString = i.ToString();
                rfid_no = rfid_no + i;
            }
            textBox1.Text = rfid_no;

            //sport.Close();// comment
            //label13.Text = "Disconnected"; //comment
            //if (!sport.IsOpen) // comment this
            //{
            //    button7.Enabled = false;
            //    button6.Enabled = true;
            //}
        }
        //データ受信
        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            // 繋がっていない場合は処理しない。
            if (serialPort == null)
            {
                return;
            }
            if (serialPort.IsOpen == false)
            {
                return;
            }

            try
            {
                //! 受信データを読み込む.
                string data = serialPort.ReadExisting();

                //! 受信したデータをテキストボックスに書き込む.
                Dispatcher.Invoke(new Delegate_RcvDataToTextBox(RcvDataToTextBox), new Object[] { data });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #25
0
        private static void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DateTime dt  = DateTime.Now;
            String   dtn = dt.ToShortTimeString();

            Console.WriteLine($"[{DateTime.Now.ToShortTimeString()}] Received: {sport.ReadExisting()}");
        }
        public SerialController(SerialPort port)
        {
            _port = port;
            _port.Open();

            _port.DataReceived += (sender, args) => Console.Write("{0}", _port.ReadExisting());
        }
Exemple #27
0
        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;

                byte[] buffer = new byte[8];
                if (sp.BytesToRead == 8)
                {
                    sp.Read(buffer, 0, 8);
                    _BufferSB.Clear();
                }
                else
                {
                    _BufferSB.Append(sp.ReadExisting());
                    if (_BufferSB.Length == 8)
                    {
                        Utilite.StrToMas(_BufferSB.ToString(), buffer);
                        _BufferSB.Clear();
                    }
                    else if (_BufferSB.Length > 8)
                    {
                        int pieces    = (_BufferSB.Length / 8);
                        int piecesSum = pieces * 8;
                        if (piecesSum == _BufferSB.Length)
                        {
                            Utilite.StrToMas(_BufferSB.ToString().Substring(_BufferSB.Length - 8, 8), buffer);
                            _BufferSB.Clear();
                        }
                        else
                        {
                            int    ix    = _BufferSB.Length - piecesSum;
                            string piece = _BufferSB.ToString().Substring(_BufferSB.Length - ix, ix);
                            _BufferSB.Clear();
                            _BufferSB.Append(piece);
                        }
                    }
                }
                // Валидация
                if ((buffer[6] != 0) || (buffer[7] != 0))
                {
                    int CR = 0;
                    for (int i = 0; i < 6; i++)
                    {
                        CR += buffer[i];
                    }
                    string strCR = BitConverter.ToString(buffer, 6, 2).Replace("-", "");
                    if (CR == Utilite.HexToBase(strCR))
                    {
                        buffer.CopyTo(_Response, 0);
                    }
                }
            }
            catch (Exception ex)
            {
                _ExceptionMessage = ex.Message;
                _BufferSB.Clear();
            }
        }
Exemple #28
0
 private void TrySerial()
 {
     /* to understand if the keyboard is serial or ps/2 */
     if (serialPort.BytesToRead > 0)
     {
         serialPort.ReadExisting();
     }
 }
        public string ExecuteCommand(byte[] bytes)
        {
            string response = "notresponse";

            _serialPortRS232.Write(bytes, 0, bytes.Length);
            Thread.Sleep(5000);
            response = _serialPortRS232.ReadExisting();
            return(response);
        }
Exemple #30
0
        public Hexy()
        {
            LoadOffsets();

            string hexyPort = "";

            // Find the serial port
            var ports = SerialPort.GetPortNames();
            foreach (var portName in ports)
            {
                using (var serial = new SerialPort(portName, 9600))
                {
                    serial.WriteTimeout = 1000;
                    serial.ReadTimeout = 1000;
                    serial.DtrEnable = true;

                    string check = "";

                    serial.DataReceived += (s, e) =>
                    {
                        check = serial.ReadExisting();
                    };

                    try
                    {
                        serial.Open();

                        serial.Write("V");

                        Thread.Sleep(100);

                        if (check.StartsWith("SERVOTOR"))
                        {
                            hexyPort = portName;
                            break;
                        }
                    }
                    catch (TimeoutException)
                    { }
                    catch (IOException)
                    { }
                    finally
                    {
                        if (serial.IsOpen)
                            serial.Close();
                    }
                }
            }

            if (string.IsNullOrEmpty(hexyPort))
                throw new Exception("Hexy port not found");

            port = new SerialPort(hexyPort, 9600);
            port.DtrEnable = true;
            port.Open();
        }
        private void pmdsport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DateTime dt  = DateTime.Now;
            String   dtn = dt.ToShortTimeString();

            this.Dispatcher.Invoke(() =>
            {
                pmdtxtReceive.AppendText("[" + dtn + "] " + "Received: " + pmdsport.ReadExisting() + "\n");
            });
        }
Exemple #32
0
 private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         Data_uart = sport.ReadExisting();
     }
     catch (Exception)
     {
         MessageBox.Show("Error in data received");
     }
 }
 protected override void FlushInputConnection()
 {
     try
     {
         SerialPort.ReadExisting();
         SerialPort.DiscardInBuffer();
     }
     catch
     {
     }
 }
        public Boolean openSerial(String port, String arduinoVer)
        {
            if (SP != null && SP.IsOpen)
                SP.Close();
            if (port == "")
                return false;

            console("Opening Serial Port on: " + port);
            SP = new SerialPort(port, 9600, Parity.None, 8);
            SP.Open();
            open = true;

            //handshake
            SP.ReadTimeout = 5000;
            SP.Write("1");

            String s = "";
            int t = 0;
            while (s.Length < 4 && t < 500)
            {
                System.Threading.Thread.Sleep(10);
                s = SP.ReadExisting();

                if (!s.Contains("."))
                    s = "";
                else
                    s = s.Split('.')[1];

                SP.Write("1");
                t += 1;
            }
            String av = arduinoVer.Replace(@".", string.Empty);
            if (av.Length < 4)
            {
                av = av[0] + "" + av[1] + "0" + av[2];
            }

            if (s == "")
                console("No Responce from Arduino, going ahead with connection but errors may occour");
            else
            {
                s = s.Substring(s.Length - 4, 4);
                if (Convert.ToInt16(s) < Convert.ToInt16(av))
                {
                    console("Arduino Code Outdated(v" + s[0] + "." + s[1] + "." + s[2] + s[3] + "). Please Update Arduino to at least v" + arduinoVer + " and then Retry");
                    return false;
                }

                console("Handshake Sucsessful, Connected to Arduino Running: v" + s[0] + "." + s[1] + "." + s[2] + s[3]);
                iRacingSLI.currArduinoVersion = s[0] + "." + s[1] + "." + s[2] + s[3];
            }
            return true;
        }
        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;
        }
Exemple #36
0
        private int timeout(double speed, double gotopos)
        {
            this.pmdsport.Write(pmdpositioncmd + "\r\n");
            Thread.Sleep((int)min232updtime);
            var pos = Convert.ToDouble(Regex.Split(pmdsport.ReadExisting(), "E")[1]);

            var deltapos = Math.Abs(pos - gotopos);

            int calctimeout = (int)Math.Round(deltapos / speed) + 20;


            return(calctimeout);
        }
Exemple #37
0
 private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e) //gdy event zglosi ze cos przyszlo to przechodzi do tej metody
 {
     try
     {
         InputData = sport.ReadExisting();
         IAsyncResult result = this.BeginInvoke(new SetTextDelegate(SetText), new object[] { InputData }); //wywolanie asynchroniczne (DELEGAT, ARGUMENT)
         this.EndInvoke(result);
     }
     catch (Exception)
     {
         MessageBox.Show("error");
     }
 }
Exemple #38
0
        private void sportRCV4(object sender, EventArgs e)
        {
            if (serialPort4.BytesToRead > 0)
            {
                txtRS4.Text = serialPort4.ReadExisting();

                AppendText(richTextBox1, "SerialPort1 Data :: " + txtRS4.Text);
                richTextBox1.Invoke((MethodInvoker) delegate()
                {
                    richTextBox1.SelectionStart = richTextBox1.Text.Length;
                    richTextBox1.ScrollToCaret();
                });
            }
        }
        //Int32 mBytesRead=0;
        //Byte[] mReadBuffer = new Byte[10];
        void dataReceived(System.Object sender, System.IO.Ports.SerialDataReceivedEventArgs e) //received data
        {
            System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;
            string indata = sp.ReadExisting();

            //if (sp.BytesToRead <= 0)
            //{
            //    ConsoleU.writeLine("empty trigger", ConsoleU.Level.Warning);
            //    return;
            //}
            //mBytesRead += sp.Read(mReadBuffer, mBytesRead, sp.BytesToRead);
            //ConsoleU.writeLine(string.Format("Data Received: {0}", System.Text.Encoding.Default.GetString (mReadBuffer)), ConsoleU.Level.Info);
            ConsoleU.writeLine(string.Format("Data Received: {0}", indata), ConsoleU.Level.Info);
        }
Exemple #40
0
        private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string data = "";

            //System.Threading.Thread.Sleep(250);
            while (sport.BytesToRead > 0)
            {
                data                      = sport.ReadExisting();
                data                      = data.Replace("\0", string.Empty);
                txtReceive.Text          += data;
                txtReceive.SelectionStart = txtReceive.Text.Length;
                txtReceive.ScrollToCaret();
            }
        }
 private void elecDataSendbtn_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         DateTime dt  = DateTime.Now;
         String   dtn = dt.ToShortTimeString();
         //String data = elecDatatoSend.Text;
         //elecsport.Write(data + "\r\n");
         Thread.Sleep(50);
         elecsport.ReadExisting();
         //electxtReceive.AppendText("[" + dtn + "] " + "Sent: " + data + "\n");
     }
     catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
 }
 public string GetIpAddress(SerialPort serialPort1)              //获取本机ip地址
 {
     int FrontPosition, BackPosition;
     string Flag, Result;
     serialPort1.Write("AT^IPINIT?\r");
     do
     {
         Thread.Sleep(60);
         Flag = serialPort1.ReadExisting();
     }
     while (Flag == "" || Flag == "\r\n^DSDORMANT:0\r\n\r\n" || Flag == "\r\n^DSDORMANT:1\r\n\r\n");  //申请ip后需要排除的“休眠”指令,下同
     FrontPosition = Flag.IndexOf(",");
     BackPosition = Flag.IndexOf(",", FrontPosition + 1);
     return Result = Flag.Substring(FrontPosition + 1, BackPosition - FrontPosition - 1);
 }
Exemple #43
0
        private void OnReceived(object sender, SerialDataReceivedEventArgs c)
        {
            try
            {
                // write out text coming back from the arduino
                MethodInvoker invoker = new MethodInvoker(delegate()
                                                          { responseTextBox.Text += _arduinoSerialPort.ReadExisting(); });

                Invoke(invoker);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
            }
        }
Exemple #44
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.");
      }
 
    
  }
 public bool InitialConnection(SerialPort serialPort1)           //初始化链接,申请ip地址
 {
     int FrontPosition, BackPosition;
     string Flag, Result;
     serialPort1.Write("AT^IPINIT\r");
     do
     {
         Thread.Sleep(3000);     //因ip申请时间具有不确定性,不一定能够一次得到结果
         Flag = serialPort1.ReadExisting();
     }
     while (Flag == "");
     FrontPosition = Flag.IndexOf("\r\n");
     BackPosition = Flag.LastIndexOf("\r\n");
     Result = Flag.Substring(FrontPosition + 2, BackPosition - FrontPosition - 2);
     return Result == "OK" ? true : false;
 }
 public bool StopEcho(SerialPort serialPort1)                    //关闭回显
 {
     int FrontPosition, BackPosition;
     string Flag, Result;
     serialPort1.Write("ATE0\r");
     do
     {
         Thread.Sleep(50);
         Flag = serialPort1.ReadExisting();
     }
     while (Flag == "");
     FrontPosition = Flag.IndexOf("\r\n");
     BackPosition = Flag.LastIndexOf("\r\n");
     Result = Flag.Substring(FrontPosition + 2, BackPosition - FrontPosition - 2);
     return Result == "OK" ? true : false;
 }
 public bool AtDetection(SerialPort serialPort1)                 //AT检测
 {
     int FrontPosition, BackPosition;
     string Flag, Result;
     serialPort1.Write("AT\r");
     do
     {
         Thread.Sleep(50);     //延时50ms,确保在正常情况下可以一次收到所需数据,下同(详见指令响应时间测试)
         Flag = serialPort1.ReadExisting();
     }
     while (Flag == "");    //无反馈信息则等待
     FrontPosition = Flag.IndexOf("\r\n");     //获取需要的信息的位置
     BackPosition = Flag.LastIndexOf("\r\n");
     Result = Flag.Substring(FrontPosition + 2, BackPosition - FrontPosition - 2);  //得到有用的信息
     return Result == "OK" ? true : false;
 }
        private void ReadSingle_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                elecsport.Write(elecreadchratecmd + "\r\n");
                Thread.Sleep(50);
                var chratedata = elecsport.ReadExisting();

                MessageBox.Show(chratedata.ToString(), "Single Read Output");

                var cchhrate = Convert.ToDouble(Regex.Split(chratedata, ";")[5]);

                MessageBox.Show(cchhrate.ToString(), "Charge rate Read Output");
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
        }
Exemple #49
0
        private void buttonCOMON_Click(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            string query = "*9999-0#";
            foreach (string port in ports)
            {
                SerialPort p = new SerialPort();
                p.BaudRate = 9600;
                p.PortName = port;
                try
                {
                    p.Open();
                    if (p.IsOpen)
                    {
                        p.Write(query);
                        string s;

                        Thread.Sleep(500);
                        s = p.ReadExisting();
                        p.Close();
                        try
                        {
                            if (s.Contains("<ident:"))
                            {
                                int i = s.IndexOf("<ident:");
                                s = s.Substring(i + 7);
                                i = s.IndexOf(">");
                                s = s.Substring(0, i);
                                if (s == "BORIS")
                                {
                                    serialPort1.PortName = port;
                                    serialPort1.Open();
                                }

                            }
                        }
                        catch { }
                    }
                }
                catch (Exception ex)
                {
                    ;
                }
            }
        }
Exemple #50
0
        public bool CheckExistingModemOnComPort(SerialPort serialPort)
        {
            if ((serialPort == null) || !serialPort.IsOpen)
                return false;

            // Commands for modem checking
            string[] modemCommands = new string[] { "AT",       // Check connected modem. After 'AT' command some modems autobaud their speed.
                                            "ATQ0" };   // Switch on confirmations
            serialPort.DtrEnable = true;    // Set Data Terminal Ready (DTR) signal 
            serialPort.RtsEnable = true;    // Set Request to Send (RTS) signal

            string answer = "";
            bool retOk = false;
            for (int rtsInd = 0; rtsInd < 2; rtsInd++)
            {
                foreach (string command in modemCommands)
                {
                    serialPort.Write(command + serialPort.NewLine);
                    retOk = false;
                    answer = "";
                    int timeout = (command == "AT") ? 10 : 20;

                    // Waiting for response 1-2 sec
                    for (int i = 0; i < timeout; i++)
                    {
                        Thread.Sleep(100);
                        answer += serialPort.ReadExisting();
                        if (answer.IndexOf("OK") >= 0)
                        {
                            retOk = true;
                            break;
                        }
                    }
                }
                // If got responses, we found a modem
                if (retOk)
                    return true;

                // Trying to execute the commands without RTS
                serialPort.RtsEnable = false;
            }
            return false;
        }
        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();
                }
            }
        }
        private void StartListening(string portName)
        {
            btnStart.Enabled = false;
            btnStop.Enabled = true;

            m_SerialPort = new SerialPort(portName);
            m_SerialPort.DataReceived += (sender, args) =>
            {
                string text = m_SerialPort.ReadExisting();

                if (text != null)
                {
                    text = Regex.Replace(text, @"[^\d\r\n]", string.Empty);

                    m_Sync.Invoke(new Action<string>((data) =>
                    {
                        SendKeys.Send(data);
                    }), new object[] { text });
                }
            };
            m_SerialPort.Open();
        }
Exemple #53
0
        public bool open()
        {
            serial_port = new SerialPort();
            //good to enahce so searches for Cube COM3, COM4, etc, etc.
            serial_port.PortName = "COM3";
            serial_port.BaudRate = 38400;
            serial_port.RtsEnable = true;
            serial_port.ReadTimeout = 500;
            bool temp_result = false;
            for (int comport_number = 3; comport_number < 10; comport_number++)
            {
                serial_port.Close();
                serial_port.PortName = "COM" + comport_number.ToString();
                try
                {
                    Console.WriteLine("==================================================");
                    Console.WriteLine("Try connect Cube on COM" + comport_number.ToString());
                    serial_port.Open();
                    Console.WriteLine("Open Port OK: waiting for  {whoareyou} responce ");
                    serial_port.Write("{whoareyou}");
                    // serial_port.Write("{000FF00FF}");
                    Thread.Sleep(250); // have to wait for responce from cube
                    String reply_from_cube = serial_port.ReadExisting();
                    Console.WriteLine("reply from device");
                    Console.Write(reply_from_cube);
                    if (reply_from_cube.IndexOf("cubeofleds") < 0)
                    {
                        Console.WriteLine("this is not the cube");
                    }
                    else
                    {
                        Console.WriteLine("Cube Found: OK");
                        temp_result = true;
                        connected = true;
                        break;
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Connection: FAILED");
                    Console.WriteLine(ex.Message);
                }

            }
            Console.WriteLine("==================================================");
            return temp_result;
        }
        // Creates the event ArduinoAvailable if any Arduino has been found that is ready to connect.
        // Caution, contains long operation / Thread.Sleep(ArduinoResetTime);
        public static bool CheckArduinoAvailable(string comPort)
        {
            if (!NamesAndPorts.Values.Contains(comPort) && SerialPort.GetPortNames().Contains(comPort))
            {
                SerialPort sp = new SerialPort(comPort);

                sp.BaudRate = BaudRate;
                sp.DtrEnable = true;

                if (!sp.IsOpen)
                {
                    string read = "";
                    string name = "";

                    try
                    {
                        // Caution, long operation!
                        sp.Open();
                        GC.SuppressFinalize(sp.BaseStream); // Again f**********ck you Microsoft
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(comPort);
                        sp.Close();
                        sp.Dispose();
                        return false;
                    }

                    Thread.Sleep(ArduinoResetTime);

                    try
                    {
                        read = sp.ReadExisting();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        return false;
                    }

                    Console.WriteLine(read);

                    // Format names
                    if (read.StartsWith("Name<") && read.EndsWith(">;"))
                    {
                        name = read.Substring(5, read.Length - 7);
                    }
                    else
                    {
                        return false;
                    }

                    // Only send event if the name is not empty and is not already connected
                    if (name != "" && !NamesAndPorts.Keys.Contains(name) && sp.IsOpen)
                    {
                        // Create the event.
                        RaiseArduinoAvailable(new KeyValuePair<string, string>(name, comPort), sp);
                        return true;
                    }
                }
            }

            return false;
        }
        private void Window_Initialized(object sender, EventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
            this.Title = "Text Terminal ver 0.6";// +WpfTerm1.Args.args.ToString();
            if (args[1] != null)
            {
                this.Title += (" {" + args[1] + "}");
                strComPort = args[1];
            }
            else
            {
                this.Title = "Error: No COM port available";
                return;
            }

            // init BaudRate combobox
            comboBoxSpd.Items.Add("4800");
            comboBoxSpd.Items.Add("9600");
            comboBoxSpd.Items.Add("19200");
            comboBoxSpd.Items.Add("57600");
            comboBoxSpd.Items.Add("115200");

            if (args[2] != null)
            {
                this.Title += (" {" + args[2] + "}");
                switch (args[2]) {
                    case "4800":
                        comboBoxSpd.SelectedIndex = 0;
                        iBaudRate = 4800;
                        break;
                    case "9600":
                        comboBoxSpd.SelectedIndex = 1;
                        iBaudRate = 9600;
                        break;
                    case "19200":
                        comboBoxSpd.SelectedIndex = 2;
                        iBaudRate = 19200;
                        break;
                    case "57600":
                        comboBoxSpd.SelectedIndex = 3;
                        iBaudRate = 57600;
                        break;
                    case "115200":
                        comboBoxSpd.SelectedIndex = 4;
                        iBaudRate = 115200;
                        break;
                    default:
                        this.Title = "Error : Baud rate not supported.";
                        btnSend.IsEnabled = false;
                        return;
                        break;
                }

            }

            textBoxRead.FontSize = 20;
            //serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
            serial = new SerialPort(strComPort, iBaudRate, Parity.None, 8, StopBits.One);
            serial.DataReceived += OnDataReceived;
            try {
                serial.Open();
                serial.DtrEnable = true; // reset arudino
                System.Threading.Thread.Sleep(100); // wait a little
                serial.ReadExisting();// flush existing garbage data.
                bIsStarted = true;
                //textBoxRead.Clear();
            }
            catch (Exception ee)
            {

            }

            //textBoxRead.AppendText("COM35 opened");
            //ConsoleHelper.AllocConsole();

        }
        private void UploadNowBtn_Click(object sender, EventArgs e)
        {
            uploadInProgress = true;
            // Verify that a valid file path has been entered. If a path is present in the box it is already validated so
            // there is no need to do any further validation.
            if (HexFilePathTB.Text.Length == 0)
            {
                MessageBox.Show("You must select the path to the desired Hex file in order to perform upload.", "File Path Error");
                return;
            }

            // Perform the upload...
            bool uploadSuccess = false;
            try
            {
                this.Cursor = Cursors.WaitCursor;

                // Initialize ds30 Loader engine
                {
                    string strBasePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                    bool bds30LoaderInitializeResult = false;

                    clsds30Loader.Initialize(strBasePath, ref bds30LoaderInitializeResult);

                    if (bds30LoaderInitializeResult == false)
                    {
                        MessageBox.Show("Failed to initialize ds30 Loader.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        this.Cursor = Cursors.Default;
                        return;
                    }
                }
                // Get device object
                clsDevice objDevice = clsDeviceDb.DeviceGet("PIC24HJ128GP204");

                if (objDevice == null)
                {
                    MessageBox.Show("Unknown device, write aborted.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.Cursor = Cursors.Default;
                    return;
                }
                // Parse hex file
                //clsHex18F objHex = new clsHex18F( "serlcd.hex" );

                clsHex objHex = (fileIsAutoDownloaded) ? new clsHex(hexFileDestPath) : new clsHex(HexFilePathTB.Text);
                {
                    bool bParseResult = false;
                    clsParseSettings objParseSettings = new clsParseSettings();

                    objHex.HexFileValidate += new clsHex.HexFileValidateDelegate(objHex_HexFileValidate);
                    objHex.HexFileParse += new clsHex.HexFileParseDelegate(objHex_HexFileParse);

                    objParseSettings.device = objDevice;
                    objHex.ParseHexFile(objParseSettings, false, 0, ref bParseResult);

                    if (bParseResult == false)
                    {
                        MessageBox.Show("Parse of hex file failed, write process aborted.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        this.Cursor = Cursors.Default;
                        return;
                    }
                }
                // Download
                {
                    bool bDownloadResult = false;
                    myFocuser.Action("ForceHubDisconnect", "");
                    clsWriteSettings objDownloadSettings = new clsWriteSettings();
                    objDownloadSettings.portName = myFocuser.Action("GetCOMPortName", "");
                    objDownloadSettings.writeProgram = true;
                    objDownloadSettings.baudRate = 115200;
                    switch (TimeoutCB.Text)
                    {
                        default:
                        case "10 Sec":
                            objDownloadSettings.timeout = 10000;
                            break;
                        case "30 Sec":
                            objDownloadSettings.timeout = 30000;
                            break;
                        case "60 Sec":
                            objDownloadSettings.timeout = 60000;
                            break;
                    }
                    MessageBox.Show("Press 'OK' and then cycle the power to the FocusLynx device before the timeout period expires.",
                        "Bootloader", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtInfo.Text += "Waiting for device power cycle..." + Environment.NewLine;

                    //************************************************************************************************************************
                    // Before we start the write we have to make sure any garbage that is output form the device at power up is discarded first
                    //
                    using (SerialPort tempPort = new SerialPort(objDownloadSettings.portName, objDownloadSettings.baudRate))   // use same settigs as bootloader
                    {
                        tempPort.Open();
                        tempPort.DiscardInBuffer();
                        tempPort.DiscardOutBuffer();
                        string junk = tempPort.ReadExisting();
                        DateTime startTime = DateTime.UtcNow;
                        while (DateTime.UtcNow.Subtract(startTime).TotalMilliseconds < (objDownloadSettings.timeout - 2000))
                        {
                            if (tempPort.BytesToRead > 0)
                            {
                                System.Threading.Thread.Sleep(1000);     // Pause while the serial transciever powers up...
                                break;
                            }
                        }
                        EventLogger.LogMessage("Bootloader discarding " + tempPort.BytesToRead + " bytes of junk before bootload", TraceLevel.Info);
                        junk = tempPort.ReadExisting();
                        tempPort.DiscardInBuffer();
                        tempPort.Close();
                    }
                    //*************************************************************************************************************************

                    // Now it is okay to start the download
                    clsds30Loader.Write(objDevice, objHex, objDownloadSettings, 0, ref bDownloadResult);

                    if (bDownloadResult == false)
                    {
                        MessageBox.Show("Write failed", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        this.Cursor = Cursors.Default;
                        uploadSuccess = false;
                        return;
                    }
                    else
                    {
                        uploadSuccess = true;

                        // Delete the autodownloaded file
                        if (fileIsAutoDownloaded)
                        {
                            try
                            {
                                File.Delete(hexFileDestPath);
                                txtInfo.Text += "Temporary hex file removed" + Environment.NewLine;
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred during firmware upload. " + ex.Message, "Error");
            }
            finally
            {
                uploadInProgress = false;
                this.Cursor = Cursors.Default;
            }
            if (uploadSuccess)
            {
                MessageBox.Show("The device firmware has been successfully upgraded!", "Upload Complete");
                // Close the form.
                //this.Close();
            }
            else
            {
                // Leave the form open incase they want to attempt the upload again.
            }
        }
        public void Work()
        {
            while (!_stop)
            {
                try
                {
                    foreach (var tmpPortName in SerialPort.GetPortNames())
                    {
                        _serialPort = new SerialPort
                        {
                            PortName = tmpPortName,
                            BaudRate = 9600,
                            StopBits = StopBits.One,
                            Parity = Parity.None,
                            DataBits = 8,
                            DtrEnable = false,
                            ReadTimeout = 200
                        };

                        _serialPort.Open();
                        _serialPort.ReadExisting();

                        Write();
                        Thread.Sleep(500);

                        if (_serialPort.BytesToRead != 24)
                            _serialPort.Close();
                    }

                    if (!_serialPort.IsOpen)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    Write(6);
                    _serialPort.ReadExisting();

                    for (byte i = 1; i <= 4; ++i)
                        _filterBuffer[i] = new Queue<Vector3D>();

                    for (int j = 0; j < Settings.Default.FilterLength; ++j)
                    {
                        Write();

                        for (byte i = 1; i <= 4; ++i)
                            _filterBuffer[i].Enqueue(Read());
                    }

                    for (byte i = 1; i <= 4; ++i)
                        _offset[i] = Filter(_filterBuffer[i]);

                    Write(5);

                    while (!_stop)
                    {
                        Write();

                        for (byte i = 1; i <= 4; ++i)
                            Changed(this, new CompassEventArgs(i, Filter(_filterBuffer[i]) - _offset[i]));

                        for (byte i = 1; i <= 4; ++i)
                        {
                            _filterBuffer[i].Dequeue();
                            _filterBuffer[i].Enqueue(Read());
                        }
                    }

                    Write(6);
                }
                catch (Exception)
                {
                    if (_serialPort != null && _serialPort.IsOpen)
                        _serialPort.Close();
                }
            }

            if (_serialPort != null && _serialPort.IsOpen)
                _serialPort.Close();
        }
        static void Main(string[] args)
        {
            string result;
            int end = 0;
            SerialPort sp = new SerialPort("COM2");
            sp.BaudRate = 115200; // 56700;
            sp.NewLine = "\r\n";
            sp.Open();
            sendCommand(sp, "AT+RST", eWaitFor.eOK);
            Thread.Sleep(1000);
            sendCommand(sp, "AT+CWJAP=\"\",\"\"", eWaitFor.eOK | eWaitFor.eFAIL);
            Thread.Sleep(1000);
            sendCommand(sp, "AT+CWMODE=1", eWaitFor.eOK | eWaitFor.eNoChange);
            Thread.Sleep(1000);
            //sendCommand(sp, "AT+CWJAP=\"CBA_F1\",\"abc\"", eWaitFor.eOK);
            //sendCommand(sp, "AT+CWJAP=\"LumiaTk5276\",\"abc\"", eWaitFor.eOK);
            sendCommand(sp, "AT+CWJAP=\"edup-rt\",\"abc\"", eWaitFor.eOK);

            Thread.Sleep(1000);
            Console.WriteLine("IP: " + getIP(sp));
            sendCommand(sp, "AT+CIPMUX=1", eWaitFor.eOK);
            sendCommand(sp, "AT+CIPSTART=4,\"TCP\",\"google.com\",80", eWaitFor.eOK);
            sendCommand(sp, "AT+CIPSEND=4,18", eWaitFor.eGT);
            sp.Write("GET / HTTP/1.0\r\n\r\n");
            Thread.Sleep(5000); //Czekamy tu na internet
            result = sp.ReadExisting();
            Console.WriteLine(result);

            //sp.WriteLine("AT+CIFSR");
            //result = sp.ReadTo("OK\r");

            sp.Close();
        }
 private static eWaitFor sendCommand(SerialPort sp, string cmd, eWaitFor wf)
 {
     string tmp;
     int sendcnt = 0;
     while (true) {
         do {
             tmp = sp.ReadExisting();
             Console.WriteLine(tmp);
         } while (tmp != "");
         Console.WriteLine("SENDING : " + (++sendcnt).ToString());
         sp.WriteLine(cmd);
         Thread.Sleep(1000);
         string result;
         int end = 0, findMsg = 0, retrycnt = 10;
         while ( (findMsg == 0 || end == 0 ) && retrycnt-- > 0) {
             Thread.Sleep(2000);
             result = sp.ReadExisting();
             if (result.Contains(cmd)) findMsg = 1;
             Console.WriteLine(result);
             if (((wf & eWaitFor.eFAIL) != 0) && findMsg != 0 && ( result.Contains("FAIL") || result.Contains("ERROR"))) return eWaitFor.eFAIL;
             else if (((wf & eWaitFor.eOK) != 0) && findMsg != 0 && result.Contains("OK")) return eWaitFor.eOK;
             else if (((wf & eWaitFor.eNoChange) != 0) && findMsg != 0 && result.Contains("no change")) return eWaitFor.eNoChange;
             else if (((wf & eWaitFor.eGT) != 0) && findMsg != 0 && result.Contains(">")) return eWaitFor.eGT;
         }
         Thread.Sleep(5000);
     }
 }
Exemple #60
0
 public string ReadResponse(SerialPort port, int timeout)
 {
     string buffer = string.Empty;
     try
     {
         do
         {
             if (receiveNow.WaitOne(timeout, false))
             {
                 string t = port.ReadExisting();
                 buffer += t;
             }
             else
             {
                 if (buffer.Length > 0)
                     throw new ApplicationException("Response received is incomplete.");
                 else
                     throw new ApplicationException("No data received from phone.");
             }
         }
         while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
     }
     catch (Exception ex)
     {
         throw ex;
     }
     return buffer;
 }